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