##// END OF EJS Templates
stream_in: avoid debug calls when debug is disabled
Matt Mackall -
r16398:def78975 default
parent child Browse files
Show More
@@ -1,2326 +1,2328 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]
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 def lookup(revlog, x):
1839 def lookup(revlog, x):
1840 if revlog == cl:
1840 if revlog == cl:
1841 c = cl.read(x)
1841 c = cl.read(x)
1842 changedfiles.update(c[3])
1842 changedfiles.update(c[3])
1843 mfs.setdefault(c[0], x)
1843 mfs.setdefault(c[0], x)
1844 count[0] += 1
1844 count[0] += 1
1845 self.ui.progress(_('bundling'), count[0],
1845 self.ui.progress(_('bundling'), count[0],
1846 unit=_('changesets'), total=len(csets))
1846 unit=_('changesets'), total=len(csets))
1847 return x
1847 return x
1848 elif revlog == mf:
1848 elif revlog == mf:
1849 clnode = mfs[x]
1849 clnode = mfs[x]
1850 mdata = mf.readfast(x)
1850 mdata = mf.readfast(x)
1851 for f in changedfiles:
1851 for f in changedfiles:
1852 if f in mdata:
1852 if f in mdata:
1853 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1853 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1854 count[0] += 1
1854 count[0] += 1
1855 self.ui.progress(_('bundling'), count[0],
1855 self.ui.progress(_('bundling'), count[0],
1856 unit=_('manifests'), total=len(mfs))
1856 unit=_('manifests'), total=len(mfs))
1857 return mfs[x]
1857 return mfs[x]
1858 else:
1858 else:
1859 self.ui.progress(
1859 self.ui.progress(
1860 _('bundling'), count[0], item=fstate[0],
1860 _('bundling'), count[0], item=fstate[0],
1861 unit=_('files'), total=len(changedfiles))
1861 unit=_('files'), total=len(changedfiles))
1862 return fstate[1][x]
1862 return fstate[1][x]
1863
1863
1864 bundler = changegroup.bundle10(lookup)
1864 bundler = changegroup.bundle10(lookup)
1865 reorder = self.ui.config('bundle', 'reorder', 'auto')
1865 reorder = self.ui.config('bundle', 'reorder', 'auto')
1866 if reorder == 'auto':
1866 if reorder == 'auto':
1867 reorder = None
1867 reorder = None
1868 else:
1868 else:
1869 reorder = util.parsebool(reorder)
1869 reorder = util.parsebool(reorder)
1870
1870
1871 def gengroup():
1871 def gengroup():
1872 # Create a changenode group generator that will call our functions
1872 # Create a changenode group generator that will call our functions
1873 # back to lookup the owning changenode and collect information.
1873 # back to lookup the owning changenode and collect information.
1874 for chunk in cl.group(csets, bundler, reorder=reorder):
1874 for chunk in cl.group(csets, bundler, reorder=reorder):
1875 yield chunk
1875 yield chunk
1876 self.ui.progress(_('bundling'), None)
1876 self.ui.progress(_('bundling'), None)
1877
1877
1878 # Create a generator for the manifestnodes that calls our lookup
1878 # Create a generator for the manifestnodes that calls our lookup
1879 # and data collection functions back.
1879 # and data collection functions back.
1880 count[0] = 0
1880 count[0] = 0
1881 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1881 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1882 yield chunk
1882 yield chunk
1883 self.ui.progress(_('bundling'), None)
1883 self.ui.progress(_('bundling'), None)
1884
1884
1885 mfs.clear()
1885 mfs.clear()
1886
1886
1887 # Go through all our files in order sorted by name.
1887 # Go through all our files in order sorted by name.
1888 count[0] = 0
1888 count[0] = 0
1889 for fname in sorted(changedfiles):
1889 for fname in sorted(changedfiles):
1890 filerevlog = self.file(fname)
1890 filerevlog = self.file(fname)
1891 if not len(filerevlog):
1891 if not len(filerevlog):
1892 raise util.Abort(_("empty or missing revlog for %s") % fname)
1892 raise util.Abort(_("empty or missing revlog for %s") % fname)
1893 fstate[0] = fname
1893 fstate[0] = fname
1894 fstate[1] = fnodes.pop(fname, {})
1894 fstate[1] = fnodes.pop(fname, {})
1895
1895
1896 nodelist = prune(filerevlog, fstate[1])
1896 nodelist = prune(filerevlog, fstate[1])
1897 if nodelist:
1897 if nodelist:
1898 count[0] += 1
1898 count[0] += 1
1899 yield bundler.fileheader(fname)
1899 yield bundler.fileheader(fname)
1900 for chunk in filerevlog.group(nodelist, bundler, reorder):
1900 for chunk in filerevlog.group(nodelist, bundler, reorder):
1901 yield chunk
1901 yield chunk
1902
1902
1903 # Signal that no more groups are left.
1903 # Signal that no more groups are left.
1904 yield bundler.close()
1904 yield bundler.close()
1905 self.ui.progress(_('bundling'), None)
1905 self.ui.progress(_('bundling'), None)
1906
1906
1907 if csets:
1907 if csets:
1908 self.hook('outgoing', node=hex(csets[0]), source=source)
1908 self.hook('outgoing', node=hex(csets[0]), source=source)
1909
1909
1910 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1910 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1911
1911
1912 def changegroup(self, basenodes, source):
1912 def changegroup(self, basenodes, source):
1913 # to avoid a race we use changegroupsubset() (issue1320)
1913 # to avoid a race we use changegroupsubset() (issue1320)
1914 return self.changegroupsubset(basenodes, self.heads(), source)
1914 return self.changegroupsubset(basenodes, self.heads(), source)
1915
1915
1916 def _changegroup(self, nodes, source):
1916 def _changegroup(self, nodes, source):
1917 """Compute the changegroup of all nodes that we have that a recipient
1917 """Compute the changegroup of all nodes that we have that a recipient
1918 doesn't. Return a chunkbuffer object whose read() method will return
1918 doesn't. Return a chunkbuffer object whose read() method will return
1919 successive changegroup chunks.
1919 successive changegroup chunks.
1920
1920
1921 This is much easier than the previous function as we can assume that
1921 This is much easier than the previous function as we can assume that
1922 the recipient has any changenode we aren't sending them.
1922 the recipient has any changenode we aren't sending them.
1923
1923
1924 nodes is the set of nodes to send"""
1924 nodes is the set of nodes to send"""
1925
1925
1926 cl = self.changelog
1926 cl = self.changelog
1927 mf = self.manifest
1927 mf = self.manifest
1928 mfs = {}
1928 mfs = {}
1929 changedfiles = set()
1929 changedfiles = set()
1930 fstate = ['']
1930 fstate = ['']
1931 count = [0]
1931 count = [0]
1932
1932
1933 self.hook('preoutgoing', throw=True, source=source)
1933 self.hook('preoutgoing', throw=True, source=source)
1934 self.changegroupinfo(nodes, source)
1934 self.changegroupinfo(nodes, source)
1935
1935
1936 revset = set([cl.rev(n) for n in nodes])
1936 revset = set([cl.rev(n) for n in nodes])
1937
1937
1938 def gennodelst(log):
1938 def gennodelst(log):
1939 return [log.node(r) for r in log if log.linkrev(r) in revset]
1939 return [log.node(r) for r in log if log.linkrev(r) in revset]
1940
1940
1941 def lookup(revlog, x):
1941 def lookup(revlog, x):
1942 if revlog == cl:
1942 if revlog == cl:
1943 c = cl.read(x)
1943 c = cl.read(x)
1944 changedfiles.update(c[3])
1944 changedfiles.update(c[3])
1945 mfs.setdefault(c[0], x)
1945 mfs.setdefault(c[0], x)
1946 count[0] += 1
1946 count[0] += 1
1947 self.ui.progress(_('bundling'), count[0],
1947 self.ui.progress(_('bundling'), count[0],
1948 unit=_('changesets'), total=len(nodes))
1948 unit=_('changesets'), total=len(nodes))
1949 return x
1949 return x
1950 elif revlog == mf:
1950 elif revlog == mf:
1951 count[0] += 1
1951 count[0] += 1
1952 self.ui.progress(_('bundling'), count[0],
1952 self.ui.progress(_('bundling'), count[0],
1953 unit=_('manifests'), total=len(mfs))
1953 unit=_('manifests'), total=len(mfs))
1954 return cl.node(revlog.linkrev(revlog.rev(x)))
1954 return cl.node(revlog.linkrev(revlog.rev(x)))
1955 else:
1955 else:
1956 self.ui.progress(
1956 self.ui.progress(
1957 _('bundling'), count[0], item=fstate[0],
1957 _('bundling'), count[0], item=fstate[0],
1958 total=len(changedfiles), unit=_('files'))
1958 total=len(changedfiles), unit=_('files'))
1959 return cl.node(revlog.linkrev(revlog.rev(x)))
1959 return cl.node(revlog.linkrev(revlog.rev(x)))
1960
1960
1961 bundler = changegroup.bundle10(lookup)
1961 bundler = changegroup.bundle10(lookup)
1962 reorder = self.ui.config('bundle', 'reorder', 'auto')
1962 reorder = self.ui.config('bundle', 'reorder', 'auto')
1963 if reorder == 'auto':
1963 if reorder == 'auto':
1964 reorder = None
1964 reorder = None
1965 else:
1965 else:
1966 reorder = util.parsebool(reorder)
1966 reorder = util.parsebool(reorder)
1967
1967
1968 def gengroup():
1968 def gengroup():
1969 '''yield a sequence of changegroup chunks (strings)'''
1969 '''yield a sequence of changegroup chunks (strings)'''
1970 # construct a list of all changed files
1970 # construct a list of all changed files
1971
1971
1972 for chunk in cl.group(nodes, bundler, reorder=reorder):
1972 for chunk in cl.group(nodes, bundler, reorder=reorder):
1973 yield chunk
1973 yield chunk
1974 self.ui.progress(_('bundling'), None)
1974 self.ui.progress(_('bundling'), None)
1975
1975
1976 count[0] = 0
1976 count[0] = 0
1977 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1977 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1978 yield chunk
1978 yield chunk
1979 self.ui.progress(_('bundling'), None)
1979 self.ui.progress(_('bundling'), None)
1980
1980
1981 count[0] = 0
1981 count[0] = 0
1982 for fname in sorted(changedfiles):
1982 for fname in sorted(changedfiles):
1983 filerevlog = self.file(fname)
1983 filerevlog = self.file(fname)
1984 if not len(filerevlog):
1984 if not len(filerevlog):
1985 raise util.Abort(_("empty or missing revlog for %s") % fname)
1985 raise util.Abort(_("empty or missing revlog for %s") % fname)
1986 fstate[0] = fname
1986 fstate[0] = fname
1987 nodelist = gennodelst(filerevlog)
1987 nodelist = gennodelst(filerevlog)
1988 if nodelist:
1988 if nodelist:
1989 count[0] += 1
1989 count[0] += 1
1990 yield bundler.fileheader(fname)
1990 yield bundler.fileheader(fname)
1991 for chunk in filerevlog.group(nodelist, bundler, reorder):
1991 for chunk in filerevlog.group(nodelist, bundler, reorder):
1992 yield chunk
1992 yield chunk
1993 yield bundler.close()
1993 yield bundler.close()
1994 self.ui.progress(_('bundling'), None)
1994 self.ui.progress(_('bundling'), None)
1995
1995
1996 if nodes:
1996 if nodes:
1997 self.hook('outgoing', node=hex(nodes[0]), source=source)
1997 self.hook('outgoing', node=hex(nodes[0]), source=source)
1998
1998
1999 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1999 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
2000
2000
2001 def addchangegroup(self, source, srctype, url, emptyok=False):
2001 def addchangegroup(self, source, srctype, url, emptyok=False):
2002 """Add the changegroup returned by source.read() to this repo.
2002 """Add the changegroup returned by source.read() to this repo.
2003 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2003 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2004 the URL of the repo where this changegroup is coming from.
2004 the URL of the repo where this changegroup is coming from.
2005
2005
2006 Return an integer summarizing the change to this repo:
2006 Return an integer summarizing the change to this repo:
2007 - nothing changed or no source: 0
2007 - nothing changed or no source: 0
2008 - more heads than before: 1+added heads (2..n)
2008 - more heads than before: 1+added heads (2..n)
2009 - fewer heads than before: -1-removed heads (-2..-n)
2009 - fewer heads than before: -1-removed heads (-2..-n)
2010 - number of heads stays the same: 1
2010 - number of heads stays the same: 1
2011 """
2011 """
2012 def csmap(x):
2012 def csmap(x):
2013 self.ui.debug("add changeset %s\n" % short(x))
2013 self.ui.debug("add changeset %s\n" % short(x))
2014 return len(cl)
2014 return len(cl)
2015
2015
2016 def revmap(x):
2016 def revmap(x):
2017 return cl.rev(x)
2017 return cl.rev(x)
2018
2018
2019 if not source:
2019 if not source:
2020 return 0
2020 return 0
2021
2021
2022 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2022 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2023
2023
2024 changesets = files = revisions = 0
2024 changesets = files = revisions = 0
2025 efiles = set()
2025 efiles = set()
2026
2026
2027 # write changelog data to temp files so concurrent readers will not see
2027 # write changelog data to temp files so concurrent readers will not see
2028 # inconsistent view
2028 # inconsistent view
2029 cl = self.changelog
2029 cl = self.changelog
2030 cl.delayupdate()
2030 cl.delayupdate()
2031 oldheads = cl.heads()
2031 oldheads = cl.heads()
2032
2032
2033 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2033 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2034 try:
2034 try:
2035 trp = weakref.proxy(tr)
2035 trp = weakref.proxy(tr)
2036 # pull off the changeset group
2036 # pull off the changeset group
2037 self.ui.status(_("adding changesets\n"))
2037 self.ui.status(_("adding changesets\n"))
2038 clstart = len(cl)
2038 clstart = len(cl)
2039 class prog(object):
2039 class prog(object):
2040 step = _('changesets')
2040 step = _('changesets')
2041 count = 1
2041 count = 1
2042 ui = self.ui
2042 ui = self.ui
2043 total = None
2043 total = None
2044 def __call__(self):
2044 def __call__(self):
2045 self.ui.progress(self.step, self.count, unit=_('chunks'),
2045 self.ui.progress(self.step, self.count, unit=_('chunks'),
2046 total=self.total)
2046 total=self.total)
2047 self.count += 1
2047 self.count += 1
2048 pr = prog()
2048 pr = prog()
2049 source.callback = pr
2049 source.callback = pr
2050
2050
2051 source.changelogheader()
2051 source.changelogheader()
2052 srccontent = cl.addgroup(source, csmap, trp)
2052 srccontent = cl.addgroup(source, csmap, trp)
2053 if not (srccontent or emptyok):
2053 if not (srccontent or emptyok):
2054 raise util.Abort(_("received changelog group is empty"))
2054 raise util.Abort(_("received changelog group is empty"))
2055 clend = len(cl)
2055 clend = len(cl)
2056 changesets = clend - clstart
2056 changesets = clend - clstart
2057 for c in xrange(clstart, clend):
2057 for c in xrange(clstart, clend):
2058 efiles.update(self[c].files())
2058 efiles.update(self[c].files())
2059 efiles = len(efiles)
2059 efiles = len(efiles)
2060 self.ui.progress(_('changesets'), None)
2060 self.ui.progress(_('changesets'), None)
2061
2061
2062 # pull off the manifest group
2062 # pull off the manifest group
2063 self.ui.status(_("adding manifests\n"))
2063 self.ui.status(_("adding manifests\n"))
2064 pr.step = _('manifests')
2064 pr.step = _('manifests')
2065 pr.count = 1
2065 pr.count = 1
2066 pr.total = changesets # manifests <= changesets
2066 pr.total = changesets # manifests <= changesets
2067 # no need to check for empty manifest group here:
2067 # no need to check for empty manifest group here:
2068 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2068 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2069 # no new manifest will be created and the manifest group will
2069 # no new manifest will be created and the manifest group will
2070 # be empty during the pull
2070 # be empty during the pull
2071 source.manifestheader()
2071 source.manifestheader()
2072 self.manifest.addgroup(source, revmap, trp)
2072 self.manifest.addgroup(source, revmap, trp)
2073 self.ui.progress(_('manifests'), None)
2073 self.ui.progress(_('manifests'), None)
2074
2074
2075 needfiles = {}
2075 needfiles = {}
2076 if self.ui.configbool('server', 'validate', default=False):
2076 if self.ui.configbool('server', 'validate', default=False):
2077 # validate incoming csets have their manifests
2077 # validate incoming csets have their manifests
2078 for cset in xrange(clstart, clend):
2078 for cset in xrange(clstart, clend):
2079 mfest = self.changelog.read(self.changelog.node(cset))[0]
2079 mfest = self.changelog.read(self.changelog.node(cset))[0]
2080 mfest = self.manifest.readdelta(mfest)
2080 mfest = self.manifest.readdelta(mfest)
2081 # store file nodes we must see
2081 # store file nodes we must see
2082 for f, n in mfest.iteritems():
2082 for f, n in mfest.iteritems():
2083 needfiles.setdefault(f, set()).add(n)
2083 needfiles.setdefault(f, set()).add(n)
2084
2084
2085 # process the files
2085 # process the files
2086 self.ui.status(_("adding file changes\n"))
2086 self.ui.status(_("adding file changes\n"))
2087 pr.step = _('files')
2087 pr.step = _('files')
2088 pr.count = 1
2088 pr.count = 1
2089 pr.total = efiles
2089 pr.total = efiles
2090 source.callback = None
2090 source.callback = None
2091
2091
2092 while True:
2092 while True:
2093 chunkdata = source.filelogheader()
2093 chunkdata = source.filelogheader()
2094 if not chunkdata:
2094 if not chunkdata:
2095 break
2095 break
2096 f = chunkdata["filename"]
2096 f = chunkdata["filename"]
2097 self.ui.debug("adding %s revisions\n" % f)
2097 self.ui.debug("adding %s revisions\n" % f)
2098 pr()
2098 pr()
2099 fl = self.file(f)
2099 fl = self.file(f)
2100 o = len(fl)
2100 o = len(fl)
2101 if not fl.addgroup(source, revmap, trp):
2101 if not fl.addgroup(source, revmap, trp):
2102 raise util.Abort(_("received file revlog group is empty"))
2102 raise util.Abort(_("received file revlog group is empty"))
2103 revisions += len(fl) - o
2103 revisions += len(fl) - o
2104 files += 1
2104 files += 1
2105 if f in needfiles:
2105 if f in needfiles:
2106 needs = needfiles[f]
2106 needs = needfiles[f]
2107 for new in xrange(o, len(fl)):
2107 for new in xrange(o, len(fl)):
2108 n = fl.node(new)
2108 n = fl.node(new)
2109 if n in needs:
2109 if n in needs:
2110 needs.remove(n)
2110 needs.remove(n)
2111 if not needs:
2111 if not needs:
2112 del needfiles[f]
2112 del needfiles[f]
2113 self.ui.progress(_('files'), None)
2113 self.ui.progress(_('files'), None)
2114
2114
2115 for f, needs in needfiles.iteritems():
2115 for f, needs in needfiles.iteritems():
2116 fl = self.file(f)
2116 fl = self.file(f)
2117 for n in needs:
2117 for n in needs:
2118 try:
2118 try:
2119 fl.rev(n)
2119 fl.rev(n)
2120 except error.LookupError:
2120 except error.LookupError:
2121 raise util.Abort(
2121 raise util.Abort(
2122 _('missing file data for %s:%s - run hg verify') %
2122 _('missing file data for %s:%s - run hg verify') %
2123 (f, hex(n)))
2123 (f, hex(n)))
2124
2124
2125 dh = 0
2125 dh = 0
2126 if oldheads:
2126 if oldheads:
2127 heads = cl.heads()
2127 heads = cl.heads()
2128 dh = len(heads) - len(oldheads)
2128 dh = len(heads) - len(oldheads)
2129 for h in heads:
2129 for h in heads:
2130 if h not in oldheads and 'close' in self[h].extra():
2130 if h not in oldheads and 'close' in self[h].extra():
2131 dh -= 1
2131 dh -= 1
2132 htext = ""
2132 htext = ""
2133 if dh:
2133 if dh:
2134 htext = _(" (%+d heads)") % dh
2134 htext = _(" (%+d heads)") % dh
2135
2135
2136 self.ui.status(_("added %d changesets"
2136 self.ui.status(_("added %d changesets"
2137 " with %d changes to %d files%s\n")
2137 " with %d changes to %d files%s\n")
2138 % (changesets, revisions, files, htext))
2138 % (changesets, revisions, files, htext))
2139
2139
2140 if changesets > 0:
2140 if changesets > 0:
2141 p = lambda: cl.writepending() and self.root or ""
2141 p = lambda: cl.writepending() and self.root or ""
2142 self.hook('pretxnchangegroup', throw=True,
2142 self.hook('pretxnchangegroup', throw=True,
2143 node=hex(cl.node(clstart)), source=srctype,
2143 node=hex(cl.node(clstart)), source=srctype,
2144 url=url, pending=p)
2144 url=url, pending=p)
2145
2145
2146 added = [cl.node(r) for r in xrange(clstart, clend)]
2146 added = [cl.node(r) for r in xrange(clstart, clend)]
2147 publishing = self.ui.configbool('phases', 'publish', True)
2147 publishing = self.ui.configbool('phases', 'publish', True)
2148 if srctype == 'push':
2148 if srctype == 'push':
2149 # Old server can not push the boundary themself.
2149 # Old server can not push the boundary themself.
2150 # New server won't push the boundary if changeset already
2150 # New server won't push the boundary if changeset already
2151 # existed locally as secrete
2151 # existed locally as secrete
2152 #
2152 #
2153 # We should not use added here but the list of all change in
2153 # We should not use added here but the list of all change in
2154 # the bundle
2154 # the bundle
2155 if publishing:
2155 if publishing:
2156 phases.advanceboundary(self, phases.public, srccontent)
2156 phases.advanceboundary(self, phases.public, srccontent)
2157 else:
2157 else:
2158 phases.advanceboundary(self, phases.draft, srccontent)
2158 phases.advanceboundary(self, phases.draft, srccontent)
2159 phases.retractboundary(self, phases.draft, added)
2159 phases.retractboundary(self, phases.draft, added)
2160 elif srctype != 'strip':
2160 elif srctype != 'strip':
2161 # publishing only alter behavior during push
2161 # publishing only alter behavior during push
2162 #
2162 #
2163 # strip should not touch boundary at all
2163 # strip should not touch boundary at all
2164 phases.retractboundary(self, phases.draft, added)
2164 phases.retractboundary(self, phases.draft, added)
2165
2165
2166 # make changelog see real files again
2166 # make changelog see real files again
2167 cl.finalize(trp)
2167 cl.finalize(trp)
2168
2168
2169 tr.close()
2169 tr.close()
2170
2170
2171 if changesets > 0:
2171 if changesets > 0:
2172 def runhooks():
2172 def runhooks():
2173 # forcefully update the on-disk branch cache
2173 # forcefully update the on-disk branch cache
2174 self.ui.debug("updating the branch cache\n")
2174 self.ui.debug("updating the branch cache\n")
2175 self.updatebranchcache()
2175 self.updatebranchcache()
2176 self.hook("changegroup", node=hex(cl.node(clstart)),
2176 self.hook("changegroup", node=hex(cl.node(clstart)),
2177 source=srctype, url=url)
2177 source=srctype, url=url)
2178
2178
2179 for n in added:
2179 for n in added:
2180 self.hook("incoming", node=hex(n), source=srctype,
2180 self.hook("incoming", node=hex(n), source=srctype,
2181 url=url)
2181 url=url)
2182 self._afterlock(runhooks)
2182 self._afterlock(runhooks)
2183
2183
2184 finally:
2184 finally:
2185 tr.release()
2185 tr.release()
2186 # never return 0 here:
2186 # never return 0 here:
2187 if dh < 0:
2187 if dh < 0:
2188 return dh - 1
2188 return dh - 1
2189 else:
2189 else:
2190 return dh + 1
2190 return dh + 1
2191
2191
2192 def stream_in(self, remote, requirements):
2192 def stream_in(self, remote, requirements):
2193 lock = self.lock()
2193 lock = self.lock()
2194 try:
2194 try:
2195 fp = remote.stream_out()
2195 fp = remote.stream_out()
2196 l = fp.readline()
2196 l = fp.readline()
2197 try:
2197 try:
2198 resp = int(l)
2198 resp = int(l)
2199 except ValueError:
2199 except ValueError:
2200 raise error.ResponseError(
2200 raise error.ResponseError(
2201 _('Unexpected response from remote server:'), l)
2201 _('Unexpected response from remote server:'), l)
2202 if resp == 1:
2202 if resp == 1:
2203 raise util.Abort(_('operation forbidden by server'))
2203 raise util.Abort(_('operation forbidden by server'))
2204 elif resp == 2:
2204 elif resp == 2:
2205 raise util.Abort(_('locking the remote repository failed'))
2205 raise util.Abort(_('locking the remote repository failed'))
2206 elif resp != 0:
2206 elif resp != 0:
2207 raise util.Abort(_('the server sent an unknown error code'))
2207 raise util.Abort(_('the server sent an unknown error code'))
2208 self.ui.status(_('streaming all changes\n'))
2208 self.ui.status(_('streaming all changes\n'))
2209 l = fp.readline()
2209 l = fp.readline()
2210 try:
2210 try:
2211 total_files, total_bytes = map(int, l.split(' ', 1))
2211 total_files, total_bytes = map(int, l.split(' ', 1))
2212 except (ValueError, TypeError):
2212 except (ValueError, TypeError):
2213 raise error.ResponseError(
2213 raise error.ResponseError(
2214 _('Unexpected response from remote server:'), l)
2214 _('Unexpected response from remote server:'), l)
2215 self.ui.status(_('%d files to transfer, %s of data\n') %
2215 self.ui.status(_('%d files to transfer, %s of data\n') %
2216 (total_files, util.bytecount(total_bytes)))
2216 (total_files, util.bytecount(total_bytes)))
2217 start = time.time()
2217 start = time.time()
2218 for i in xrange(total_files):
2218 for i in xrange(total_files):
2219 # XXX doesn't support '\n' or '\r' in filenames
2219 # XXX doesn't support '\n' or '\r' in filenames
2220 l = fp.readline()
2220 l = fp.readline()
2221 try:
2221 try:
2222 name, size = l.split('\0', 1)
2222 name, size = l.split('\0', 1)
2223 size = int(size)
2223 size = int(size)
2224 except (ValueError, TypeError):
2224 except (ValueError, TypeError):
2225 raise error.ResponseError(
2225 raise error.ResponseError(
2226 _('Unexpected response from remote server:'), l)
2226 _('Unexpected response from remote server:'), l)
2227 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2227 if self.ui.debugflag:
2228 self.ui.debug('adding %s (%s)\n' %
2229 (name, util.bytecount(size)))
2228 # for backwards compat, name was partially encoded
2230 # for backwards compat, name was partially encoded
2229 ofp = self.sopener(store.decodedir(name), 'w')
2231 ofp = self.sopener(store.decodedir(name), 'w')
2230 for chunk in util.filechunkiter(fp, limit=size):
2232 for chunk in util.filechunkiter(fp, limit=size):
2231 ofp.write(chunk)
2233 ofp.write(chunk)
2232 ofp.close()
2234 ofp.close()
2233 elapsed = time.time() - start
2235 elapsed = time.time() - start
2234 if elapsed <= 0:
2236 if elapsed <= 0:
2235 elapsed = 0.001
2237 elapsed = 0.001
2236 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2238 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2237 (util.bytecount(total_bytes), elapsed,
2239 (util.bytecount(total_bytes), elapsed,
2238 util.bytecount(total_bytes / elapsed)))
2240 util.bytecount(total_bytes / elapsed)))
2239
2241
2240 # new requirements = old non-format requirements + new format-related
2242 # new requirements = old non-format requirements + new format-related
2241 # requirements from the streamed-in repository
2243 # requirements from the streamed-in repository
2242 requirements.update(set(self.requirements) - self.supportedformats)
2244 requirements.update(set(self.requirements) - self.supportedformats)
2243 self._applyrequirements(requirements)
2245 self._applyrequirements(requirements)
2244 self._writerequirements()
2246 self._writerequirements()
2245
2247
2246 self.invalidate()
2248 self.invalidate()
2247 return len(self.heads()) + 1
2249 return len(self.heads()) + 1
2248 finally:
2250 finally:
2249 lock.release()
2251 lock.release()
2250
2252
2251 def clone(self, remote, heads=[], stream=False):
2253 def clone(self, remote, heads=[], stream=False):
2252 '''clone remote repository.
2254 '''clone remote repository.
2253
2255
2254 keyword arguments:
2256 keyword arguments:
2255 heads: list of revs to clone (forces use of pull)
2257 heads: list of revs to clone (forces use of pull)
2256 stream: use streaming clone if possible'''
2258 stream: use streaming clone if possible'''
2257
2259
2258 # now, all clients that can request uncompressed clones can
2260 # now, all clients that can request uncompressed clones can
2259 # read repo formats supported by all servers that can serve
2261 # read repo formats supported by all servers that can serve
2260 # them.
2262 # them.
2261
2263
2262 # if revlog format changes, client will have to check version
2264 # if revlog format changes, client will have to check version
2263 # and format flags on "stream" capability, and use
2265 # and format flags on "stream" capability, and use
2264 # uncompressed only if compatible.
2266 # uncompressed only if compatible.
2265
2267
2266 if not stream:
2268 if not stream:
2267 # if the server explicitely prefer to stream (for fast LANs)
2269 # if the server explicitely prefer to stream (for fast LANs)
2268 stream = remote.capable('stream-preferred')
2270 stream = remote.capable('stream-preferred')
2269
2271
2270 if stream and not heads:
2272 if stream and not heads:
2271 # 'stream' means remote revlog format is revlogv1 only
2273 # 'stream' means remote revlog format is revlogv1 only
2272 if remote.capable('stream'):
2274 if remote.capable('stream'):
2273 return self.stream_in(remote, set(('revlogv1',)))
2275 return self.stream_in(remote, set(('revlogv1',)))
2274 # otherwise, 'streamreqs' contains the remote revlog format
2276 # otherwise, 'streamreqs' contains the remote revlog format
2275 streamreqs = remote.capable('streamreqs')
2277 streamreqs = remote.capable('streamreqs')
2276 if streamreqs:
2278 if streamreqs:
2277 streamreqs = set(streamreqs.split(','))
2279 streamreqs = set(streamreqs.split(','))
2278 # if we support it, stream in and adjust our requirements
2280 # if we support it, stream in and adjust our requirements
2279 if not streamreqs - self.supportedformats:
2281 if not streamreqs - self.supportedformats:
2280 return self.stream_in(remote, streamreqs)
2282 return self.stream_in(remote, streamreqs)
2281 return self.pull(remote, heads)
2283 return self.pull(remote, heads)
2282
2284
2283 def pushkey(self, namespace, key, old, new):
2285 def pushkey(self, namespace, key, old, new):
2284 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2286 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2285 old=old, new=new)
2287 old=old, new=new)
2286 ret = pushkey.push(self, namespace, key, old, new)
2288 ret = pushkey.push(self, namespace, key, old, new)
2287 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2289 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2288 ret=ret)
2290 ret=ret)
2289 return ret
2291 return ret
2290
2292
2291 def listkeys(self, namespace):
2293 def listkeys(self, namespace):
2292 self.hook('prelistkeys', throw=True, namespace=namespace)
2294 self.hook('prelistkeys', throw=True, namespace=namespace)
2293 values = pushkey.list(self, namespace)
2295 values = pushkey.list(self, namespace)
2294 self.hook('listkeys', namespace=namespace, values=values)
2296 self.hook('listkeys', namespace=namespace, values=values)
2295 return values
2297 return values
2296
2298
2297 def debugwireargs(self, one, two, three=None, four=None, five=None):
2299 def debugwireargs(self, one, two, three=None, four=None, five=None):
2298 '''used to test argument passing over the wire'''
2300 '''used to test argument passing over the wire'''
2299 return "%s %s %s %s %s" % (one, two, three, four, five)
2301 return "%s %s %s %s %s" % (one, two, three, four, five)
2300
2302
2301 def savecommitmessage(self, text):
2303 def savecommitmessage(self, text):
2302 fp = self.opener('last-message.txt', 'wb')
2304 fp = self.opener('last-message.txt', 'wb')
2303 try:
2305 try:
2304 fp.write(text)
2306 fp.write(text)
2305 finally:
2307 finally:
2306 fp.close()
2308 fp.close()
2307 return self.pathto(fp.name[len(self.root)+1:])
2309 return self.pathto(fp.name[len(self.root)+1:])
2308
2310
2309 # used to avoid circular references so destructors work
2311 # used to avoid circular references so destructors work
2310 def aftertrans(files):
2312 def aftertrans(files):
2311 renamefiles = [tuple(t) for t in files]
2313 renamefiles = [tuple(t) for t in files]
2312 def a():
2314 def a():
2313 for src, dest in renamefiles:
2315 for src, dest in renamefiles:
2314 util.rename(src, dest)
2316 util.rename(src, dest)
2315 return a
2317 return a
2316
2318
2317 def undoname(fn):
2319 def undoname(fn):
2318 base, name = os.path.split(fn)
2320 base, name = os.path.split(fn)
2319 assert name.startswith('journal')
2321 assert name.startswith('journal')
2320 return os.path.join(base, name.replace('journal', 'undo', 1))
2322 return os.path.join(base, name.replace('journal', 'undo', 1))
2321
2323
2322 def instance(ui, path, create):
2324 def instance(ui, path, create):
2323 return localrepository(ui, util.urllocalpath(path), create)
2325 return localrepository(ui, util.urllocalpath(path), create)
2324
2326
2325 def islocal(path):
2327 def islocal(path):
2326 return True
2328 return True
General Comments 0
You need to be logged in to leave comments. Login now