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