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