##// END OF EJS Templates
unify encode/decode filter routines
Matt Mackall -
r4004:c83c35f2 default
parent child Browse files
Show More
@@ -1,1877 +1,1866 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository 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
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import *
8 from node import *
9 from i18n import _
9 from i18n import _
10 import repo, appendfile, changegroup
10 import repo, appendfile, changegroup
11 import changelog, dirstate, filelog, manifest, context
11 import changelog, dirstate, filelog, manifest, context
12 import re, lock, transaction, tempfile, stat, mdiff, errno, ui
12 import re, lock, transaction, tempfile, stat, mdiff, errno, ui
13 import os, revlog, time, util
13 import os, revlog, time, util
14
14
15 class localrepository(repo.repository):
15 class localrepository(repo.repository):
16 capabilities = ('lookup', 'changegroupsubset')
16 capabilities = ('lookup', 'changegroupsubset')
17 supported = ('revlogv1', 'store')
17 supported = ('revlogv1', 'store')
18
18
19 def __del__(self):
19 def __del__(self):
20 self.transhandle = None
20 self.transhandle = None
21 def __init__(self, parentui, path=None, create=0):
21 def __init__(self, parentui, path=None, create=0):
22 repo.repository.__init__(self)
22 repo.repository.__init__(self)
23 if not path:
23 if not path:
24 p = os.getcwd()
24 p = os.getcwd()
25 while not os.path.isdir(os.path.join(p, ".hg")):
25 while not os.path.isdir(os.path.join(p, ".hg")):
26 oldp = p
26 oldp = p
27 p = os.path.dirname(p)
27 p = os.path.dirname(p)
28 if p == oldp:
28 if p == oldp:
29 raise repo.RepoError(_("There is no Mercurial repository"
29 raise repo.RepoError(_("There is no Mercurial repository"
30 " here (.hg not found)"))
30 " here (.hg not found)"))
31 path = p
31 path = p
32
32
33 self.path = os.path.join(path, ".hg")
33 self.path = os.path.join(path, ".hg")
34 self.root = os.path.realpath(path)
34 self.root = os.path.realpath(path)
35 self.origroot = path
35 self.origroot = path
36 self.opener = util.opener(self.path)
36 self.opener = util.opener(self.path)
37 self.wopener = util.opener(self.root)
37 self.wopener = util.opener(self.root)
38
38
39 if not os.path.isdir(self.path):
39 if not os.path.isdir(self.path):
40 if create:
40 if create:
41 if not os.path.exists(path):
41 if not os.path.exists(path):
42 os.mkdir(path)
42 os.mkdir(path)
43 os.mkdir(self.path)
43 os.mkdir(self.path)
44 os.mkdir(os.path.join(self.path, "store"))
44 os.mkdir(os.path.join(self.path, "store"))
45 requirements = ("revlogv1", "store")
45 requirements = ("revlogv1", "store")
46 reqfile = self.opener("requires", "w")
46 reqfile = self.opener("requires", "w")
47 for r in requirements:
47 for r in requirements:
48 reqfile.write("%s\n" % r)
48 reqfile.write("%s\n" % r)
49 reqfile.close()
49 reqfile.close()
50 # create an invalid changelog
50 # create an invalid changelog
51 self.opener("00changelog.i", "a").write(
51 self.opener("00changelog.i", "a").write(
52 '\0\0\0\2' # represents revlogv2
52 '\0\0\0\2' # represents revlogv2
53 ' dummy changelog to prevent using the old repo layout'
53 ' dummy changelog to prevent using the old repo layout'
54 )
54 )
55 else:
55 else:
56 raise repo.RepoError(_("repository %s not found") % path)
56 raise repo.RepoError(_("repository %s not found") % path)
57 elif create:
57 elif create:
58 raise repo.RepoError(_("repository %s already exists") % path)
58 raise repo.RepoError(_("repository %s already exists") % path)
59 else:
59 else:
60 # find requirements
60 # find requirements
61 try:
61 try:
62 requirements = self.opener("requires").read().splitlines()
62 requirements = self.opener("requires").read().splitlines()
63 except IOError, inst:
63 except IOError, inst:
64 if inst.errno != errno.ENOENT:
64 if inst.errno != errno.ENOENT:
65 raise
65 raise
66 requirements = []
66 requirements = []
67 # check them
67 # check them
68 for r in requirements:
68 for r in requirements:
69 if r not in self.supported:
69 if r not in self.supported:
70 raise repo.RepoError(_("requirement '%s' not supported") % r)
70 raise repo.RepoError(_("requirement '%s' not supported") % r)
71
71
72 # setup store
72 # setup store
73 if "store" in requirements:
73 if "store" in requirements:
74 self.encodefn = util.encodefilename
74 self.encodefn = util.encodefilename
75 self.decodefn = util.decodefilename
75 self.decodefn = util.decodefilename
76 self.spath = os.path.join(self.path, "store")
76 self.spath = os.path.join(self.path, "store")
77 else:
77 else:
78 self.encodefn = lambda x: x
78 self.encodefn = lambda x: x
79 self.decodefn = lambda x: x
79 self.decodefn = lambda x: x
80 self.spath = self.path
80 self.spath = self.path
81 self.sopener = util.encodedopener(util.opener(self.spath), self.encodefn)
81 self.sopener = util.encodedopener(util.opener(self.spath), self.encodefn)
82
82
83 self.ui = ui.ui(parentui=parentui)
83 self.ui = ui.ui(parentui=parentui)
84 try:
84 try:
85 self.ui.readconfig(self.join("hgrc"), self.root)
85 self.ui.readconfig(self.join("hgrc"), self.root)
86 except IOError:
86 except IOError:
87 pass
87 pass
88
88
89 v = self.ui.configrevlog()
89 v = self.ui.configrevlog()
90 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
90 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
91 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
91 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
92 fl = v.get('flags', None)
92 fl = v.get('flags', None)
93 flags = 0
93 flags = 0
94 if fl != None:
94 if fl != None:
95 for x in fl.split():
95 for x in fl.split():
96 flags |= revlog.flagstr(x)
96 flags |= revlog.flagstr(x)
97 elif self.revlogv1:
97 elif self.revlogv1:
98 flags = revlog.REVLOG_DEFAULT_FLAGS
98 flags = revlog.REVLOG_DEFAULT_FLAGS
99
99
100 v = self.revlogversion | flags
100 v = self.revlogversion | flags
101 self.manifest = manifest.manifest(self.sopener, v)
101 self.manifest = manifest.manifest(self.sopener, v)
102 self.changelog = changelog.changelog(self.sopener, v)
102 self.changelog = changelog.changelog(self.sopener, v)
103
103
104 fallback = self.ui.config('ui', 'fallbackencoding')
104 fallback = self.ui.config('ui', 'fallbackencoding')
105 if fallback:
105 if fallback:
106 util._fallbackencoding = fallback
106 util._fallbackencoding = fallback
107
107
108 # the changelog might not have the inline index flag
108 # the changelog might not have the inline index flag
109 # on. If the format of the changelog is the same as found in
109 # on. If the format of the changelog is the same as found in
110 # .hgrc, apply any flags found in the .hgrc as well.
110 # .hgrc, apply any flags found in the .hgrc as well.
111 # Otherwise, just version from the changelog
111 # Otherwise, just version from the changelog
112 v = self.changelog.version
112 v = self.changelog.version
113 if v == self.revlogversion:
113 if v == self.revlogversion:
114 v |= flags
114 v |= flags
115 self.revlogversion = v
115 self.revlogversion = v
116
116
117 self.tagscache = None
117 self.tagscache = None
118 self.branchcache = None
118 self.branchcache = None
119 self.nodetagscache = None
119 self.nodetagscache = None
120 self.encodepats = None
120 self.filterpats = {}
121 self.decodepats = None
122 self.transhandle = None
121 self.transhandle = None
123
122
124 self._link = lambda x: False
123 self._link = lambda x: False
125 if util.checklink(self.root):
124 if util.checklink(self.root):
126 r = self.root # avoid circular reference in lambda
125 r = self.root # avoid circular reference in lambda
127 self._link = lambda x: util.is_link(os.path.join(r, x))
126 self._link = lambda x: util.is_link(os.path.join(r, x))
128
127
129 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
128 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
130
129
131 def url(self):
130 def url(self):
132 return 'file:' + self.root
131 return 'file:' + self.root
133
132
134 def hook(self, name, throw=False, **args):
133 def hook(self, name, throw=False, **args):
135 def callhook(hname, funcname):
134 def callhook(hname, funcname):
136 '''call python hook. hook is callable object, looked up as
135 '''call python hook. hook is callable object, looked up as
137 name in python module. if callable returns "true", hook
136 name in python module. if callable returns "true", hook
138 fails, else passes. if hook raises exception, treated as
137 fails, else passes. if hook raises exception, treated as
139 hook failure. exception propagates if throw is "true".
138 hook failure. exception propagates if throw is "true".
140
139
141 reason for "true" meaning "hook failed" is so that
140 reason for "true" meaning "hook failed" is so that
142 unmodified commands (e.g. mercurial.commands.update) can
141 unmodified commands (e.g. mercurial.commands.update) can
143 be run as hooks without wrappers to convert return values.'''
142 be run as hooks without wrappers to convert return values.'''
144
143
145 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
144 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
146 d = funcname.rfind('.')
145 d = funcname.rfind('.')
147 if d == -1:
146 if d == -1:
148 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
147 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
149 % (hname, funcname))
148 % (hname, funcname))
150 modname = funcname[:d]
149 modname = funcname[:d]
151 try:
150 try:
152 obj = __import__(modname)
151 obj = __import__(modname)
153 except ImportError:
152 except ImportError:
154 try:
153 try:
155 # extensions are loaded with hgext_ prefix
154 # extensions are loaded with hgext_ prefix
156 obj = __import__("hgext_%s" % modname)
155 obj = __import__("hgext_%s" % modname)
157 except ImportError:
156 except ImportError:
158 raise util.Abort(_('%s hook is invalid '
157 raise util.Abort(_('%s hook is invalid '
159 '(import of "%s" failed)') %
158 '(import of "%s" failed)') %
160 (hname, modname))
159 (hname, modname))
161 try:
160 try:
162 for p in funcname.split('.')[1:]:
161 for p in funcname.split('.')[1:]:
163 obj = getattr(obj, p)
162 obj = getattr(obj, p)
164 except AttributeError, err:
163 except AttributeError, err:
165 raise util.Abort(_('%s hook is invalid '
164 raise util.Abort(_('%s hook is invalid '
166 '("%s" is not defined)') %
165 '("%s" is not defined)') %
167 (hname, funcname))
166 (hname, funcname))
168 if not callable(obj):
167 if not callable(obj):
169 raise util.Abort(_('%s hook is invalid '
168 raise util.Abort(_('%s hook is invalid '
170 '("%s" is not callable)') %
169 '("%s" is not callable)') %
171 (hname, funcname))
170 (hname, funcname))
172 try:
171 try:
173 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
172 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
174 except (KeyboardInterrupt, util.SignalInterrupt):
173 except (KeyboardInterrupt, util.SignalInterrupt):
175 raise
174 raise
176 except Exception, exc:
175 except Exception, exc:
177 if isinstance(exc, util.Abort):
176 if isinstance(exc, util.Abort):
178 self.ui.warn(_('error: %s hook failed: %s\n') %
177 self.ui.warn(_('error: %s hook failed: %s\n') %
179 (hname, exc.args[0]))
178 (hname, exc.args[0]))
180 else:
179 else:
181 self.ui.warn(_('error: %s hook raised an exception: '
180 self.ui.warn(_('error: %s hook raised an exception: '
182 '%s\n') % (hname, exc))
181 '%s\n') % (hname, exc))
183 if throw:
182 if throw:
184 raise
183 raise
185 self.ui.print_exc()
184 self.ui.print_exc()
186 return True
185 return True
187 if r:
186 if r:
188 if throw:
187 if throw:
189 raise util.Abort(_('%s hook failed') % hname)
188 raise util.Abort(_('%s hook failed') % hname)
190 self.ui.warn(_('warning: %s hook failed\n') % hname)
189 self.ui.warn(_('warning: %s hook failed\n') % hname)
191 return r
190 return r
192
191
193 def runhook(name, cmd):
192 def runhook(name, cmd):
194 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
193 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
195 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
194 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
196 r = util.system(cmd, environ=env, cwd=self.root)
195 r = util.system(cmd, environ=env, cwd=self.root)
197 if r:
196 if r:
198 desc, r = util.explain_exit(r)
197 desc, r = util.explain_exit(r)
199 if throw:
198 if throw:
200 raise util.Abort(_('%s hook %s') % (name, desc))
199 raise util.Abort(_('%s hook %s') % (name, desc))
201 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
200 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
202 return r
201 return r
203
202
204 r = False
203 r = False
205 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
204 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
206 if hname.split(".", 1)[0] == name and cmd]
205 if hname.split(".", 1)[0] == name and cmd]
207 hooks.sort()
206 hooks.sort()
208 for hname, cmd in hooks:
207 for hname, cmd in hooks:
209 if cmd.startswith('python:'):
208 if cmd.startswith('python:'):
210 r = callhook(hname, cmd[7:].strip()) or r
209 r = callhook(hname, cmd[7:].strip()) or r
211 else:
210 else:
212 r = runhook(hname, cmd) or r
211 r = runhook(hname, cmd) or r
213 return r
212 return r
214
213
215 tag_disallowed = ':\r\n'
214 tag_disallowed = ':\r\n'
216
215
217 def tag(self, name, node, message, local, user, date):
216 def tag(self, name, node, message, local, user, date):
218 '''tag a revision with a symbolic name.
217 '''tag a revision with a symbolic name.
219
218
220 if local is True, the tag is stored in a per-repository file.
219 if local is True, the tag is stored in a per-repository file.
221 otherwise, it is stored in the .hgtags file, and a new
220 otherwise, it is stored in the .hgtags file, and a new
222 changeset is committed with the change.
221 changeset is committed with the change.
223
222
224 keyword arguments:
223 keyword arguments:
225
224
226 local: whether to store tag in non-version-controlled file
225 local: whether to store tag in non-version-controlled file
227 (default False)
226 (default False)
228
227
229 message: commit message to use if committing
228 message: commit message to use if committing
230
229
231 user: name of user to use if committing
230 user: name of user to use if committing
232
231
233 date: date tuple to use if committing'''
232 date: date tuple to use if committing'''
234
233
235 for c in self.tag_disallowed:
234 for c in self.tag_disallowed:
236 if c in name:
235 if c in name:
237 raise util.Abort(_('%r cannot be used in a tag name') % c)
236 raise util.Abort(_('%r cannot be used in a tag name') % c)
238
237
239 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
238 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
240
239
241 if local:
240 if local:
242 # local tags are stored in the current charset
241 # local tags are stored in the current charset
243 self.opener('localtags', 'a').write('%s %s\n' % (hex(node), name))
242 self.opener('localtags', 'a').write('%s %s\n' % (hex(node), name))
244 self.hook('tag', node=hex(node), tag=name, local=local)
243 self.hook('tag', node=hex(node), tag=name, local=local)
245 return
244 return
246
245
247 for x in self.status()[:5]:
246 for x in self.status()[:5]:
248 if '.hgtags' in x:
247 if '.hgtags' in x:
249 raise util.Abort(_('working copy of .hgtags is changed '
248 raise util.Abort(_('working copy of .hgtags is changed '
250 '(please commit .hgtags manually)'))
249 '(please commit .hgtags manually)'))
251
250
252 # committed tags are stored in UTF-8
251 # committed tags are stored in UTF-8
253 line = '%s %s\n' % (hex(node), util.fromlocal(name))
252 line = '%s %s\n' % (hex(node), util.fromlocal(name))
254 self.wfile('.hgtags', 'ab').write(line)
253 self.wfile('.hgtags', 'ab').write(line)
255 if self.dirstate.state('.hgtags') == '?':
254 if self.dirstate.state('.hgtags') == '?':
256 self.add(['.hgtags'])
255 self.add(['.hgtags'])
257
256
258 self.commit(['.hgtags'], message, user, date)
257 self.commit(['.hgtags'], message, user, date)
259 self.hook('tag', node=hex(node), tag=name, local=local)
258 self.hook('tag', node=hex(node), tag=name, local=local)
260
259
261 def tags(self):
260 def tags(self):
262 '''return a mapping of tag to node'''
261 '''return a mapping of tag to node'''
263 if not self.tagscache:
262 if not self.tagscache:
264 self.tagscache = {}
263 self.tagscache = {}
265
264
266 def parsetag(line, context):
265 def parsetag(line, context):
267 if not line:
266 if not line:
268 return
267 return
269 s = l.split(" ", 1)
268 s = l.split(" ", 1)
270 if len(s) != 2:
269 if len(s) != 2:
271 self.ui.warn(_("%s: cannot parse entry\n") % context)
270 self.ui.warn(_("%s: cannot parse entry\n") % context)
272 return
271 return
273 node, key = s
272 node, key = s
274 key = util.tolocal(key.strip()) # stored in UTF-8
273 key = util.tolocal(key.strip()) # stored in UTF-8
275 try:
274 try:
276 bin_n = bin(node)
275 bin_n = bin(node)
277 except TypeError:
276 except TypeError:
278 self.ui.warn(_("%s: node '%s' is not well formed\n") %
277 self.ui.warn(_("%s: node '%s' is not well formed\n") %
279 (context, node))
278 (context, node))
280 return
279 return
281 if bin_n not in self.changelog.nodemap:
280 if bin_n not in self.changelog.nodemap:
282 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
281 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
283 (context, key))
282 (context, key))
284 return
283 return
285 self.tagscache[key] = bin_n
284 self.tagscache[key] = bin_n
286
285
287 # read the tags file from each head, ending with the tip,
286 # read the tags file from each head, ending with the tip,
288 # and add each tag found to the map, with "newer" ones
287 # and add each tag found to the map, with "newer" ones
289 # taking precedence
288 # taking precedence
290 f = None
289 f = None
291 for rev, node, fnode in self._hgtagsnodes():
290 for rev, node, fnode in self._hgtagsnodes():
292 f = (f and f.filectx(fnode) or
291 f = (f and f.filectx(fnode) or
293 self.filectx('.hgtags', fileid=fnode))
292 self.filectx('.hgtags', fileid=fnode))
294 count = 0
293 count = 0
295 for l in f.data().splitlines():
294 for l in f.data().splitlines():
296 count += 1
295 count += 1
297 parsetag(l, _("%s, line %d") % (str(f), count))
296 parsetag(l, _("%s, line %d") % (str(f), count))
298
297
299 try:
298 try:
300 f = self.opener("localtags")
299 f = self.opener("localtags")
301 count = 0
300 count = 0
302 for l in f:
301 for l in f:
303 # localtags are stored in the local character set
302 # localtags are stored in the local character set
304 # while the internal tag table is stored in UTF-8
303 # while the internal tag table is stored in UTF-8
305 l = util.fromlocal(l)
304 l = util.fromlocal(l)
306 count += 1
305 count += 1
307 parsetag(l, _("localtags, line %d") % count)
306 parsetag(l, _("localtags, line %d") % count)
308 except IOError:
307 except IOError:
309 pass
308 pass
310
309
311 self.tagscache['tip'] = self.changelog.tip()
310 self.tagscache['tip'] = self.changelog.tip()
312
311
313 return self.tagscache
312 return self.tagscache
314
313
315 def _hgtagsnodes(self):
314 def _hgtagsnodes(self):
316 heads = self.heads()
315 heads = self.heads()
317 heads.reverse()
316 heads.reverse()
318 last = {}
317 last = {}
319 ret = []
318 ret = []
320 for node in heads:
319 for node in heads:
321 c = self.changectx(node)
320 c = self.changectx(node)
322 rev = c.rev()
321 rev = c.rev()
323 try:
322 try:
324 fnode = c.filenode('.hgtags')
323 fnode = c.filenode('.hgtags')
325 except revlog.LookupError:
324 except revlog.LookupError:
326 continue
325 continue
327 ret.append((rev, node, fnode))
326 ret.append((rev, node, fnode))
328 if fnode in last:
327 if fnode in last:
329 ret[last[fnode]] = None
328 ret[last[fnode]] = None
330 last[fnode] = len(ret) - 1
329 last[fnode] = len(ret) - 1
331 return [item for item in ret if item]
330 return [item for item in ret if item]
332
331
333 def tagslist(self):
332 def tagslist(self):
334 '''return a list of tags ordered by revision'''
333 '''return a list of tags ordered by revision'''
335 l = []
334 l = []
336 for t, n in self.tags().items():
335 for t, n in self.tags().items():
337 try:
336 try:
338 r = self.changelog.rev(n)
337 r = self.changelog.rev(n)
339 except:
338 except:
340 r = -2 # sort to the beginning of the list if unknown
339 r = -2 # sort to the beginning of the list if unknown
341 l.append((r, t, n))
340 l.append((r, t, n))
342 l.sort()
341 l.sort()
343 return [(t, n) for r, t, n in l]
342 return [(t, n) for r, t, n in l]
344
343
345 def nodetags(self, node):
344 def nodetags(self, node):
346 '''return the tags associated with a node'''
345 '''return the tags associated with a node'''
347 if not self.nodetagscache:
346 if not self.nodetagscache:
348 self.nodetagscache = {}
347 self.nodetagscache = {}
349 for t, n in self.tags().items():
348 for t, n in self.tags().items():
350 self.nodetagscache.setdefault(n, []).append(t)
349 self.nodetagscache.setdefault(n, []).append(t)
351 return self.nodetagscache.get(node, [])
350 return self.nodetagscache.get(node, [])
352
351
353 def _branchtags(self):
352 def _branchtags(self):
354 partial, last, lrev = self._readbranchcache()
353 partial, last, lrev = self._readbranchcache()
355
354
356 tiprev = self.changelog.count() - 1
355 tiprev = self.changelog.count() - 1
357 if lrev != tiprev:
356 if lrev != tiprev:
358 self._updatebranchcache(partial, lrev+1, tiprev+1)
357 self._updatebranchcache(partial, lrev+1, tiprev+1)
359 self._writebranchcache(partial, self.changelog.tip(), tiprev)
358 self._writebranchcache(partial, self.changelog.tip(), tiprev)
360
359
361 return partial
360 return partial
362
361
363 def branchtags(self):
362 def branchtags(self):
364 if self.branchcache is not None:
363 if self.branchcache is not None:
365 return self.branchcache
364 return self.branchcache
366
365
367 self.branchcache = {} # avoid recursion in changectx
366 self.branchcache = {} # avoid recursion in changectx
368 partial = self._branchtags()
367 partial = self._branchtags()
369
368
370 # the branch cache is stored on disk as UTF-8, but in the local
369 # the branch cache is stored on disk as UTF-8, but in the local
371 # charset internally
370 # charset internally
372 for k, v in partial.items():
371 for k, v in partial.items():
373 self.branchcache[util.tolocal(k)] = v
372 self.branchcache[util.tolocal(k)] = v
374 return self.branchcache
373 return self.branchcache
375
374
376 def _readbranchcache(self):
375 def _readbranchcache(self):
377 partial = {}
376 partial = {}
378 try:
377 try:
379 f = self.opener("branches.cache")
378 f = self.opener("branches.cache")
380 lines = f.read().split('\n')
379 lines = f.read().split('\n')
381 f.close()
380 f.close()
382 last, lrev = lines.pop(0).rstrip().split(" ", 1)
381 last, lrev = lines.pop(0).rstrip().split(" ", 1)
383 last, lrev = bin(last), int(lrev)
382 last, lrev = bin(last), int(lrev)
384 if not (lrev < self.changelog.count() and
383 if not (lrev < self.changelog.count() and
385 self.changelog.node(lrev) == last): # sanity check
384 self.changelog.node(lrev) == last): # sanity check
386 # invalidate the cache
385 # invalidate the cache
387 raise ValueError('Invalid branch cache: unknown tip')
386 raise ValueError('Invalid branch cache: unknown tip')
388 for l in lines:
387 for l in lines:
389 if not l: continue
388 if not l: continue
390 node, label = l.rstrip().split(" ", 1)
389 node, label = l.rstrip().split(" ", 1)
391 partial[label] = bin(node)
390 partial[label] = bin(node)
392 except (KeyboardInterrupt, util.SignalInterrupt):
391 except (KeyboardInterrupt, util.SignalInterrupt):
393 raise
392 raise
394 except Exception, inst:
393 except Exception, inst:
395 if self.ui.debugflag:
394 if self.ui.debugflag:
396 self.ui.warn(str(inst), '\n')
395 self.ui.warn(str(inst), '\n')
397 partial, last, lrev = {}, nullid, nullrev
396 partial, last, lrev = {}, nullid, nullrev
398 return partial, last, lrev
397 return partial, last, lrev
399
398
400 def _writebranchcache(self, branches, tip, tiprev):
399 def _writebranchcache(self, branches, tip, tiprev):
401 try:
400 try:
402 f = self.opener("branches.cache", "w")
401 f = self.opener("branches.cache", "w")
403 f.write("%s %s\n" % (hex(tip), tiprev))
402 f.write("%s %s\n" % (hex(tip), tiprev))
404 for label, node in branches.iteritems():
403 for label, node in branches.iteritems():
405 f.write("%s %s\n" % (hex(node), label))
404 f.write("%s %s\n" % (hex(node), label))
406 except IOError:
405 except IOError:
407 pass
406 pass
408
407
409 def _updatebranchcache(self, partial, start, end):
408 def _updatebranchcache(self, partial, start, end):
410 for r in xrange(start, end):
409 for r in xrange(start, end):
411 c = self.changectx(r)
410 c = self.changectx(r)
412 b = c.branch()
411 b = c.branch()
413 if b:
412 if b:
414 partial[b] = c.node()
413 partial[b] = c.node()
415
414
416 def lookup(self, key):
415 def lookup(self, key):
417 if key == '.':
416 if key == '.':
418 key = self.dirstate.parents()[0]
417 key = self.dirstate.parents()[0]
419 if key == nullid:
418 if key == nullid:
420 raise repo.RepoError(_("no revision checked out"))
419 raise repo.RepoError(_("no revision checked out"))
421 elif key == 'null':
420 elif key == 'null':
422 return nullid
421 return nullid
423 n = self.changelog._match(key)
422 n = self.changelog._match(key)
424 if n:
423 if n:
425 return n
424 return n
426 if key in self.tags():
425 if key in self.tags():
427 return self.tags()[key]
426 return self.tags()[key]
428 if key in self.branchtags():
427 if key in self.branchtags():
429 return self.branchtags()[key]
428 return self.branchtags()[key]
430 n = self.changelog._partialmatch(key)
429 n = self.changelog._partialmatch(key)
431 if n:
430 if n:
432 return n
431 return n
433 raise repo.RepoError(_("unknown revision '%s'") % key)
432 raise repo.RepoError(_("unknown revision '%s'") % key)
434
433
435 def dev(self):
434 def dev(self):
436 return os.lstat(self.path).st_dev
435 return os.lstat(self.path).st_dev
437
436
438 def local(self):
437 def local(self):
439 return True
438 return True
440
439
441 def join(self, f):
440 def join(self, f):
442 return os.path.join(self.path, f)
441 return os.path.join(self.path, f)
443
442
444 def sjoin(self, f):
443 def sjoin(self, f):
445 f = self.encodefn(f)
444 f = self.encodefn(f)
446 return os.path.join(self.spath, f)
445 return os.path.join(self.spath, f)
447
446
448 def wjoin(self, f):
447 def wjoin(self, f):
449 return os.path.join(self.root, f)
448 return os.path.join(self.root, f)
450
449
451 def file(self, f):
450 def file(self, f):
452 if f[0] == '/':
451 if f[0] == '/':
453 f = f[1:]
452 f = f[1:]
454 return filelog.filelog(self.sopener, f, self.revlogversion)
453 return filelog.filelog(self.sopener, f, self.revlogversion)
455
454
456 def changectx(self, changeid=None):
455 def changectx(self, changeid=None):
457 return context.changectx(self, changeid)
456 return context.changectx(self, changeid)
458
457
459 def workingctx(self):
458 def workingctx(self):
460 return context.workingctx(self)
459 return context.workingctx(self)
461
460
462 def parents(self, changeid=None):
461 def parents(self, changeid=None):
463 '''
462 '''
464 get list of changectxs for parents of changeid or working directory
463 get list of changectxs for parents of changeid or working directory
465 '''
464 '''
466 if changeid is None:
465 if changeid is None:
467 pl = self.dirstate.parents()
466 pl = self.dirstate.parents()
468 else:
467 else:
469 n = self.changelog.lookup(changeid)
468 n = self.changelog.lookup(changeid)
470 pl = self.changelog.parents(n)
469 pl = self.changelog.parents(n)
471 if pl[1] == nullid:
470 if pl[1] == nullid:
472 return [self.changectx(pl[0])]
471 return [self.changectx(pl[0])]
473 return [self.changectx(pl[0]), self.changectx(pl[1])]
472 return [self.changectx(pl[0]), self.changectx(pl[1])]
474
473
475 def filectx(self, path, changeid=None, fileid=None):
474 def filectx(self, path, changeid=None, fileid=None):
476 """changeid can be a changeset revision, node, or tag.
475 """changeid can be a changeset revision, node, or tag.
477 fileid can be a file revision or node."""
476 fileid can be a file revision or node."""
478 return context.filectx(self, path, changeid, fileid)
477 return context.filectx(self, path, changeid, fileid)
479
478
480 def getcwd(self):
479 def getcwd(self):
481 return self.dirstate.getcwd()
480 return self.dirstate.getcwd()
482
481
483 def wfile(self, f, mode='r'):
482 def wfile(self, f, mode='r'):
484 return self.wopener(f, mode)
483 return self.wopener(f, mode)
485
484
486 def wread(self, filename):
485 def _filter(self, filter, filename, data):
487 if self.encodepats == None:
486 if filter not in self.filterpats:
488 l = []
487 l = []
489 for pat, cmd in self.ui.configitems("encode"):
488 for pat, cmd in self.ui.configitems(filter):
490 mf = util.matcher(self.root, "", [pat], [], [])[1]
489 mf = util.matcher(self.root, "", [pat], [], [])[1]
491 l.append((mf, cmd))
490 l.append((mf, cmd))
492 self.encodepats = l
491 self.filterpats[filter] = l
493
492
494 if self._link(filename):
493 for mf, cmd in self.filterpats[filter]:
495 data = os.readlink(self.wjoin(filename))
496 else:
497 data = self.wopener(filename, 'r').read()
498
499 for mf, cmd in self.encodepats:
500 if mf(filename):
494 if mf(filename):
501 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
495 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
502 data = util.filter(data, cmd)
496 data = util.filter(data, cmd)
503 break
497 break
504
498
505 return data
499 return data
506
500
501 def wread(self, filename):
502 if self._link(filename):
503 data = os.readlink(self.wjoin(filename))
504 else:
505 data = self.wopener(filename, 'r').read()
506 return self._filter("encode", filename, data)
507
507 def wwrite(self, filename, data, fd=None):
508 def wwrite(self, filename, data, fd=None):
508 if self.decodepats == None:
509 data = self._filter("decode", filename, data)
509 l = []
510 for pat, cmd in self.ui.configitems("decode"):
511 mf = util.matcher(self.root, "", [pat], [], [])[1]
512 l.append((mf, cmd))
513 self.decodepats = l
514
515 for mf, cmd in self.decodepats:
516 if mf(filename):
517 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
518 data = util.filter(data, cmd)
519 break
520
521 if fd:
510 if fd:
522 return fd.write(data)
511 return fd.write(data)
523 return self.wopener(filename, 'w').write(data)
512 return self.wopener(filename, 'w').write(data)
524
513
525 def transaction(self):
514 def transaction(self):
526 tr = self.transhandle
515 tr = self.transhandle
527 if tr != None and tr.running():
516 if tr != None and tr.running():
528 return tr.nest()
517 return tr.nest()
529
518
530 # save dirstate for rollback
519 # save dirstate for rollback
531 try:
520 try:
532 ds = self.opener("dirstate").read()
521 ds = self.opener("dirstate").read()
533 except IOError:
522 except IOError:
534 ds = ""
523 ds = ""
535 self.opener("journal.dirstate", "w").write(ds)
524 self.opener("journal.dirstate", "w").write(ds)
536
525
537 renames = [(self.sjoin("journal"), self.sjoin("undo")),
526 renames = [(self.sjoin("journal"), self.sjoin("undo")),
538 (self.join("journal.dirstate"), self.join("undo.dirstate"))]
527 (self.join("journal.dirstate"), self.join("undo.dirstate"))]
539 tr = transaction.transaction(self.ui.warn, self.sopener,
528 tr = transaction.transaction(self.ui.warn, self.sopener,
540 self.sjoin("journal"),
529 self.sjoin("journal"),
541 aftertrans(renames))
530 aftertrans(renames))
542 self.transhandle = tr
531 self.transhandle = tr
543 return tr
532 return tr
544
533
545 def recover(self):
534 def recover(self):
546 l = self.lock()
535 l = self.lock()
547 if os.path.exists(self.sjoin("journal")):
536 if os.path.exists(self.sjoin("journal")):
548 self.ui.status(_("rolling back interrupted transaction\n"))
537 self.ui.status(_("rolling back interrupted transaction\n"))
549 transaction.rollback(self.sopener, self.sjoin("journal"))
538 transaction.rollback(self.sopener, self.sjoin("journal"))
550 self.reload()
539 self.reload()
551 return True
540 return True
552 else:
541 else:
553 self.ui.warn(_("no interrupted transaction available\n"))
542 self.ui.warn(_("no interrupted transaction available\n"))
554 return False
543 return False
555
544
556 def rollback(self, wlock=None):
545 def rollback(self, wlock=None):
557 if not wlock:
546 if not wlock:
558 wlock = self.wlock()
547 wlock = self.wlock()
559 l = self.lock()
548 l = self.lock()
560 if os.path.exists(self.sjoin("undo")):
549 if os.path.exists(self.sjoin("undo")):
561 self.ui.status(_("rolling back last transaction\n"))
550 self.ui.status(_("rolling back last transaction\n"))
562 transaction.rollback(self.sopener, self.sjoin("undo"))
551 transaction.rollback(self.sopener, self.sjoin("undo"))
563 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
552 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
564 self.reload()
553 self.reload()
565 self.wreload()
554 self.wreload()
566 else:
555 else:
567 self.ui.warn(_("no rollback information available\n"))
556 self.ui.warn(_("no rollback information available\n"))
568
557
569 def wreload(self):
558 def wreload(self):
570 self.dirstate.read()
559 self.dirstate.read()
571
560
572 def reload(self):
561 def reload(self):
573 self.changelog.load()
562 self.changelog.load()
574 self.manifest.load()
563 self.manifest.load()
575 self.tagscache = None
564 self.tagscache = None
576 self.nodetagscache = None
565 self.nodetagscache = None
577
566
578 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
567 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
579 desc=None):
568 desc=None):
580 try:
569 try:
581 l = lock.lock(lockname, 0, releasefn, desc=desc)
570 l = lock.lock(lockname, 0, releasefn, desc=desc)
582 except lock.LockHeld, inst:
571 except lock.LockHeld, inst:
583 if not wait:
572 if not wait:
584 raise
573 raise
585 self.ui.warn(_("waiting for lock on %s held by %r\n") %
574 self.ui.warn(_("waiting for lock on %s held by %r\n") %
586 (desc, inst.locker))
575 (desc, inst.locker))
587 # default to 600 seconds timeout
576 # default to 600 seconds timeout
588 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
577 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
589 releasefn, desc=desc)
578 releasefn, desc=desc)
590 if acquirefn:
579 if acquirefn:
591 acquirefn()
580 acquirefn()
592 return l
581 return l
593
582
594 def lock(self, wait=1):
583 def lock(self, wait=1):
595 return self.do_lock(self.sjoin("lock"), wait, acquirefn=self.reload,
584 return self.do_lock(self.sjoin("lock"), wait, acquirefn=self.reload,
596 desc=_('repository %s') % self.origroot)
585 desc=_('repository %s') % self.origroot)
597
586
598 def wlock(self, wait=1):
587 def wlock(self, wait=1):
599 return self.do_lock(self.join("wlock"), wait, self.dirstate.write,
588 return self.do_lock(self.join("wlock"), wait, self.dirstate.write,
600 self.wreload,
589 self.wreload,
601 desc=_('working directory of %s') % self.origroot)
590 desc=_('working directory of %s') % self.origroot)
602
591
603 def filecommit(self, fn, manifest1, manifest2, linkrev, transaction, changelist):
592 def filecommit(self, fn, manifest1, manifest2, linkrev, transaction, changelist):
604 """
593 """
605 commit an individual file as part of a larger transaction
594 commit an individual file as part of a larger transaction
606 """
595 """
607
596
608 t = self.wread(fn)
597 t = self.wread(fn)
609 fl = self.file(fn)
598 fl = self.file(fn)
610 fp1 = manifest1.get(fn, nullid)
599 fp1 = manifest1.get(fn, nullid)
611 fp2 = manifest2.get(fn, nullid)
600 fp2 = manifest2.get(fn, nullid)
612
601
613 meta = {}
602 meta = {}
614 cp = self.dirstate.copied(fn)
603 cp = self.dirstate.copied(fn)
615 if cp:
604 if cp:
616 meta["copy"] = cp
605 meta["copy"] = cp
617 if not manifest2: # not a branch merge
606 if not manifest2: # not a branch merge
618 meta["copyrev"] = hex(manifest1.get(cp, nullid))
607 meta["copyrev"] = hex(manifest1.get(cp, nullid))
619 fp2 = nullid
608 fp2 = nullid
620 elif fp2 != nullid: # copied on remote side
609 elif fp2 != nullid: # copied on remote side
621 meta["copyrev"] = hex(manifest1.get(cp, nullid))
610 meta["copyrev"] = hex(manifest1.get(cp, nullid))
622 elif fp1 != nullid: # copied on local side, reversed
611 elif fp1 != nullid: # copied on local side, reversed
623 meta["copyrev"] = hex(manifest2.get(cp))
612 meta["copyrev"] = hex(manifest2.get(cp))
624 fp2 = nullid
613 fp2 = nullid
625 else: # directory rename
614 else: # directory rename
626 meta["copyrev"] = hex(manifest1.get(cp, nullid))
615 meta["copyrev"] = hex(manifest1.get(cp, nullid))
627 self.ui.debug(_(" %s: copy %s:%s\n") %
616 self.ui.debug(_(" %s: copy %s:%s\n") %
628 (fn, cp, meta["copyrev"]))
617 (fn, cp, meta["copyrev"]))
629 fp1 = nullid
618 fp1 = nullid
630 elif fp2 != nullid:
619 elif fp2 != nullid:
631 # is one parent an ancestor of the other?
620 # is one parent an ancestor of the other?
632 fpa = fl.ancestor(fp1, fp2)
621 fpa = fl.ancestor(fp1, fp2)
633 if fpa == fp1:
622 if fpa == fp1:
634 fp1, fp2 = fp2, nullid
623 fp1, fp2 = fp2, nullid
635 elif fpa == fp2:
624 elif fpa == fp2:
636 fp2 = nullid
625 fp2 = nullid
637
626
638 # is the file unmodified from the parent? report existing entry
627 # is the file unmodified from the parent? report existing entry
639 if fp2 == nullid and not fl.cmp(fp1, t):
628 if fp2 == nullid and not fl.cmp(fp1, t):
640 return fp1
629 return fp1
641
630
642 changelist.append(fn)
631 changelist.append(fn)
643 return fl.add(t, meta, transaction, linkrev, fp1, fp2)
632 return fl.add(t, meta, transaction, linkrev, fp1, fp2)
644
633
645 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None, extra={}):
634 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None, extra={}):
646 if p1 is None:
635 if p1 is None:
647 p1, p2 = self.dirstate.parents()
636 p1, p2 = self.dirstate.parents()
648 return self.commit(files=files, text=text, user=user, date=date,
637 return self.commit(files=files, text=text, user=user, date=date,
649 p1=p1, p2=p2, wlock=wlock, extra=extra)
638 p1=p1, p2=p2, wlock=wlock, extra=extra)
650
639
651 def commit(self, files=None, text="", user=None, date=None,
640 def commit(self, files=None, text="", user=None, date=None,
652 match=util.always, force=False, lock=None, wlock=None,
641 match=util.always, force=False, lock=None, wlock=None,
653 force_editor=False, p1=None, p2=None, extra={}):
642 force_editor=False, p1=None, p2=None, extra={}):
654
643
655 commit = []
644 commit = []
656 remove = []
645 remove = []
657 changed = []
646 changed = []
658 use_dirstate = (p1 is None) # not rawcommit
647 use_dirstate = (p1 is None) # not rawcommit
659 extra = extra.copy()
648 extra = extra.copy()
660
649
661 if use_dirstate:
650 if use_dirstate:
662 if files:
651 if files:
663 for f in files:
652 for f in files:
664 s = self.dirstate.state(f)
653 s = self.dirstate.state(f)
665 if s in 'nmai':
654 if s in 'nmai':
666 commit.append(f)
655 commit.append(f)
667 elif s == 'r':
656 elif s == 'r':
668 remove.append(f)
657 remove.append(f)
669 else:
658 else:
670 self.ui.warn(_("%s not tracked!\n") % f)
659 self.ui.warn(_("%s not tracked!\n") % f)
671 else:
660 else:
672 changes = self.status(match=match)[:5]
661 changes = self.status(match=match)[:5]
673 modified, added, removed, deleted, unknown = changes
662 modified, added, removed, deleted, unknown = changes
674 commit = modified + added
663 commit = modified + added
675 remove = removed
664 remove = removed
676 else:
665 else:
677 commit = files
666 commit = files
678
667
679 if use_dirstate:
668 if use_dirstate:
680 p1, p2 = self.dirstate.parents()
669 p1, p2 = self.dirstate.parents()
681 update_dirstate = True
670 update_dirstate = True
682 else:
671 else:
683 p1, p2 = p1, p2 or nullid
672 p1, p2 = p1, p2 or nullid
684 update_dirstate = (self.dirstate.parents()[0] == p1)
673 update_dirstate = (self.dirstate.parents()[0] == p1)
685
674
686 c1 = self.changelog.read(p1)
675 c1 = self.changelog.read(p1)
687 c2 = self.changelog.read(p2)
676 c2 = self.changelog.read(p2)
688 m1 = self.manifest.read(c1[0]).copy()
677 m1 = self.manifest.read(c1[0]).copy()
689 m2 = self.manifest.read(c2[0])
678 m2 = self.manifest.read(c2[0])
690
679
691 if use_dirstate:
680 if use_dirstate:
692 branchname = self.workingctx().branch()
681 branchname = self.workingctx().branch()
693 try:
682 try:
694 branchname = branchname.decode('UTF-8').encode('UTF-8')
683 branchname = branchname.decode('UTF-8').encode('UTF-8')
695 except UnicodeDecodeError:
684 except UnicodeDecodeError:
696 raise util.Abort(_('branch name not in UTF-8!'))
685 raise util.Abort(_('branch name not in UTF-8!'))
697 else:
686 else:
698 branchname = ""
687 branchname = ""
699
688
700 if use_dirstate:
689 if use_dirstate:
701 oldname = c1[5].get("branch", "") # stored in UTF-8
690 oldname = c1[5].get("branch", "") # stored in UTF-8
702 if not commit and not remove and not force and p2 == nullid and \
691 if not commit and not remove and not force and p2 == nullid and \
703 branchname == oldname:
692 branchname == oldname:
704 self.ui.status(_("nothing changed\n"))
693 self.ui.status(_("nothing changed\n"))
705 return None
694 return None
706
695
707 xp1 = hex(p1)
696 xp1 = hex(p1)
708 if p2 == nullid: xp2 = ''
697 if p2 == nullid: xp2 = ''
709 else: xp2 = hex(p2)
698 else: xp2 = hex(p2)
710
699
711 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
700 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
712
701
713 if not wlock:
702 if not wlock:
714 wlock = self.wlock()
703 wlock = self.wlock()
715 if not lock:
704 if not lock:
716 lock = self.lock()
705 lock = self.lock()
717 tr = self.transaction()
706 tr = self.transaction()
718
707
719 # check in files
708 # check in files
720 new = {}
709 new = {}
721 linkrev = self.changelog.count()
710 linkrev = self.changelog.count()
722 commit.sort()
711 commit.sort()
723 is_exec = util.execfunc(self.root, m1.execf)
712 is_exec = util.execfunc(self.root, m1.execf)
724 is_link = util.linkfunc(self.root, m1.linkf)
713 is_link = util.linkfunc(self.root, m1.linkf)
725 for f in commit:
714 for f in commit:
726 self.ui.note(f + "\n")
715 self.ui.note(f + "\n")
727 try:
716 try:
728 new[f] = self.filecommit(f, m1, m2, linkrev, tr, changed)
717 new[f] = self.filecommit(f, m1, m2, linkrev, tr, changed)
729 m1.set(f, is_exec(f), is_link(f))
718 m1.set(f, is_exec(f), is_link(f))
730 except OSError:
719 except OSError:
731 if use_dirstate:
720 if use_dirstate:
732 self.ui.warn(_("trouble committing %s!\n") % f)
721 self.ui.warn(_("trouble committing %s!\n") % f)
733 raise
722 raise
734 else:
723 else:
735 remove.append(f)
724 remove.append(f)
736
725
737 # update manifest
726 # update manifest
738 m1.update(new)
727 m1.update(new)
739 remove.sort()
728 remove.sort()
740 removed = []
729 removed = []
741
730
742 for f in remove:
731 for f in remove:
743 if f in m1:
732 if f in m1:
744 del m1[f]
733 del m1[f]
745 removed.append(f)
734 removed.append(f)
746 mn = self.manifest.add(m1, tr, linkrev, c1[0], c2[0], (new, removed))
735 mn = self.manifest.add(m1, tr, linkrev, c1[0], c2[0], (new, removed))
747
736
748 # add changeset
737 # add changeset
749 new = new.keys()
738 new = new.keys()
750 new.sort()
739 new.sort()
751
740
752 user = user or self.ui.username()
741 user = user or self.ui.username()
753 if not text or force_editor:
742 if not text or force_editor:
754 edittext = []
743 edittext = []
755 if text:
744 if text:
756 edittext.append(text)
745 edittext.append(text)
757 edittext.append("")
746 edittext.append("")
758 edittext.append("HG: user: %s" % user)
747 edittext.append("HG: user: %s" % user)
759 if p2 != nullid:
748 if p2 != nullid:
760 edittext.append("HG: branch merge")
749 edittext.append("HG: branch merge")
761 edittext.extend(["HG: changed %s" % f for f in changed])
750 edittext.extend(["HG: changed %s" % f for f in changed])
762 edittext.extend(["HG: removed %s" % f for f in removed])
751 edittext.extend(["HG: removed %s" % f for f in removed])
763 if not changed and not remove:
752 if not changed and not remove:
764 edittext.append("HG: no files changed")
753 edittext.append("HG: no files changed")
765 edittext.append("")
754 edittext.append("")
766 # run editor in the repository root
755 # run editor in the repository root
767 olddir = os.getcwd()
756 olddir = os.getcwd()
768 os.chdir(self.root)
757 os.chdir(self.root)
769 text = self.ui.edit("\n".join(edittext), user)
758 text = self.ui.edit("\n".join(edittext), user)
770 os.chdir(olddir)
759 os.chdir(olddir)
771
760
772 lines = [line.rstrip() for line in text.rstrip().splitlines()]
761 lines = [line.rstrip() for line in text.rstrip().splitlines()]
773 while lines and not lines[0]:
762 while lines and not lines[0]:
774 del lines[0]
763 del lines[0]
775 if not lines:
764 if not lines:
776 return None
765 return None
777 text = '\n'.join(lines)
766 text = '\n'.join(lines)
778 if branchname:
767 if branchname:
779 extra["branch"] = branchname
768 extra["branch"] = branchname
780 n = self.changelog.add(mn, changed + removed, text, tr, p1, p2,
769 n = self.changelog.add(mn, changed + removed, text, tr, p1, p2,
781 user, date, extra)
770 user, date, extra)
782 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
771 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
783 parent2=xp2)
772 parent2=xp2)
784 tr.close()
773 tr.close()
785
774
786 if use_dirstate or update_dirstate:
775 if use_dirstate or update_dirstate:
787 self.dirstate.setparents(n)
776 self.dirstate.setparents(n)
788 if use_dirstate:
777 if use_dirstate:
789 self.dirstate.update(new, "n")
778 self.dirstate.update(new, "n")
790 self.dirstate.forget(removed)
779 self.dirstate.forget(removed)
791
780
792 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
781 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
793 return n
782 return n
794
783
795 def walk(self, node=None, files=[], match=util.always, badmatch=None):
784 def walk(self, node=None, files=[], match=util.always, badmatch=None):
796 '''
785 '''
797 walk recursively through the directory tree or a given
786 walk recursively through the directory tree or a given
798 changeset, finding all files matched by the match
787 changeset, finding all files matched by the match
799 function
788 function
800
789
801 results are yielded in a tuple (src, filename), where src
790 results are yielded in a tuple (src, filename), where src
802 is one of:
791 is one of:
803 'f' the file was found in the directory tree
792 'f' the file was found in the directory tree
804 'm' the file was only in the dirstate and not in the tree
793 'm' the file was only in the dirstate and not in the tree
805 'b' file was not found and matched badmatch
794 'b' file was not found and matched badmatch
806 '''
795 '''
807
796
808 if node:
797 if node:
809 fdict = dict.fromkeys(files)
798 fdict = dict.fromkeys(files)
810 for fn in self.manifest.read(self.changelog.read(node)[0]):
799 for fn in self.manifest.read(self.changelog.read(node)[0]):
811 for ffn in fdict:
800 for ffn in fdict:
812 # match if the file is the exact name or a directory
801 # match if the file is the exact name or a directory
813 if ffn == fn or fn.startswith("%s/" % ffn):
802 if ffn == fn or fn.startswith("%s/" % ffn):
814 del fdict[ffn]
803 del fdict[ffn]
815 break
804 break
816 if match(fn):
805 if match(fn):
817 yield 'm', fn
806 yield 'm', fn
818 for fn in fdict:
807 for fn in fdict:
819 if badmatch and badmatch(fn):
808 if badmatch and badmatch(fn):
820 if match(fn):
809 if match(fn):
821 yield 'b', fn
810 yield 'b', fn
822 else:
811 else:
823 self.ui.warn(_('%s: No such file in rev %s\n') % (
812 self.ui.warn(_('%s: No such file in rev %s\n') % (
824 util.pathto(self.getcwd(), fn), short(node)))
813 util.pathto(self.getcwd(), fn), short(node)))
825 else:
814 else:
826 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
815 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
827 yield src, fn
816 yield src, fn
828
817
829 def status(self, node1=None, node2=None, files=[], match=util.always,
818 def status(self, node1=None, node2=None, files=[], match=util.always,
830 wlock=None, list_ignored=False, list_clean=False):
819 wlock=None, list_ignored=False, list_clean=False):
831 """return status of files between two nodes or node and working directory
820 """return status of files between two nodes or node and working directory
832
821
833 If node1 is None, use the first dirstate parent instead.
822 If node1 is None, use the first dirstate parent instead.
834 If node2 is None, compare node1 with working directory.
823 If node2 is None, compare node1 with working directory.
835 """
824 """
836
825
837 def fcmp(fn, mf):
826 def fcmp(fn, mf):
838 t1 = self.wread(fn)
827 t1 = self.wread(fn)
839 return self.file(fn).cmp(mf.get(fn, nullid), t1)
828 return self.file(fn).cmp(mf.get(fn, nullid), t1)
840
829
841 def mfmatches(node):
830 def mfmatches(node):
842 change = self.changelog.read(node)
831 change = self.changelog.read(node)
843 mf = self.manifest.read(change[0]).copy()
832 mf = self.manifest.read(change[0]).copy()
844 for fn in mf.keys():
833 for fn in mf.keys():
845 if not match(fn):
834 if not match(fn):
846 del mf[fn]
835 del mf[fn]
847 return mf
836 return mf
848
837
849 modified, added, removed, deleted, unknown = [], [], [], [], []
838 modified, added, removed, deleted, unknown = [], [], [], [], []
850 ignored, clean = [], []
839 ignored, clean = [], []
851
840
852 compareworking = False
841 compareworking = False
853 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
842 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
854 compareworking = True
843 compareworking = True
855
844
856 if not compareworking:
845 if not compareworking:
857 # read the manifest from node1 before the manifest from node2,
846 # read the manifest from node1 before the manifest from node2,
858 # so that we'll hit the manifest cache if we're going through
847 # so that we'll hit the manifest cache if we're going through
859 # all the revisions in parent->child order.
848 # all the revisions in parent->child order.
860 mf1 = mfmatches(node1)
849 mf1 = mfmatches(node1)
861
850
862 # are we comparing the working directory?
851 # are we comparing the working directory?
863 if not node2:
852 if not node2:
864 if not wlock:
853 if not wlock:
865 try:
854 try:
866 wlock = self.wlock(wait=0)
855 wlock = self.wlock(wait=0)
867 except lock.LockException:
856 except lock.LockException:
868 wlock = None
857 wlock = None
869 (lookup, modified, added, removed, deleted, unknown,
858 (lookup, modified, added, removed, deleted, unknown,
870 ignored, clean) = self.dirstate.status(files, match,
859 ignored, clean) = self.dirstate.status(files, match,
871 list_ignored, list_clean)
860 list_ignored, list_clean)
872
861
873 # are we comparing working dir against its parent?
862 # are we comparing working dir against its parent?
874 if compareworking:
863 if compareworking:
875 if lookup:
864 if lookup:
876 # do a full compare of any files that might have changed
865 # do a full compare of any files that might have changed
877 mf2 = mfmatches(self.dirstate.parents()[0])
866 mf2 = mfmatches(self.dirstate.parents()[0])
878 for f in lookup:
867 for f in lookup:
879 if fcmp(f, mf2):
868 if fcmp(f, mf2):
880 modified.append(f)
869 modified.append(f)
881 else:
870 else:
882 clean.append(f)
871 clean.append(f)
883 if wlock is not None:
872 if wlock is not None:
884 self.dirstate.update([f], "n")
873 self.dirstate.update([f], "n")
885 else:
874 else:
886 # we are comparing working dir against non-parent
875 # we are comparing working dir against non-parent
887 # generate a pseudo-manifest for the working dir
876 # generate a pseudo-manifest for the working dir
888 # XXX: create it in dirstate.py ?
877 # XXX: create it in dirstate.py ?
889 mf2 = mfmatches(self.dirstate.parents()[0])
878 mf2 = mfmatches(self.dirstate.parents()[0])
890 is_exec = util.execfunc(self.root, mf2.execf)
879 is_exec = util.execfunc(self.root, mf2.execf)
891 is_link = util.linkfunc(self.root, mf2.linkf)
880 is_link = util.linkfunc(self.root, mf2.linkf)
892 for f in lookup + modified + added:
881 for f in lookup + modified + added:
893 mf2[f] = ""
882 mf2[f] = ""
894 mf2.set(f, is_exec(f), is_link(f))
883 mf2.set(f, is_exec(f), is_link(f))
895 for f in removed:
884 for f in removed:
896 if f in mf2:
885 if f in mf2:
897 del mf2[f]
886 del mf2[f]
898 else:
887 else:
899 # we are comparing two revisions
888 # we are comparing two revisions
900 mf2 = mfmatches(node2)
889 mf2 = mfmatches(node2)
901
890
902 if not compareworking:
891 if not compareworking:
903 # flush lists from dirstate before comparing manifests
892 # flush lists from dirstate before comparing manifests
904 modified, added, clean = [], [], []
893 modified, added, clean = [], [], []
905
894
906 # make sure to sort the files so we talk to the disk in a
895 # make sure to sort the files so we talk to the disk in a
907 # reasonable order
896 # reasonable order
908 mf2keys = mf2.keys()
897 mf2keys = mf2.keys()
909 mf2keys.sort()
898 mf2keys.sort()
910 for fn in mf2keys:
899 for fn in mf2keys:
911 if mf1.has_key(fn):
900 if mf1.has_key(fn):
912 if mf1.flags(fn) != mf2.flags(fn) or \
901 if mf1.flags(fn) != mf2.flags(fn) or \
913 (mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1))):
902 (mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1))):
914 modified.append(fn)
903 modified.append(fn)
915 elif list_clean:
904 elif list_clean:
916 clean.append(fn)
905 clean.append(fn)
917 del mf1[fn]
906 del mf1[fn]
918 else:
907 else:
919 added.append(fn)
908 added.append(fn)
920
909
921 removed = mf1.keys()
910 removed = mf1.keys()
922
911
923 # sort and return results:
912 # sort and return results:
924 for l in modified, added, removed, deleted, unknown, ignored, clean:
913 for l in modified, added, removed, deleted, unknown, ignored, clean:
925 l.sort()
914 l.sort()
926 return (modified, added, removed, deleted, unknown, ignored, clean)
915 return (modified, added, removed, deleted, unknown, ignored, clean)
927
916
928 def add(self, list, wlock=None):
917 def add(self, list, wlock=None):
929 if not wlock:
918 if not wlock:
930 wlock = self.wlock()
919 wlock = self.wlock()
931 for f in list:
920 for f in list:
932 p = self.wjoin(f)
921 p = self.wjoin(f)
933 if not os.path.exists(p):
922 if not os.path.exists(p):
934 self.ui.warn(_("%s does not exist!\n") % f)
923 self.ui.warn(_("%s does not exist!\n") % f)
935 elif not os.path.isfile(p):
924 elif not os.path.isfile(p):
936 self.ui.warn(_("%s not added: only files supported currently\n")
925 self.ui.warn(_("%s not added: only files supported currently\n")
937 % f)
926 % f)
938 elif self.dirstate.state(f) in 'an':
927 elif self.dirstate.state(f) in 'an':
939 self.ui.warn(_("%s already tracked!\n") % f)
928 self.ui.warn(_("%s already tracked!\n") % f)
940 else:
929 else:
941 self.dirstate.update([f], "a")
930 self.dirstate.update([f], "a")
942
931
943 def forget(self, list, wlock=None):
932 def forget(self, list, wlock=None):
944 if not wlock:
933 if not wlock:
945 wlock = self.wlock()
934 wlock = self.wlock()
946 for f in list:
935 for f in list:
947 if self.dirstate.state(f) not in 'ai':
936 if self.dirstate.state(f) not in 'ai':
948 self.ui.warn(_("%s not added!\n") % f)
937 self.ui.warn(_("%s not added!\n") % f)
949 else:
938 else:
950 self.dirstate.forget([f])
939 self.dirstate.forget([f])
951
940
952 def remove(self, list, unlink=False, wlock=None):
941 def remove(self, list, unlink=False, wlock=None):
953 if unlink:
942 if unlink:
954 for f in list:
943 for f in list:
955 try:
944 try:
956 util.unlink(self.wjoin(f))
945 util.unlink(self.wjoin(f))
957 except OSError, inst:
946 except OSError, inst:
958 if inst.errno != errno.ENOENT:
947 if inst.errno != errno.ENOENT:
959 raise
948 raise
960 if not wlock:
949 if not wlock:
961 wlock = self.wlock()
950 wlock = self.wlock()
962 for f in list:
951 for f in list:
963 p = self.wjoin(f)
952 p = self.wjoin(f)
964 if os.path.exists(p):
953 if os.path.exists(p):
965 self.ui.warn(_("%s still exists!\n") % f)
954 self.ui.warn(_("%s still exists!\n") % f)
966 elif self.dirstate.state(f) == 'a':
955 elif self.dirstate.state(f) == 'a':
967 self.dirstate.forget([f])
956 self.dirstate.forget([f])
968 elif f not in self.dirstate:
957 elif f not in self.dirstate:
969 self.ui.warn(_("%s not tracked!\n") % f)
958 self.ui.warn(_("%s not tracked!\n") % f)
970 else:
959 else:
971 self.dirstate.update([f], "r")
960 self.dirstate.update([f], "r")
972
961
973 def undelete(self, list, wlock=None):
962 def undelete(self, list, wlock=None):
974 p = self.dirstate.parents()[0]
963 p = self.dirstate.parents()[0]
975 mn = self.changelog.read(p)[0]
964 mn = self.changelog.read(p)[0]
976 m = self.manifest.read(mn)
965 m = self.manifest.read(mn)
977 if not wlock:
966 if not wlock:
978 wlock = self.wlock()
967 wlock = self.wlock()
979 for f in list:
968 for f in list:
980 if self.dirstate.state(f) not in "r":
969 if self.dirstate.state(f) not in "r":
981 self.ui.warn("%s not removed!\n" % f)
970 self.ui.warn("%s not removed!\n" % f)
982 else:
971 else:
983 t = self.file(f).read(m[f])
972 t = self.file(f).read(m[f])
984 self.wwrite(f, t)
973 self.wwrite(f, t)
985 util.set_exec(self.wjoin(f), m.execf(f))
974 util.set_exec(self.wjoin(f), m.execf(f))
986 self.dirstate.update([f], "n")
975 self.dirstate.update([f], "n")
987
976
988 def copy(self, source, dest, wlock=None):
977 def copy(self, source, dest, wlock=None):
989 p = self.wjoin(dest)
978 p = self.wjoin(dest)
990 if not os.path.exists(p):
979 if not os.path.exists(p):
991 self.ui.warn(_("%s does not exist!\n") % dest)
980 self.ui.warn(_("%s does not exist!\n") % dest)
992 elif not os.path.isfile(p):
981 elif not os.path.isfile(p):
993 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
982 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
994 else:
983 else:
995 if not wlock:
984 if not wlock:
996 wlock = self.wlock()
985 wlock = self.wlock()
997 if self.dirstate.state(dest) == '?':
986 if self.dirstate.state(dest) == '?':
998 self.dirstate.update([dest], "a")
987 self.dirstate.update([dest], "a")
999 self.dirstate.copy(source, dest)
988 self.dirstate.copy(source, dest)
1000
989
1001 def heads(self, start=None):
990 def heads(self, start=None):
1002 heads = self.changelog.heads(start)
991 heads = self.changelog.heads(start)
1003 # sort the output in rev descending order
992 # sort the output in rev descending order
1004 heads = [(-self.changelog.rev(h), h) for h in heads]
993 heads = [(-self.changelog.rev(h), h) for h in heads]
1005 heads.sort()
994 heads.sort()
1006 return [n for (r, n) in heads]
995 return [n for (r, n) in heads]
1007
996
1008 def branches(self, nodes):
997 def branches(self, nodes):
1009 if not nodes:
998 if not nodes:
1010 nodes = [self.changelog.tip()]
999 nodes = [self.changelog.tip()]
1011 b = []
1000 b = []
1012 for n in nodes:
1001 for n in nodes:
1013 t = n
1002 t = n
1014 while 1:
1003 while 1:
1015 p = self.changelog.parents(n)
1004 p = self.changelog.parents(n)
1016 if p[1] != nullid or p[0] == nullid:
1005 if p[1] != nullid or p[0] == nullid:
1017 b.append((t, n, p[0], p[1]))
1006 b.append((t, n, p[0], p[1]))
1018 break
1007 break
1019 n = p[0]
1008 n = p[0]
1020 return b
1009 return b
1021
1010
1022 def between(self, pairs):
1011 def between(self, pairs):
1023 r = []
1012 r = []
1024
1013
1025 for top, bottom in pairs:
1014 for top, bottom in pairs:
1026 n, l, i = top, [], 0
1015 n, l, i = top, [], 0
1027 f = 1
1016 f = 1
1028
1017
1029 while n != bottom:
1018 while n != bottom:
1030 p = self.changelog.parents(n)[0]
1019 p = self.changelog.parents(n)[0]
1031 if i == f:
1020 if i == f:
1032 l.append(n)
1021 l.append(n)
1033 f = f * 2
1022 f = f * 2
1034 n = p
1023 n = p
1035 i += 1
1024 i += 1
1036
1025
1037 r.append(l)
1026 r.append(l)
1038
1027
1039 return r
1028 return r
1040
1029
1041 def findincoming(self, remote, base=None, heads=None, force=False):
1030 def findincoming(self, remote, base=None, heads=None, force=False):
1042 """Return list of roots of the subsets of missing nodes from remote
1031 """Return list of roots of the subsets of missing nodes from remote
1043
1032
1044 If base dict is specified, assume that these nodes and their parents
1033 If base dict is specified, assume that these nodes and their parents
1045 exist on the remote side and that no child of a node of base exists
1034 exist on the remote side and that no child of a node of base exists
1046 in both remote and self.
1035 in both remote and self.
1047 Furthermore base will be updated to include the nodes that exists
1036 Furthermore base will be updated to include the nodes that exists
1048 in self and remote but no children exists in self and remote.
1037 in self and remote but no children exists in self and remote.
1049 If a list of heads is specified, return only nodes which are heads
1038 If a list of heads is specified, return only nodes which are heads
1050 or ancestors of these heads.
1039 or ancestors of these heads.
1051
1040
1052 All the ancestors of base are in self and in remote.
1041 All the ancestors of base are in self and in remote.
1053 All the descendants of the list returned are missing in self.
1042 All the descendants of the list returned are missing in self.
1054 (and so we know that the rest of the nodes are missing in remote, see
1043 (and so we know that the rest of the nodes are missing in remote, see
1055 outgoing)
1044 outgoing)
1056 """
1045 """
1057 m = self.changelog.nodemap
1046 m = self.changelog.nodemap
1058 search = []
1047 search = []
1059 fetch = {}
1048 fetch = {}
1060 seen = {}
1049 seen = {}
1061 seenbranch = {}
1050 seenbranch = {}
1062 if base == None:
1051 if base == None:
1063 base = {}
1052 base = {}
1064
1053
1065 if not heads:
1054 if not heads:
1066 heads = remote.heads()
1055 heads = remote.heads()
1067
1056
1068 if self.changelog.tip() == nullid:
1057 if self.changelog.tip() == nullid:
1069 base[nullid] = 1
1058 base[nullid] = 1
1070 if heads != [nullid]:
1059 if heads != [nullid]:
1071 return [nullid]
1060 return [nullid]
1072 return []
1061 return []
1073
1062
1074 # assume we're closer to the tip than the root
1063 # assume we're closer to the tip than the root
1075 # and start by examining the heads
1064 # and start by examining the heads
1076 self.ui.status(_("searching for changes\n"))
1065 self.ui.status(_("searching for changes\n"))
1077
1066
1078 unknown = []
1067 unknown = []
1079 for h in heads:
1068 for h in heads:
1080 if h not in m:
1069 if h not in m:
1081 unknown.append(h)
1070 unknown.append(h)
1082 else:
1071 else:
1083 base[h] = 1
1072 base[h] = 1
1084
1073
1085 if not unknown:
1074 if not unknown:
1086 return []
1075 return []
1087
1076
1088 req = dict.fromkeys(unknown)
1077 req = dict.fromkeys(unknown)
1089 reqcnt = 0
1078 reqcnt = 0
1090
1079
1091 # search through remote branches
1080 # search through remote branches
1092 # a 'branch' here is a linear segment of history, with four parts:
1081 # a 'branch' here is a linear segment of history, with four parts:
1093 # head, root, first parent, second parent
1082 # head, root, first parent, second parent
1094 # (a branch always has two parents (or none) by definition)
1083 # (a branch always has two parents (or none) by definition)
1095 unknown = remote.branches(unknown)
1084 unknown = remote.branches(unknown)
1096 while unknown:
1085 while unknown:
1097 r = []
1086 r = []
1098 while unknown:
1087 while unknown:
1099 n = unknown.pop(0)
1088 n = unknown.pop(0)
1100 if n[0] in seen:
1089 if n[0] in seen:
1101 continue
1090 continue
1102
1091
1103 self.ui.debug(_("examining %s:%s\n")
1092 self.ui.debug(_("examining %s:%s\n")
1104 % (short(n[0]), short(n[1])))
1093 % (short(n[0]), short(n[1])))
1105 if n[0] == nullid: # found the end of the branch
1094 if n[0] == nullid: # found the end of the branch
1106 pass
1095 pass
1107 elif n in seenbranch:
1096 elif n in seenbranch:
1108 self.ui.debug(_("branch already found\n"))
1097 self.ui.debug(_("branch already found\n"))
1109 continue
1098 continue
1110 elif n[1] and n[1] in m: # do we know the base?
1099 elif n[1] and n[1] in m: # do we know the base?
1111 self.ui.debug(_("found incomplete branch %s:%s\n")
1100 self.ui.debug(_("found incomplete branch %s:%s\n")
1112 % (short(n[0]), short(n[1])))
1101 % (short(n[0]), short(n[1])))
1113 search.append(n) # schedule branch range for scanning
1102 search.append(n) # schedule branch range for scanning
1114 seenbranch[n] = 1
1103 seenbranch[n] = 1
1115 else:
1104 else:
1116 if n[1] not in seen and n[1] not in fetch:
1105 if n[1] not in seen and n[1] not in fetch:
1117 if n[2] in m and n[3] in m:
1106 if n[2] in m and n[3] in m:
1118 self.ui.debug(_("found new changeset %s\n") %
1107 self.ui.debug(_("found new changeset %s\n") %
1119 short(n[1]))
1108 short(n[1]))
1120 fetch[n[1]] = 1 # earliest unknown
1109 fetch[n[1]] = 1 # earliest unknown
1121 for p in n[2:4]:
1110 for p in n[2:4]:
1122 if p in m:
1111 if p in m:
1123 base[p] = 1 # latest known
1112 base[p] = 1 # latest known
1124
1113
1125 for p in n[2:4]:
1114 for p in n[2:4]:
1126 if p not in req and p not in m:
1115 if p not in req and p not in m:
1127 r.append(p)
1116 r.append(p)
1128 req[p] = 1
1117 req[p] = 1
1129 seen[n[0]] = 1
1118 seen[n[0]] = 1
1130
1119
1131 if r:
1120 if r:
1132 reqcnt += 1
1121 reqcnt += 1
1133 self.ui.debug(_("request %d: %s\n") %
1122 self.ui.debug(_("request %d: %s\n") %
1134 (reqcnt, " ".join(map(short, r))))
1123 (reqcnt, " ".join(map(short, r))))
1135 for p in xrange(0, len(r), 10):
1124 for p in xrange(0, len(r), 10):
1136 for b in remote.branches(r[p:p+10]):
1125 for b in remote.branches(r[p:p+10]):
1137 self.ui.debug(_("received %s:%s\n") %
1126 self.ui.debug(_("received %s:%s\n") %
1138 (short(b[0]), short(b[1])))
1127 (short(b[0]), short(b[1])))
1139 unknown.append(b)
1128 unknown.append(b)
1140
1129
1141 # do binary search on the branches we found
1130 # do binary search on the branches we found
1142 while search:
1131 while search:
1143 n = search.pop(0)
1132 n = search.pop(0)
1144 reqcnt += 1
1133 reqcnt += 1
1145 l = remote.between([(n[0], n[1])])[0]
1134 l = remote.between([(n[0], n[1])])[0]
1146 l.append(n[1])
1135 l.append(n[1])
1147 p = n[0]
1136 p = n[0]
1148 f = 1
1137 f = 1
1149 for i in l:
1138 for i in l:
1150 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1139 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1151 if i in m:
1140 if i in m:
1152 if f <= 2:
1141 if f <= 2:
1153 self.ui.debug(_("found new branch changeset %s\n") %
1142 self.ui.debug(_("found new branch changeset %s\n") %
1154 short(p))
1143 short(p))
1155 fetch[p] = 1
1144 fetch[p] = 1
1156 base[i] = 1
1145 base[i] = 1
1157 else:
1146 else:
1158 self.ui.debug(_("narrowed branch search to %s:%s\n")
1147 self.ui.debug(_("narrowed branch search to %s:%s\n")
1159 % (short(p), short(i)))
1148 % (short(p), short(i)))
1160 search.append((p, i))
1149 search.append((p, i))
1161 break
1150 break
1162 p, f = i, f * 2
1151 p, f = i, f * 2
1163
1152
1164 # sanity check our fetch list
1153 # sanity check our fetch list
1165 for f in fetch.keys():
1154 for f in fetch.keys():
1166 if f in m:
1155 if f in m:
1167 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1156 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1168
1157
1169 if base.keys() == [nullid]:
1158 if base.keys() == [nullid]:
1170 if force:
1159 if force:
1171 self.ui.warn(_("warning: repository is unrelated\n"))
1160 self.ui.warn(_("warning: repository is unrelated\n"))
1172 else:
1161 else:
1173 raise util.Abort(_("repository is unrelated"))
1162 raise util.Abort(_("repository is unrelated"))
1174
1163
1175 self.ui.debug(_("found new changesets starting at ") +
1164 self.ui.debug(_("found new changesets starting at ") +
1176 " ".join([short(f) for f in fetch]) + "\n")
1165 " ".join([short(f) for f in fetch]) + "\n")
1177
1166
1178 self.ui.debug(_("%d total queries\n") % reqcnt)
1167 self.ui.debug(_("%d total queries\n") % reqcnt)
1179
1168
1180 return fetch.keys()
1169 return fetch.keys()
1181
1170
1182 def findoutgoing(self, remote, base=None, heads=None, force=False):
1171 def findoutgoing(self, remote, base=None, heads=None, force=False):
1183 """Return list of nodes that are roots of subsets not in remote
1172 """Return list of nodes that are roots of subsets not in remote
1184
1173
1185 If base dict is specified, assume that these nodes and their parents
1174 If base dict is specified, assume that these nodes and their parents
1186 exist on the remote side.
1175 exist on the remote side.
1187 If a list of heads is specified, return only nodes which are heads
1176 If a list of heads is specified, return only nodes which are heads
1188 or ancestors of these heads, and return a second element which
1177 or ancestors of these heads, and return a second element which
1189 contains all remote heads which get new children.
1178 contains all remote heads which get new children.
1190 """
1179 """
1191 if base == None:
1180 if base == None:
1192 base = {}
1181 base = {}
1193 self.findincoming(remote, base, heads, force=force)
1182 self.findincoming(remote, base, heads, force=force)
1194
1183
1195 self.ui.debug(_("common changesets up to ")
1184 self.ui.debug(_("common changesets up to ")
1196 + " ".join(map(short, base.keys())) + "\n")
1185 + " ".join(map(short, base.keys())) + "\n")
1197
1186
1198 remain = dict.fromkeys(self.changelog.nodemap)
1187 remain = dict.fromkeys(self.changelog.nodemap)
1199
1188
1200 # prune everything remote has from the tree
1189 # prune everything remote has from the tree
1201 del remain[nullid]
1190 del remain[nullid]
1202 remove = base.keys()
1191 remove = base.keys()
1203 while remove:
1192 while remove:
1204 n = remove.pop(0)
1193 n = remove.pop(0)
1205 if n in remain:
1194 if n in remain:
1206 del remain[n]
1195 del remain[n]
1207 for p in self.changelog.parents(n):
1196 for p in self.changelog.parents(n):
1208 remove.append(p)
1197 remove.append(p)
1209
1198
1210 # find every node whose parents have been pruned
1199 # find every node whose parents have been pruned
1211 subset = []
1200 subset = []
1212 # find every remote head that will get new children
1201 # find every remote head that will get new children
1213 updated_heads = {}
1202 updated_heads = {}
1214 for n in remain:
1203 for n in remain:
1215 p1, p2 = self.changelog.parents(n)
1204 p1, p2 = self.changelog.parents(n)
1216 if p1 not in remain and p2 not in remain:
1205 if p1 not in remain and p2 not in remain:
1217 subset.append(n)
1206 subset.append(n)
1218 if heads:
1207 if heads:
1219 if p1 in heads:
1208 if p1 in heads:
1220 updated_heads[p1] = True
1209 updated_heads[p1] = True
1221 if p2 in heads:
1210 if p2 in heads:
1222 updated_heads[p2] = True
1211 updated_heads[p2] = True
1223
1212
1224 # this is the set of all roots we have to push
1213 # this is the set of all roots we have to push
1225 if heads:
1214 if heads:
1226 return subset, updated_heads.keys()
1215 return subset, updated_heads.keys()
1227 else:
1216 else:
1228 return subset
1217 return subset
1229
1218
1230 def pull(self, remote, heads=None, force=False, lock=None):
1219 def pull(self, remote, heads=None, force=False, lock=None):
1231 mylock = False
1220 mylock = False
1232 if not lock:
1221 if not lock:
1233 lock = self.lock()
1222 lock = self.lock()
1234 mylock = True
1223 mylock = True
1235
1224
1236 try:
1225 try:
1237 fetch = self.findincoming(remote, force=force)
1226 fetch = self.findincoming(remote, force=force)
1238 if fetch == [nullid]:
1227 if fetch == [nullid]:
1239 self.ui.status(_("requesting all changes\n"))
1228 self.ui.status(_("requesting all changes\n"))
1240
1229
1241 if not fetch:
1230 if not fetch:
1242 self.ui.status(_("no changes found\n"))
1231 self.ui.status(_("no changes found\n"))
1243 return 0
1232 return 0
1244
1233
1245 if heads is None:
1234 if heads is None:
1246 cg = remote.changegroup(fetch, 'pull')
1235 cg = remote.changegroup(fetch, 'pull')
1247 else:
1236 else:
1248 if 'changegroupsubset' not in remote.capabilities:
1237 if 'changegroupsubset' not in remote.capabilities:
1249 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1238 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1250 cg = remote.changegroupsubset(fetch, heads, 'pull')
1239 cg = remote.changegroupsubset(fetch, heads, 'pull')
1251 return self.addchangegroup(cg, 'pull', remote.url())
1240 return self.addchangegroup(cg, 'pull', remote.url())
1252 finally:
1241 finally:
1253 if mylock:
1242 if mylock:
1254 lock.release()
1243 lock.release()
1255
1244
1256 def push(self, remote, force=False, revs=None):
1245 def push(self, remote, force=False, revs=None):
1257 # there are two ways to push to remote repo:
1246 # there are two ways to push to remote repo:
1258 #
1247 #
1259 # addchangegroup assumes local user can lock remote
1248 # addchangegroup assumes local user can lock remote
1260 # repo (local filesystem, old ssh servers).
1249 # repo (local filesystem, old ssh servers).
1261 #
1250 #
1262 # unbundle assumes local user cannot lock remote repo (new ssh
1251 # unbundle assumes local user cannot lock remote repo (new ssh
1263 # servers, http servers).
1252 # servers, http servers).
1264
1253
1265 if remote.capable('unbundle'):
1254 if remote.capable('unbundle'):
1266 return self.push_unbundle(remote, force, revs)
1255 return self.push_unbundle(remote, force, revs)
1267 return self.push_addchangegroup(remote, force, revs)
1256 return self.push_addchangegroup(remote, force, revs)
1268
1257
1269 def prepush(self, remote, force, revs):
1258 def prepush(self, remote, force, revs):
1270 base = {}
1259 base = {}
1271 remote_heads = remote.heads()
1260 remote_heads = remote.heads()
1272 inc = self.findincoming(remote, base, remote_heads, force=force)
1261 inc = self.findincoming(remote, base, remote_heads, force=force)
1273
1262
1274 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1263 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1275 if revs is not None:
1264 if revs is not None:
1276 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1265 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1277 else:
1266 else:
1278 bases, heads = update, self.changelog.heads()
1267 bases, heads = update, self.changelog.heads()
1279
1268
1280 if not bases:
1269 if not bases:
1281 self.ui.status(_("no changes found\n"))
1270 self.ui.status(_("no changes found\n"))
1282 return None, 1
1271 return None, 1
1283 elif not force:
1272 elif not force:
1284 # check if we're creating new remote heads
1273 # check if we're creating new remote heads
1285 # to be a remote head after push, node must be either
1274 # to be a remote head after push, node must be either
1286 # - unknown locally
1275 # - unknown locally
1287 # - a local outgoing head descended from update
1276 # - a local outgoing head descended from update
1288 # - a remote head that's known locally and not
1277 # - a remote head that's known locally and not
1289 # ancestral to an outgoing head
1278 # ancestral to an outgoing head
1290
1279
1291 warn = 0
1280 warn = 0
1292
1281
1293 if remote_heads == [nullid]:
1282 if remote_heads == [nullid]:
1294 warn = 0
1283 warn = 0
1295 elif not revs and len(heads) > len(remote_heads):
1284 elif not revs and len(heads) > len(remote_heads):
1296 warn = 1
1285 warn = 1
1297 else:
1286 else:
1298 newheads = list(heads)
1287 newheads = list(heads)
1299 for r in remote_heads:
1288 for r in remote_heads:
1300 if r in self.changelog.nodemap:
1289 if r in self.changelog.nodemap:
1301 desc = self.changelog.heads(r, heads)
1290 desc = self.changelog.heads(r, heads)
1302 l = [h for h in heads if h in desc]
1291 l = [h for h in heads if h in desc]
1303 if not l:
1292 if not l:
1304 newheads.append(r)
1293 newheads.append(r)
1305 else:
1294 else:
1306 newheads.append(r)
1295 newheads.append(r)
1307 if len(newheads) > len(remote_heads):
1296 if len(newheads) > len(remote_heads):
1308 warn = 1
1297 warn = 1
1309
1298
1310 if warn:
1299 if warn:
1311 self.ui.warn(_("abort: push creates new remote branches!\n"))
1300 self.ui.warn(_("abort: push creates new remote branches!\n"))
1312 self.ui.status(_("(did you forget to merge?"
1301 self.ui.status(_("(did you forget to merge?"
1313 " use push -f to force)\n"))
1302 " use push -f to force)\n"))
1314 return None, 1
1303 return None, 1
1315 elif inc:
1304 elif inc:
1316 self.ui.warn(_("note: unsynced remote changes!\n"))
1305 self.ui.warn(_("note: unsynced remote changes!\n"))
1317
1306
1318
1307
1319 if revs is None:
1308 if revs is None:
1320 cg = self.changegroup(update, 'push')
1309 cg = self.changegroup(update, 'push')
1321 else:
1310 else:
1322 cg = self.changegroupsubset(update, revs, 'push')
1311 cg = self.changegroupsubset(update, revs, 'push')
1323 return cg, remote_heads
1312 return cg, remote_heads
1324
1313
1325 def push_addchangegroup(self, remote, force, revs):
1314 def push_addchangegroup(self, remote, force, revs):
1326 lock = remote.lock()
1315 lock = remote.lock()
1327
1316
1328 ret = self.prepush(remote, force, revs)
1317 ret = self.prepush(remote, force, revs)
1329 if ret[0] is not None:
1318 if ret[0] is not None:
1330 cg, remote_heads = ret
1319 cg, remote_heads = ret
1331 return remote.addchangegroup(cg, 'push', self.url())
1320 return remote.addchangegroup(cg, 'push', self.url())
1332 return ret[1]
1321 return ret[1]
1333
1322
1334 def push_unbundle(self, remote, force, revs):
1323 def push_unbundle(self, remote, force, revs):
1335 # local repo finds heads on server, finds out what revs it
1324 # local repo finds heads on server, finds out what revs it
1336 # must push. once revs transferred, if server finds it has
1325 # must push. once revs transferred, if server finds it has
1337 # different heads (someone else won commit/push race), server
1326 # different heads (someone else won commit/push race), server
1338 # aborts.
1327 # aborts.
1339
1328
1340 ret = self.prepush(remote, force, revs)
1329 ret = self.prepush(remote, force, revs)
1341 if ret[0] is not None:
1330 if ret[0] is not None:
1342 cg, remote_heads = ret
1331 cg, remote_heads = ret
1343 if force: remote_heads = ['force']
1332 if force: remote_heads = ['force']
1344 return remote.unbundle(cg, remote_heads, 'push')
1333 return remote.unbundle(cg, remote_heads, 'push')
1345 return ret[1]
1334 return ret[1]
1346
1335
1347 def changegroupinfo(self, nodes):
1336 def changegroupinfo(self, nodes):
1348 self.ui.note(_("%d changesets found\n") % len(nodes))
1337 self.ui.note(_("%d changesets found\n") % len(nodes))
1349 if self.ui.debugflag:
1338 if self.ui.debugflag:
1350 self.ui.debug(_("List of changesets:\n"))
1339 self.ui.debug(_("List of changesets:\n"))
1351 for node in nodes:
1340 for node in nodes:
1352 self.ui.debug("%s\n" % hex(node))
1341 self.ui.debug("%s\n" % hex(node))
1353
1342
1354 def changegroupsubset(self, bases, heads, source):
1343 def changegroupsubset(self, bases, heads, source):
1355 """This function generates a changegroup consisting of all the nodes
1344 """This function generates a changegroup consisting of all the nodes
1356 that are descendents of any of the bases, and ancestors of any of
1345 that are descendents of any of the bases, and ancestors of any of
1357 the heads.
1346 the heads.
1358
1347
1359 It is fairly complex as determining which filenodes and which
1348 It is fairly complex as determining which filenodes and which
1360 manifest nodes need to be included for the changeset to be complete
1349 manifest nodes need to be included for the changeset to be complete
1361 is non-trivial.
1350 is non-trivial.
1362
1351
1363 Another wrinkle is doing the reverse, figuring out which changeset in
1352 Another wrinkle is doing the reverse, figuring out which changeset in
1364 the changegroup a particular filenode or manifestnode belongs to."""
1353 the changegroup a particular filenode or manifestnode belongs to."""
1365
1354
1366 self.hook('preoutgoing', throw=True, source=source)
1355 self.hook('preoutgoing', throw=True, source=source)
1367
1356
1368 # Set up some initial variables
1357 # Set up some initial variables
1369 # Make it easy to refer to self.changelog
1358 # Make it easy to refer to self.changelog
1370 cl = self.changelog
1359 cl = self.changelog
1371 # msng is short for missing - compute the list of changesets in this
1360 # msng is short for missing - compute the list of changesets in this
1372 # changegroup.
1361 # changegroup.
1373 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1362 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1374 self.changegroupinfo(msng_cl_lst)
1363 self.changegroupinfo(msng_cl_lst)
1375 # Some bases may turn out to be superfluous, and some heads may be
1364 # Some bases may turn out to be superfluous, and some heads may be
1376 # too. nodesbetween will return the minimal set of bases and heads
1365 # too. nodesbetween will return the minimal set of bases and heads
1377 # necessary to re-create the changegroup.
1366 # necessary to re-create the changegroup.
1378
1367
1379 # Known heads are the list of heads that it is assumed the recipient
1368 # Known heads are the list of heads that it is assumed the recipient
1380 # of this changegroup will know about.
1369 # of this changegroup will know about.
1381 knownheads = {}
1370 knownheads = {}
1382 # We assume that all parents of bases are known heads.
1371 # We assume that all parents of bases are known heads.
1383 for n in bases:
1372 for n in bases:
1384 for p in cl.parents(n):
1373 for p in cl.parents(n):
1385 if p != nullid:
1374 if p != nullid:
1386 knownheads[p] = 1
1375 knownheads[p] = 1
1387 knownheads = knownheads.keys()
1376 knownheads = knownheads.keys()
1388 if knownheads:
1377 if knownheads:
1389 # Now that we know what heads are known, we can compute which
1378 # Now that we know what heads are known, we can compute which
1390 # changesets are known. The recipient must know about all
1379 # changesets are known. The recipient must know about all
1391 # changesets required to reach the known heads from the null
1380 # changesets required to reach the known heads from the null
1392 # changeset.
1381 # changeset.
1393 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1382 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1394 junk = None
1383 junk = None
1395 # Transform the list into an ersatz set.
1384 # Transform the list into an ersatz set.
1396 has_cl_set = dict.fromkeys(has_cl_set)
1385 has_cl_set = dict.fromkeys(has_cl_set)
1397 else:
1386 else:
1398 # If there were no known heads, the recipient cannot be assumed to
1387 # If there were no known heads, the recipient cannot be assumed to
1399 # know about any changesets.
1388 # know about any changesets.
1400 has_cl_set = {}
1389 has_cl_set = {}
1401
1390
1402 # Make it easy to refer to self.manifest
1391 # Make it easy to refer to self.manifest
1403 mnfst = self.manifest
1392 mnfst = self.manifest
1404 # We don't know which manifests are missing yet
1393 # We don't know which manifests are missing yet
1405 msng_mnfst_set = {}
1394 msng_mnfst_set = {}
1406 # Nor do we know which filenodes are missing.
1395 # Nor do we know which filenodes are missing.
1407 msng_filenode_set = {}
1396 msng_filenode_set = {}
1408
1397
1409 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1398 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1410 junk = None
1399 junk = None
1411
1400
1412 # A changeset always belongs to itself, so the changenode lookup
1401 # A changeset always belongs to itself, so the changenode lookup
1413 # function for a changenode is identity.
1402 # function for a changenode is identity.
1414 def identity(x):
1403 def identity(x):
1415 return x
1404 return x
1416
1405
1417 # A function generating function. Sets up an environment for the
1406 # A function generating function. Sets up an environment for the
1418 # inner function.
1407 # inner function.
1419 def cmp_by_rev_func(revlog):
1408 def cmp_by_rev_func(revlog):
1420 # Compare two nodes by their revision number in the environment's
1409 # Compare two nodes by their revision number in the environment's
1421 # revision history. Since the revision number both represents the
1410 # revision history. Since the revision number both represents the
1422 # most efficient order to read the nodes in, and represents a
1411 # most efficient order to read the nodes in, and represents a
1423 # topological sorting of the nodes, this function is often useful.
1412 # topological sorting of the nodes, this function is often useful.
1424 def cmp_by_rev(a, b):
1413 def cmp_by_rev(a, b):
1425 return cmp(revlog.rev(a), revlog.rev(b))
1414 return cmp(revlog.rev(a), revlog.rev(b))
1426 return cmp_by_rev
1415 return cmp_by_rev
1427
1416
1428 # If we determine that a particular file or manifest node must be a
1417 # If we determine that a particular file or manifest node must be a
1429 # node that the recipient of the changegroup will already have, we can
1418 # node that the recipient of the changegroup will already have, we can
1430 # also assume the recipient will have all the parents. This function
1419 # also assume the recipient will have all the parents. This function
1431 # prunes them from the set of missing nodes.
1420 # prunes them from the set of missing nodes.
1432 def prune_parents(revlog, hasset, msngset):
1421 def prune_parents(revlog, hasset, msngset):
1433 haslst = hasset.keys()
1422 haslst = hasset.keys()
1434 haslst.sort(cmp_by_rev_func(revlog))
1423 haslst.sort(cmp_by_rev_func(revlog))
1435 for node in haslst:
1424 for node in haslst:
1436 parentlst = [p for p in revlog.parents(node) if p != nullid]
1425 parentlst = [p for p in revlog.parents(node) if p != nullid]
1437 while parentlst:
1426 while parentlst:
1438 n = parentlst.pop()
1427 n = parentlst.pop()
1439 if n not in hasset:
1428 if n not in hasset:
1440 hasset[n] = 1
1429 hasset[n] = 1
1441 p = [p for p in revlog.parents(n) if p != nullid]
1430 p = [p for p in revlog.parents(n) if p != nullid]
1442 parentlst.extend(p)
1431 parentlst.extend(p)
1443 for n in hasset:
1432 for n in hasset:
1444 msngset.pop(n, None)
1433 msngset.pop(n, None)
1445
1434
1446 # This is a function generating function used to set up an environment
1435 # This is a function generating function used to set up an environment
1447 # for the inner function to execute in.
1436 # for the inner function to execute in.
1448 def manifest_and_file_collector(changedfileset):
1437 def manifest_and_file_collector(changedfileset):
1449 # This is an information gathering function that gathers
1438 # This is an information gathering function that gathers
1450 # information from each changeset node that goes out as part of
1439 # information from each changeset node that goes out as part of
1451 # the changegroup. The information gathered is a list of which
1440 # the changegroup. The information gathered is a list of which
1452 # manifest nodes are potentially required (the recipient may
1441 # manifest nodes are potentially required (the recipient may
1453 # already have them) and total list of all files which were
1442 # already have them) and total list of all files which were
1454 # changed in any changeset in the changegroup.
1443 # changed in any changeset in the changegroup.
1455 #
1444 #
1456 # We also remember the first changenode we saw any manifest
1445 # We also remember the first changenode we saw any manifest
1457 # referenced by so we can later determine which changenode 'owns'
1446 # referenced by so we can later determine which changenode 'owns'
1458 # the manifest.
1447 # the manifest.
1459 def collect_manifests_and_files(clnode):
1448 def collect_manifests_and_files(clnode):
1460 c = cl.read(clnode)
1449 c = cl.read(clnode)
1461 for f in c[3]:
1450 for f in c[3]:
1462 # This is to make sure we only have one instance of each
1451 # This is to make sure we only have one instance of each
1463 # filename string for each filename.
1452 # filename string for each filename.
1464 changedfileset.setdefault(f, f)
1453 changedfileset.setdefault(f, f)
1465 msng_mnfst_set.setdefault(c[0], clnode)
1454 msng_mnfst_set.setdefault(c[0], clnode)
1466 return collect_manifests_and_files
1455 return collect_manifests_and_files
1467
1456
1468 # Figure out which manifest nodes (of the ones we think might be part
1457 # Figure out which manifest nodes (of the ones we think might be part
1469 # of the changegroup) the recipient must know about and remove them
1458 # of the changegroup) the recipient must know about and remove them
1470 # from the changegroup.
1459 # from the changegroup.
1471 def prune_manifests():
1460 def prune_manifests():
1472 has_mnfst_set = {}
1461 has_mnfst_set = {}
1473 for n in msng_mnfst_set:
1462 for n in msng_mnfst_set:
1474 # If a 'missing' manifest thinks it belongs to a changenode
1463 # If a 'missing' manifest thinks it belongs to a changenode
1475 # the recipient is assumed to have, obviously the recipient
1464 # the recipient is assumed to have, obviously the recipient
1476 # must have that manifest.
1465 # must have that manifest.
1477 linknode = cl.node(mnfst.linkrev(n))
1466 linknode = cl.node(mnfst.linkrev(n))
1478 if linknode in has_cl_set:
1467 if linknode in has_cl_set:
1479 has_mnfst_set[n] = 1
1468 has_mnfst_set[n] = 1
1480 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1469 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1481
1470
1482 # Use the information collected in collect_manifests_and_files to say
1471 # Use the information collected in collect_manifests_and_files to say
1483 # which changenode any manifestnode belongs to.
1472 # which changenode any manifestnode belongs to.
1484 def lookup_manifest_link(mnfstnode):
1473 def lookup_manifest_link(mnfstnode):
1485 return msng_mnfst_set[mnfstnode]
1474 return msng_mnfst_set[mnfstnode]
1486
1475
1487 # A function generating function that sets up the initial environment
1476 # A function generating function that sets up the initial environment
1488 # the inner function.
1477 # the inner function.
1489 def filenode_collector(changedfiles):
1478 def filenode_collector(changedfiles):
1490 next_rev = [0]
1479 next_rev = [0]
1491 # This gathers information from each manifestnode included in the
1480 # This gathers information from each manifestnode included in the
1492 # changegroup about which filenodes the manifest node references
1481 # changegroup about which filenodes the manifest node references
1493 # so we can include those in the changegroup too.
1482 # so we can include those in the changegroup too.
1494 #
1483 #
1495 # It also remembers which changenode each filenode belongs to. It
1484 # It also remembers which changenode each filenode belongs to. It
1496 # does this by assuming the a filenode belongs to the changenode
1485 # does this by assuming the a filenode belongs to the changenode
1497 # the first manifest that references it belongs to.
1486 # the first manifest that references it belongs to.
1498 def collect_msng_filenodes(mnfstnode):
1487 def collect_msng_filenodes(mnfstnode):
1499 r = mnfst.rev(mnfstnode)
1488 r = mnfst.rev(mnfstnode)
1500 if r == next_rev[0]:
1489 if r == next_rev[0]:
1501 # If the last rev we looked at was the one just previous,
1490 # If the last rev we looked at was the one just previous,
1502 # we only need to see a diff.
1491 # we only need to see a diff.
1503 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1492 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1504 # For each line in the delta
1493 # For each line in the delta
1505 for dline in delta.splitlines():
1494 for dline in delta.splitlines():
1506 # get the filename and filenode for that line
1495 # get the filename and filenode for that line
1507 f, fnode = dline.split('\0')
1496 f, fnode = dline.split('\0')
1508 fnode = bin(fnode[:40])
1497 fnode = bin(fnode[:40])
1509 f = changedfiles.get(f, None)
1498 f = changedfiles.get(f, None)
1510 # And if the file is in the list of files we care
1499 # And if the file is in the list of files we care
1511 # about.
1500 # about.
1512 if f is not None:
1501 if f is not None:
1513 # Get the changenode this manifest belongs to
1502 # Get the changenode this manifest belongs to
1514 clnode = msng_mnfst_set[mnfstnode]
1503 clnode = msng_mnfst_set[mnfstnode]
1515 # Create the set of filenodes for the file if
1504 # Create the set of filenodes for the file if
1516 # there isn't one already.
1505 # there isn't one already.
1517 ndset = msng_filenode_set.setdefault(f, {})
1506 ndset = msng_filenode_set.setdefault(f, {})
1518 # And set the filenode's changelog node to the
1507 # And set the filenode's changelog node to the
1519 # manifest's if it hasn't been set already.
1508 # manifest's if it hasn't been set already.
1520 ndset.setdefault(fnode, clnode)
1509 ndset.setdefault(fnode, clnode)
1521 else:
1510 else:
1522 # Otherwise we need a full manifest.
1511 # Otherwise we need a full manifest.
1523 m = mnfst.read(mnfstnode)
1512 m = mnfst.read(mnfstnode)
1524 # For every file in we care about.
1513 # For every file in we care about.
1525 for f in changedfiles:
1514 for f in changedfiles:
1526 fnode = m.get(f, None)
1515 fnode = m.get(f, None)
1527 # If it's in the manifest
1516 # If it's in the manifest
1528 if fnode is not None:
1517 if fnode is not None:
1529 # See comments above.
1518 # See comments above.
1530 clnode = msng_mnfst_set[mnfstnode]
1519 clnode = msng_mnfst_set[mnfstnode]
1531 ndset = msng_filenode_set.setdefault(f, {})
1520 ndset = msng_filenode_set.setdefault(f, {})
1532 ndset.setdefault(fnode, clnode)
1521 ndset.setdefault(fnode, clnode)
1533 # Remember the revision we hope to see next.
1522 # Remember the revision we hope to see next.
1534 next_rev[0] = r + 1
1523 next_rev[0] = r + 1
1535 return collect_msng_filenodes
1524 return collect_msng_filenodes
1536
1525
1537 # We have a list of filenodes we think we need for a file, lets remove
1526 # We have a list of filenodes we think we need for a file, lets remove
1538 # all those we now the recipient must have.
1527 # all those we now the recipient must have.
1539 def prune_filenodes(f, filerevlog):
1528 def prune_filenodes(f, filerevlog):
1540 msngset = msng_filenode_set[f]
1529 msngset = msng_filenode_set[f]
1541 hasset = {}
1530 hasset = {}
1542 # If a 'missing' filenode thinks it belongs to a changenode we
1531 # If a 'missing' filenode thinks it belongs to a changenode we
1543 # assume the recipient must have, then the recipient must have
1532 # assume the recipient must have, then the recipient must have
1544 # that filenode.
1533 # that filenode.
1545 for n in msngset:
1534 for n in msngset:
1546 clnode = cl.node(filerevlog.linkrev(n))
1535 clnode = cl.node(filerevlog.linkrev(n))
1547 if clnode in has_cl_set:
1536 if clnode in has_cl_set:
1548 hasset[n] = 1
1537 hasset[n] = 1
1549 prune_parents(filerevlog, hasset, msngset)
1538 prune_parents(filerevlog, hasset, msngset)
1550
1539
1551 # A function generator function that sets up the a context for the
1540 # A function generator function that sets up the a context for the
1552 # inner function.
1541 # inner function.
1553 def lookup_filenode_link_func(fname):
1542 def lookup_filenode_link_func(fname):
1554 msngset = msng_filenode_set[fname]
1543 msngset = msng_filenode_set[fname]
1555 # Lookup the changenode the filenode belongs to.
1544 # Lookup the changenode the filenode belongs to.
1556 def lookup_filenode_link(fnode):
1545 def lookup_filenode_link(fnode):
1557 return msngset[fnode]
1546 return msngset[fnode]
1558 return lookup_filenode_link
1547 return lookup_filenode_link
1559
1548
1560 # Now that we have all theses utility functions to help out and
1549 # Now that we have all theses utility functions to help out and
1561 # logically divide up the task, generate the group.
1550 # logically divide up the task, generate the group.
1562 def gengroup():
1551 def gengroup():
1563 # The set of changed files starts empty.
1552 # The set of changed files starts empty.
1564 changedfiles = {}
1553 changedfiles = {}
1565 # Create a changenode group generator that will call our functions
1554 # Create a changenode group generator that will call our functions
1566 # back to lookup the owning changenode and collect information.
1555 # back to lookup the owning changenode and collect information.
1567 group = cl.group(msng_cl_lst, identity,
1556 group = cl.group(msng_cl_lst, identity,
1568 manifest_and_file_collector(changedfiles))
1557 manifest_and_file_collector(changedfiles))
1569 for chnk in group:
1558 for chnk in group:
1570 yield chnk
1559 yield chnk
1571
1560
1572 # The list of manifests has been collected by the generator
1561 # The list of manifests has been collected by the generator
1573 # calling our functions back.
1562 # calling our functions back.
1574 prune_manifests()
1563 prune_manifests()
1575 msng_mnfst_lst = msng_mnfst_set.keys()
1564 msng_mnfst_lst = msng_mnfst_set.keys()
1576 # Sort the manifestnodes by revision number.
1565 # Sort the manifestnodes by revision number.
1577 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1566 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1578 # Create a generator for the manifestnodes that calls our lookup
1567 # Create a generator for the manifestnodes that calls our lookup
1579 # and data collection functions back.
1568 # and data collection functions back.
1580 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1569 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1581 filenode_collector(changedfiles))
1570 filenode_collector(changedfiles))
1582 for chnk in group:
1571 for chnk in group:
1583 yield chnk
1572 yield chnk
1584
1573
1585 # These are no longer needed, dereference and toss the memory for
1574 # These are no longer needed, dereference and toss the memory for
1586 # them.
1575 # them.
1587 msng_mnfst_lst = None
1576 msng_mnfst_lst = None
1588 msng_mnfst_set.clear()
1577 msng_mnfst_set.clear()
1589
1578
1590 changedfiles = changedfiles.keys()
1579 changedfiles = changedfiles.keys()
1591 changedfiles.sort()
1580 changedfiles.sort()
1592 # Go through all our files in order sorted by name.
1581 # Go through all our files in order sorted by name.
1593 for fname in changedfiles:
1582 for fname in changedfiles:
1594 filerevlog = self.file(fname)
1583 filerevlog = self.file(fname)
1595 # Toss out the filenodes that the recipient isn't really
1584 # Toss out the filenodes that the recipient isn't really
1596 # missing.
1585 # missing.
1597 if msng_filenode_set.has_key(fname):
1586 if msng_filenode_set.has_key(fname):
1598 prune_filenodes(fname, filerevlog)
1587 prune_filenodes(fname, filerevlog)
1599 msng_filenode_lst = msng_filenode_set[fname].keys()
1588 msng_filenode_lst = msng_filenode_set[fname].keys()
1600 else:
1589 else:
1601 msng_filenode_lst = []
1590 msng_filenode_lst = []
1602 # If any filenodes are left, generate the group for them,
1591 # If any filenodes are left, generate the group for them,
1603 # otherwise don't bother.
1592 # otherwise don't bother.
1604 if len(msng_filenode_lst) > 0:
1593 if len(msng_filenode_lst) > 0:
1605 yield changegroup.genchunk(fname)
1594 yield changegroup.genchunk(fname)
1606 # Sort the filenodes by their revision #
1595 # Sort the filenodes by their revision #
1607 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1596 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1608 # Create a group generator and only pass in a changenode
1597 # Create a group generator and only pass in a changenode
1609 # lookup function as we need to collect no information
1598 # lookup function as we need to collect no information
1610 # from filenodes.
1599 # from filenodes.
1611 group = filerevlog.group(msng_filenode_lst,
1600 group = filerevlog.group(msng_filenode_lst,
1612 lookup_filenode_link_func(fname))
1601 lookup_filenode_link_func(fname))
1613 for chnk in group:
1602 for chnk in group:
1614 yield chnk
1603 yield chnk
1615 if msng_filenode_set.has_key(fname):
1604 if msng_filenode_set.has_key(fname):
1616 # Don't need this anymore, toss it to free memory.
1605 # Don't need this anymore, toss it to free memory.
1617 del msng_filenode_set[fname]
1606 del msng_filenode_set[fname]
1618 # Signal that no more groups are left.
1607 # Signal that no more groups are left.
1619 yield changegroup.closechunk()
1608 yield changegroup.closechunk()
1620
1609
1621 if msng_cl_lst:
1610 if msng_cl_lst:
1622 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1611 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1623
1612
1624 return util.chunkbuffer(gengroup())
1613 return util.chunkbuffer(gengroup())
1625
1614
1626 def changegroup(self, basenodes, source):
1615 def changegroup(self, basenodes, source):
1627 """Generate a changegroup of all nodes that we have that a recipient
1616 """Generate a changegroup of all nodes that we have that a recipient
1628 doesn't.
1617 doesn't.
1629
1618
1630 This is much easier than the previous function as we can assume that
1619 This is much easier than the previous function as we can assume that
1631 the recipient has any changenode we aren't sending them."""
1620 the recipient has any changenode we aren't sending them."""
1632
1621
1633 self.hook('preoutgoing', throw=True, source=source)
1622 self.hook('preoutgoing', throw=True, source=source)
1634
1623
1635 cl = self.changelog
1624 cl = self.changelog
1636 nodes = cl.nodesbetween(basenodes, None)[0]
1625 nodes = cl.nodesbetween(basenodes, None)[0]
1637 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1626 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1638 self.changegroupinfo(nodes)
1627 self.changegroupinfo(nodes)
1639
1628
1640 def identity(x):
1629 def identity(x):
1641 return x
1630 return x
1642
1631
1643 def gennodelst(revlog):
1632 def gennodelst(revlog):
1644 for r in xrange(0, revlog.count()):
1633 for r in xrange(0, revlog.count()):
1645 n = revlog.node(r)
1634 n = revlog.node(r)
1646 if revlog.linkrev(n) in revset:
1635 if revlog.linkrev(n) in revset:
1647 yield n
1636 yield n
1648
1637
1649 def changed_file_collector(changedfileset):
1638 def changed_file_collector(changedfileset):
1650 def collect_changed_files(clnode):
1639 def collect_changed_files(clnode):
1651 c = cl.read(clnode)
1640 c = cl.read(clnode)
1652 for fname in c[3]:
1641 for fname in c[3]:
1653 changedfileset[fname] = 1
1642 changedfileset[fname] = 1
1654 return collect_changed_files
1643 return collect_changed_files
1655
1644
1656 def lookuprevlink_func(revlog):
1645 def lookuprevlink_func(revlog):
1657 def lookuprevlink(n):
1646 def lookuprevlink(n):
1658 return cl.node(revlog.linkrev(n))
1647 return cl.node(revlog.linkrev(n))
1659 return lookuprevlink
1648 return lookuprevlink
1660
1649
1661 def gengroup():
1650 def gengroup():
1662 # construct a list of all changed files
1651 # construct a list of all changed files
1663 changedfiles = {}
1652 changedfiles = {}
1664
1653
1665 for chnk in cl.group(nodes, identity,
1654 for chnk in cl.group(nodes, identity,
1666 changed_file_collector(changedfiles)):
1655 changed_file_collector(changedfiles)):
1667 yield chnk
1656 yield chnk
1668 changedfiles = changedfiles.keys()
1657 changedfiles = changedfiles.keys()
1669 changedfiles.sort()
1658 changedfiles.sort()
1670
1659
1671 mnfst = self.manifest
1660 mnfst = self.manifest
1672 nodeiter = gennodelst(mnfst)
1661 nodeiter = gennodelst(mnfst)
1673 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1662 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1674 yield chnk
1663 yield chnk
1675
1664
1676 for fname in changedfiles:
1665 for fname in changedfiles:
1677 filerevlog = self.file(fname)
1666 filerevlog = self.file(fname)
1678 nodeiter = gennodelst(filerevlog)
1667 nodeiter = gennodelst(filerevlog)
1679 nodeiter = list(nodeiter)
1668 nodeiter = list(nodeiter)
1680 if nodeiter:
1669 if nodeiter:
1681 yield changegroup.genchunk(fname)
1670 yield changegroup.genchunk(fname)
1682 lookup = lookuprevlink_func(filerevlog)
1671 lookup = lookuprevlink_func(filerevlog)
1683 for chnk in filerevlog.group(nodeiter, lookup):
1672 for chnk in filerevlog.group(nodeiter, lookup):
1684 yield chnk
1673 yield chnk
1685
1674
1686 yield changegroup.closechunk()
1675 yield changegroup.closechunk()
1687
1676
1688 if nodes:
1677 if nodes:
1689 self.hook('outgoing', node=hex(nodes[0]), source=source)
1678 self.hook('outgoing', node=hex(nodes[0]), source=source)
1690
1679
1691 return util.chunkbuffer(gengroup())
1680 return util.chunkbuffer(gengroup())
1692
1681
1693 def addchangegroup(self, source, srctype, url):
1682 def addchangegroup(self, source, srctype, url):
1694 """add changegroup to repo.
1683 """add changegroup to repo.
1695
1684
1696 return values:
1685 return values:
1697 - nothing changed or no source: 0
1686 - nothing changed or no source: 0
1698 - more heads than before: 1+added heads (2..n)
1687 - more heads than before: 1+added heads (2..n)
1699 - less heads than before: -1-removed heads (-2..-n)
1688 - less heads than before: -1-removed heads (-2..-n)
1700 - number of heads stays the same: 1
1689 - number of heads stays the same: 1
1701 """
1690 """
1702 def csmap(x):
1691 def csmap(x):
1703 self.ui.debug(_("add changeset %s\n") % short(x))
1692 self.ui.debug(_("add changeset %s\n") % short(x))
1704 return cl.count()
1693 return cl.count()
1705
1694
1706 def revmap(x):
1695 def revmap(x):
1707 return cl.rev(x)
1696 return cl.rev(x)
1708
1697
1709 if not source:
1698 if not source:
1710 return 0
1699 return 0
1711
1700
1712 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1701 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1713
1702
1714 changesets = files = revisions = 0
1703 changesets = files = revisions = 0
1715
1704
1716 tr = self.transaction()
1705 tr = self.transaction()
1717
1706
1718 # write changelog data to temp files so concurrent readers will not see
1707 # write changelog data to temp files so concurrent readers will not see
1719 # inconsistent view
1708 # inconsistent view
1720 cl = None
1709 cl = None
1721 try:
1710 try:
1722 cl = appendfile.appendchangelog(self.sopener,
1711 cl = appendfile.appendchangelog(self.sopener,
1723 self.changelog.version)
1712 self.changelog.version)
1724
1713
1725 oldheads = len(cl.heads())
1714 oldheads = len(cl.heads())
1726
1715
1727 # pull off the changeset group
1716 # pull off the changeset group
1728 self.ui.status(_("adding changesets\n"))
1717 self.ui.status(_("adding changesets\n"))
1729 cor = cl.count() - 1
1718 cor = cl.count() - 1
1730 chunkiter = changegroup.chunkiter(source)
1719 chunkiter = changegroup.chunkiter(source)
1731 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1720 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1732 raise util.Abort(_("received changelog group is empty"))
1721 raise util.Abort(_("received changelog group is empty"))
1733 cnr = cl.count() - 1
1722 cnr = cl.count() - 1
1734 changesets = cnr - cor
1723 changesets = cnr - cor
1735
1724
1736 # pull off the manifest group
1725 # pull off the manifest group
1737 self.ui.status(_("adding manifests\n"))
1726 self.ui.status(_("adding manifests\n"))
1738 chunkiter = changegroup.chunkiter(source)
1727 chunkiter = changegroup.chunkiter(source)
1739 # no need to check for empty manifest group here:
1728 # no need to check for empty manifest group here:
1740 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1729 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1741 # no new manifest will be created and the manifest group will
1730 # no new manifest will be created and the manifest group will
1742 # be empty during the pull
1731 # be empty during the pull
1743 self.manifest.addgroup(chunkiter, revmap, tr)
1732 self.manifest.addgroup(chunkiter, revmap, tr)
1744
1733
1745 # process the files
1734 # process the files
1746 self.ui.status(_("adding file changes\n"))
1735 self.ui.status(_("adding file changes\n"))
1747 while 1:
1736 while 1:
1748 f = changegroup.getchunk(source)
1737 f = changegroup.getchunk(source)
1749 if not f:
1738 if not f:
1750 break
1739 break
1751 self.ui.debug(_("adding %s revisions\n") % f)
1740 self.ui.debug(_("adding %s revisions\n") % f)
1752 fl = self.file(f)
1741 fl = self.file(f)
1753 o = fl.count()
1742 o = fl.count()
1754 chunkiter = changegroup.chunkiter(source)
1743 chunkiter = changegroup.chunkiter(source)
1755 if fl.addgroup(chunkiter, revmap, tr) is None:
1744 if fl.addgroup(chunkiter, revmap, tr) is None:
1756 raise util.Abort(_("received file revlog group is empty"))
1745 raise util.Abort(_("received file revlog group is empty"))
1757 revisions += fl.count() - o
1746 revisions += fl.count() - o
1758 files += 1
1747 files += 1
1759
1748
1760 cl.writedata()
1749 cl.writedata()
1761 finally:
1750 finally:
1762 if cl:
1751 if cl:
1763 cl.cleanup()
1752 cl.cleanup()
1764
1753
1765 # make changelog see real files again
1754 # make changelog see real files again
1766 self.changelog = changelog.changelog(self.sopener,
1755 self.changelog = changelog.changelog(self.sopener,
1767 self.changelog.version)
1756 self.changelog.version)
1768 self.changelog.checkinlinesize(tr)
1757 self.changelog.checkinlinesize(tr)
1769
1758
1770 newheads = len(self.changelog.heads())
1759 newheads = len(self.changelog.heads())
1771 heads = ""
1760 heads = ""
1772 if oldheads and newheads != oldheads:
1761 if oldheads and newheads != oldheads:
1773 heads = _(" (%+d heads)") % (newheads - oldheads)
1762 heads = _(" (%+d heads)") % (newheads - oldheads)
1774
1763
1775 self.ui.status(_("added %d changesets"
1764 self.ui.status(_("added %d changesets"
1776 " with %d changes to %d files%s\n")
1765 " with %d changes to %d files%s\n")
1777 % (changesets, revisions, files, heads))
1766 % (changesets, revisions, files, heads))
1778
1767
1779 if changesets > 0:
1768 if changesets > 0:
1780 self.hook('pretxnchangegroup', throw=True,
1769 self.hook('pretxnchangegroup', throw=True,
1781 node=hex(self.changelog.node(cor+1)), source=srctype,
1770 node=hex(self.changelog.node(cor+1)), source=srctype,
1782 url=url)
1771 url=url)
1783
1772
1784 tr.close()
1773 tr.close()
1785
1774
1786 if changesets > 0:
1775 if changesets > 0:
1787 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1776 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1788 source=srctype, url=url)
1777 source=srctype, url=url)
1789
1778
1790 for i in xrange(cor + 1, cnr + 1):
1779 for i in xrange(cor + 1, cnr + 1):
1791 self.hook("incoming", node=hex(self.changelog.node(i)),
1780 self.hook("incoming", node=hex(self.changelog.node(i)),
1792 source=srctype, url=url)
1781 source=srctype, url=url)
1793
1782
1794 # never return 0 here:
1783 # never return 0 here:
1795 if newheads < oldheads:
1784 if newheads < oldheads:
1796 return newheads - oldheads - 1
1785 return newheads - oldheads - 1
1797 else:
1786 else:
1798 return newheads - oldheads + 1
1787 return newheads - oldheads + 1
1799
1788
1800
1789
1801 def stream_in(self, remote):
1790 def stream_in(self, remote):
1802 fp = remote.stream_out()
1791 fp = remote.stream_out()
1803 l = fp.readline()
1792 l = fp.readline()
1804 try:
1793 try:
1805 resp = int(l)
1794 resp = int(l)
1806 except ValueError:
1795 except ValueError:
1807 raise util.UnexpectedOutput(
1796 raise util.UnexpectedOutput(
1808 _('Unexpected response from remote server:'), l)
1797 _('Unexpected response from remote server:'), l)
1809 if resp == 1:
1798 if resp == 1:
1810 raise util.Abort(_('operation forbidden by server'))
1799 raise util.Abort(_('operation forbidden by server'))
1811 elif resp == 2:
1800 elif resp == 2:
1812 raise util.Abort(_('locking the remote repository failed'))
1801 raise util.Abort(_('locking the remote repository failed'))
1813 elif resp != 0:
1802 elif resp != 0:
1814 raise util.Abort(_('the server sent an unknown error code'))
1803 raise util.Abort(_('the server sent an unknown error code'))
1815 self.ui.status(_('streaming all changes\n'))
1804 self.ui.status(_('streaming all changes\n'))
1816 l = fp.readline()
1805 l = fp.readline()
1817 try:
1806 try:
1818 total_files, total_bytes = map(int, l.split(' ', 1))
1807 total_files, total_bytes = map(int, l.split(' ', 1))
1819 except ValueError, TypeError:
1808 except ValueError, TypeError:
1820 raise util.UnexpectedOutput(
1809 raise util.UnexpectedOutput(
1821 _('Unexpected response from remote server:'), l)
1810 _('Unexpected response from remote server:'), l)
1822 self.ui.status(_('%d files to transfer, %s of data\n') %
1811 self.ui.status(_('%d files to transfer, %s of data\n') %
1823 (total_files, util.bytecount(total_bytes)))
1812 (total_files, util.bytecount(total_bytes)))
1824 start = time.time()
1813 start = time.time()
1825 for i in xrange(total_files):
1814 for i in xrange(total_files):
1826 # XXX doesn't support '\n' or '\r' in filenames
1815 # XXX doesn't support '\n' or '\r' in filenames
1827 l = fp.readline()
1816 l = fp.readline()
1828 try:
1817 try:
1829 name, size = l.split('\0', 1)
1818 name, size = l.split('\0', 1)
1830 size = int(size)
1819 size = int(size)
1831 except ValueError, TypeError:
1820 except ValueError, TypeError:
1832 raise util.UnexpectedOutput(
1821 raise util.UnexpectedOutput(
1833 _('Unexpected response from remote server:'), l)
1822 _('Unexpected response from remote server:'), l)
1834 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1823 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1835 ofp = self.sopener(name, 'w')
1824 ofp = self.sopener(name, 'w')
1836 for chunk in util.filechunkiter(fp, limit=size):
1825 for chunk in util.filechunkiter(fp, limit=size):
1837 ofp.write(chunk)
1826 ofp.write(chunk)
1838 ofp.close()
1827 ofp.close()
1839 elapsed = time.time() - start
1828 elapsed = time.time() - start
1840 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1829 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1841 (util.bytecount(total_bytes), elapsed,
1830 (util.bytecount(total_bytes), elapsed,
1842 util.bytecount(total_bytes / elapsed)))
1831 util.bytecount(total_bytes / elapsed)))
1843 self.reload()
1832 self.reload()
1844 return len(self.heads()) + 1
1833 return len(self.heads()) + 1
1845
1834
1846 def clone(self, remote, heads=[], stream=False):
1835 def clone(self, remote, heads=[], stream=False):
1847 '''clone remote repository.
1836 '''clone remote repository.
1848
1837
1849 keyword arguments:
1838 keyword arguments:
1850 heads: list of revs to clone (forces use of pull)
1839 heads: list of revs to clone (forces use of pull)
1851 stream: use streaming clone if possible'''
1840 stream: use streaming clone if possible'''
1852
1841
1853 # now, all clients that can request uncompressed clones can
1842 # now, all clients that can request uncompressed clones can
1854 # read repo formats supported by all servers that can serve
1843 # read repo formats supported by all servers that can serve
1855 # them.
1844 # them.
1856
1845
1857 # if revlog format changes, client will have to check version
1846 # if revlog format changes, client will have to check version
1858 # and format flags on "stream" capability, and use
1847 # and format flags on "stream" capability, and use
1859 # uncompressed only if compatible.
1848 # uncompressed only if compatible.
1860
1849
1861 if stream and not heads and remote.capable('stream'):
1850 if stream and not heads and remote.capable('stream'):
1862 return self.stream_in(remote)
1851 return self.stream_in(remote)
1863 return self.pull(remote, heads)
1852 return self.pull(remote, heads)
1864
1853
1865 # used to avoid circular references so destructors work
1854 # used to avoid circular references so destructors work
1866 def aftertrans(files):
1855 def aftertrans(files):
1867 renamefiles = [tuple(t) for t in files]
1856 renamefiles = [tuple(t) for t in files]
1868 def a():
1857 def a():
1869 for src, dest in renamefiles:
1858 for src, dest in renamefiles:
1870 util.rename(src, dest)
1859 util.rename(src, dest)
1871 return a
1860 return a
1872
1861
1873 def instance(ui, path, create):
1862 def instance(ui, path, create):
1874 return localrepository(ui, util.drop_scheme('file', path), create)
1863 return localrepository(ui, util.drop_scheme('file', path), create)
1875
1864
1876 def islocal(path):
1865 def islocal(path):
1877 return True
1866 return True
General Comments 0
You need to be logged in to leave comments. Login now