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