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