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