##// END OF EJS Templates
localrepo: use commonancestorsheads for checking linear heritage in file commit...
Mads Kiilerich -
r21106:53433d8f default
parent child Browse files
Show More
@@ -1,1906 +1,1906 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 from node import hex, nullid, short
7 from node import hex, nullid, short
8 from i18n import _
8 from i18n import _
9 import peer, changegroup, subrepo, pushkey, obsolete, repoview
9 import peer, changegroup, subrepo, pushkey, obsolete, repoview
10 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
10 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
11 import lock as lockmod
11 import lock as lockmod
12 import transaction, store, encoding, exchange, bundle2
12 import transaction, store, encoding, exchange, bundle2
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 import branchmap, pathutil
19 import branchmap, pathutil
20 propertycache = util.propertycache
20 propertycache = util.propertycache
21 filecache = scmutil.filecache
21 filecache = scmutil.filecache
22
22
23 class repofilecache(filecache):
23 class repofilecache(filecache):
24 """All filecache usage on repo are done for logic that should be unfiltered
24 """All filecache usage on repo are done for logic that should be unfiltered
25 """
25 """
26
26
27 def __get__(self, repo, type=None):
27 def __get__(self, repo, type=None):
28 return super(repofilecache, self).__get__(repo.unfiltered(), type)
28 return super(repofilecache, self).__get__(repo.unfiltered(), type)
29 def __set__(self, repo, value):
29 def __set__(self, repo, value):
30 return super(repofilecache, self).__set__(repo.unfiltered(), value)
30 return super(repofilecache, self).__set__(repo.unfiltered(), value)
31 def __delete__(self, repo):
31 def __delete__(self, repo):
32 return super(repofilecache, self).__delete__(repo.unfiltered())
32 return super(repofilecache, self).__delete__(repo.unfiltered())
33
33
34 class storecache(repofilecache):
34 class storecache(repofilecache):
35 """filecache for files in the store"""
35 """filecache for files in the store"""
36 def join(self, obj, fname):
36 def join(self, obj, fname):
37 return obj.sjoin(fname)
37 return obj.sjoin(fname)
38
38
39 class unfilteredpropertycache(propertycache):
39 class unfilteredpropertycache(propertycache):
40 """propertycache that apply to unfiltered repo only"""
40 """propertycache that apply to unfiltered repo only"""
41
41
42 def __get__(self, repo, type=None):
42 def __get__(self, repo, type=None):
43 unfi = repo.unfiltered()
43 unfi = repo.unfiltered()
44 if unfi is repo:
44 if unfi is repo:
45 return super(unfilteredpropertycache, self).__get__(unfi)
45 return super(unfilteredpropertycache, self).__get__(unfi)
46 return getattr(unfi, self.name)
46 return getattr(unfi, self.name)
47
47
48 class filteredpropertycache(propertycache):
48 class filteredpropertycache(propertycache):
49 """propertycache that must take filtering in account"""
49 """propertycache that must take filtering in account"""
50
50
51 def cachevalue(self, obj, value):
51 def cachevalue(self, obj, value):
52 object.__setattr__(obj, self.name, value)
52 object.__setattr__(obj, self.name, value)
53
53
54
54
55 def hasunfilteredcache(repo, name):
55 def hasunfilteredcache(repo, name):
56 """check if a repo has an unfilteredpropertycache value for <name>"""
56 """check if a repo has an unfilteredpropertycache value for <name>"""
57 return name in vars(repo.unfiltered())
57 return name in vars(repo.unfiltered())
58
58
59 def unfilteredmethod(orig):
59 def unfilteredmethod(orig):
60 """decorate method that always need to be run on unfiltered version"""
60 """decorate method that always need to be run on unfiltered version"""
61 def wrapper(repo, *args, **kwargs):
61 def wrapper(repo, *args, **kwargs):
62 return orig(repo.unfiltered(), *args, **kwargs)
62 return orig(repo.unfiltered(), *args, **kwargs)
63 return wrapper
63 return wrapper
64
64
65 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
65 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
66 'bundle2', 'unbundle'))
66 'bundle2', 'unbundle'))
67 legacycaps = moderncaps.union(set(['changegroupsubset']))
67 legacycaps = moderncaps.union(set(['changegroupsubset']))
68
68
69 class localpeer(peer.peerrepository):
69 class localpeer(peer.peerrepository):
70 '''peer for a local repo; reflects only the most recent API'''
70 '''peer for a local repo; reflects only the most recent API'''
71
71
72 def __init__(self, repo, caps=moderncaps):
72 def __init__(self, repo, caps=moderncaps):
73 peer.peerrepository.__init__(self)
73 peer.peerrepository.__init__(self)
74 self._repo = repo.filtered('served')
74 self._repo = repo.filtered('served')
75 self.ui = repo.ui
75 self.ui = repo.ui
76 self._caps = repo._restrictcapabilities(caps)
76 self._caps = repo._restrictcapabilities(caps)
77 self.requirements = repo.requirements
77 self.requirements = repo.requirements
78 self.supportedformats = repo.supportedformats
78 self.supportedformats = repo.supportedformats
79
79
80 def close(self):
80 def close(self):
81 self._repo.close()
81 self._repo.close()
82
82
83 def _capabilities(self):
83 def _capabilities(self):
84 return self._caps
84 return self._caps
85
85
86 def local(self):
86 def local(self):
87 return self._repo
87 return self._repo
88
88
89 def canpush(self):
89 def canpush(self):
90 return True
90 return True
91
91
92 def url(self):
92 def url(self):
93 return self._repo.url()
93 return self._repo.url()
94
94
95 def lookup(self, key):
95 def lookup(self, key):
96 return self._repo.lookup(key)
96 return self._repo.lookup(key)
97
97
98 def branchmap(self):
98 def branchmap(self):
99 return self._repo.branchmap()
99 return self._repo.branchmap()
100
100
101 def heads(self):
101 def heads(self):
102 return self._repo.heads()
102 return self._repo.heads()
103
103
104 def known(self, nodes):
104 def known(self, nodes):
105 return self._repo.known(nodes)
105 return self._repo.known(nodes)
106
106
107 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
107 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
108 format='HG10'):
108 format='HG10'):
109 cg = exchange.getbundle(self._repo, source, heads=heads,
109 cg = exchange.getbundle(self._repo, source, heads=heads,
110 common=common, bundlecaps=bundlecaps)
110 common=common, bundlecaps=bundlecaps)
111 if bundlecaps is not None and 'HG20' in bundlecaps:
111 if bundlecaps is not None and 'HG20' in bundlecaps:
112 # When requesting a bundle2, getbundle returns a stream to make the
112 # When requesting a bundle2, getbundle returns a stream to make the
113 # wire level function happier. We need to build a proper object
113 # wire level function happier. We need to build a proper object
114 # from it in local peer.
114 # from it in local peer.
115 cg = bundle2.unbundle20(self.ui, cg)
115 cg = bundle2.unbundle20(self.ui, cg)
116 return cg
116 return cg
117
117
118 # TODO We might want to move the next two calls into legacypeer and add
118 # TODO We might want to move the next two calls into legacypeer and add
119 # unbundle instead.
119 # unbundle instead.
120
120
121 def unbundle(self, cg, heads, url):
121 def unbundle(self, cg, heads, url):
122 """apply a bundle on a repo
122 """apply a bundle on a repo
123
123
124 This function handles the repo locking itself."""
124 This function handles the repo locking itself."""
125 try:
125 try:
126 cg = exchange.readbundle(self.ui, cg, None)
126 cg = exchange.readbundle(self.ui, cg, None)
127 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
127 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
128 if util.safehasattr(ret, 'getchunks'):
128 if util.safehasattr(ret, 'getchunks'):
129 # This is a bundle20 object, turn it into an unbundler.
129 # This is a bundle20 object, turn it into an unbundler.
130 # This little dance should be dropped eventually when the API
130 # This little dance should be dropped eventually when the API
131 # is finally improved.
131 # is finally improved.
132 stream = util.chunkbuffer(ret.getchunks())
132 stream = util.chunkbuffer(ret.getchunks())
133 ret = bundle2.unbundle20(self.ui, stream)
133 ret = bundle2.unbundle20(self.ui, stream)
134 return ret
134 return ret
135 except exchange.PushRaced, exc:
135 except exchange.PushRaced, exc:
136 raise error.ResponseError(_('push failed:'), exc.message)
136 raise error.ResponseError(_('push failed:'), exc.message)
137
137
138 def lock(self):
138 def lock(self):
139 return self._repo.lock()
139 return self._repo.lock()
140
140
141 def addchangegroup(self, cg, source, url):
141 def addchangegroup(self, cg, source, url):
142 return changegroup.addchangegroup(self._repo, cg, source, url)
142 return changegroup.addchangegroup(self._repo, cg, source, url)
143
143
144 def pushkey(self, namespace, key, old, new):
144 def pushkey(self, namespace, key, old, new):
145 return self._repo.pushkey(namespace, key, old, new)
145 return self._repo.pushkey(namespace, key, old, new)
146
146
147 def listkeys(self, namespace):
147 def listkeys(self, namespace):
148 return self._repo.listkeys(namespace)
148 return self._repo.listkeys(namespace)
149
149
150 def debugwireargs(self, one, two, three=None, four=None, five=None):
150 def debugwireargs(self, one, two, three=None, four=None, five=None):
151 '''used to test argument passing over the wire'''
151 '''used to test argument passing over the wire'''
152 return "%s %s %s %s %s" % (one, two, three, four, five)
152 return "%s %s %s %s %s" % (one, two, three, four, five)
153
153
154 class locallegacypeer(localpeer):
154 class locallegacypeer(localpeer):
155 '''peer extension which implements legacy methods too; used for tests with
155 '''peer extension which implements legacy methods too; used for tests with
156 restricted capabilities'''
156 restricted capabilities'''
157
157
158 def __init__(self, repo):
158 def __init__(self, repo):
159 localpeer.__init__(self, repo, caps=legacycaps)
159 localpeer.__init__(self, repo, caps=legacycaps)
160
160
161 def branches(self, nodes):
161 def branches(self, nodes):
162 return self._repo.branches(nodes)
162 return self._repo.branches(nodes)
163
163
164 def between(self, pairs):
164 def between(self, pairs):
165 return self._repo.between(pairs)
165 return self._repo.between(pairs)
166
166
167 def changegroup(self, basenodes, source):
167 def changegroup(self, basenodes, source):
168 return changegroup.changegroup(self._repo, basenodes, source)
168 return changegroup.changegroup(self._repo, basenodes, source)
169
169
170 def changegroupsubset(self, bases, heads, source):
170 def changegroupsubset(self, bases, heads, source):
171 return changegroup.changegroupsubset(self._repo, bases, heads, source)
171 return changegroup.changegroupsubset(self._repo, bases, heads, source)
172
172
173 class localrepository(object):
173 class localrepository(object):
174
174
175 supportedformats = set(('revlogv1', 'generaldelta'))
175 supportedformats = set(('revlogv1', 'generaldelta'))
176 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
176 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
177 'dotencode'))
177 'dotencode'))
178 openerreqs = set(('revlogv1', 'generaldelta'))
178 openerreqs = set(('revlogv1', 'generaldelta'))
179 requirements = ['revlogv1']
179 requirements = ['revlogv1']
180 filtername = None
180 filtername = None
181
181
182 # a list of (ui, featureset) functions.
182 # a list of (ui, featureset) functions.
183 # only functions defined in module of enabled extensions are invoked
183 # only functions defined in module of enabled extensions are invoked
184 featuresetupfuncs = set()
184 featuresetupfuncs = set()
185
185
186 def _baserequirements(self, create):
186 def _baserequirements(self, create):
187 return self.requirements[:]
187 return self.requirements[:]
188
188
189 def __init__(self, baseui, path=None, create=False):
189 def __init__(self, baseui, path=None, create=False):
190 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
190 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
191 self.wopener = self.wvfs
191 self.wopener = self.wvfs
192 self.root = self.wvfs.base
192 self.root = self.wvfs.base
193 self.path = self.wvfs.join(".hg")
193 self.path = self.wvfs.join(".hg")
194 self.origroot = path
194 self.origroot = path
195 self.auditor = pathutil.pathauditor(self.root, self._checknested)
195 self.auditor = pathutil.pathauditor(self.root, self._checknested)
196 self.vfs = scmutil.vfs(self.path)
196 self.vfs = scmutil.vfs(self.path)
197 self.opener = self.vfs
197 self.opener = self.vfs
198 self.baseui = baseui
198 self.baseui = baseui
199 self.ui = baseui.copy()
199 self.ui = baseui.copy()
200 self.ui.copy = baseui.copy # prevent copying repo configuration
200 self.ui.copy = baseui.copy # prevent copying repo configuration
201 # A list of callback to shape the phase if no data were found.
201 # A list of callback to shape the phase if no data were found.
202 # Callback are in the form: func(repo, roots) --> processed root.
202 # Callback are in the form: func(repo, roots) --> processed root.
203 # This list it to be filled by extension during repo setup
203 # This list it to be filled by extension during repo setup
204 self._phasedefaults = []
204 self._phasedefaults = []
205 try:
205 try:
206 self.ui.readconfig(self.join("hgrc"), self.root)
206 self.ui.readconfig(self.join("hgrc"), self.root)
207 extensions.loadall(self.ui)
207 extensions.loadall(self.ui)
208 except IOError:
208 except IOError:
209 pass
209 pass
210
210
211 if self.featuresetupfuncs:
211 if self.featuresetupfuncs:
212 self.supported = set(self._basesupported) # use private copy
212 self.supported = set(self._basesupported) # use private copy
213 extmods = set(m.__name__ for n, m
213 extmods = set(m.__name__ for n, m
214 in extensions.extensions(self.ui))
214 in extensions.extensions(self.ui))
215 for setupfunc in self.featuresetupfuncs:
215 for setupfunc in self.featuresetupfuncs:
216 if setupfunc.__module__ in extmods:
216 if setupfunc.__module__ in extmods:
217 setupfunc(self.ui, self.supported)
217 setupfunc(self.ui, self.supported)
218 else:
218 else:
219 self.supported = self._basesupported
219 self.supported = self._basesupported
220
220
221 if not self.vfs.isdir():
221 if not self.vfs.isdir():
222 if create:
222 if create:
223 if not self.wvfs.exists():
223 if not self.wvfs.exists():
224 self.wvfs.makedirs()
224 self.wvfs.makedirs()
225 self.vfs.makedir(notindexed=True)
225 self.vfs.makedir(notindexed=True)
226 requirements = self._baserequirements(create)
226 requirements = self._baserequirements(create)
227 if self.ui.configbool('format', 'usestore', True):
227 if self.ui.configbool('format', 'usestore', True):
228 self.vfs.mkdir("store")
228 self.vfs.mkdir("store")
229 requirements.append("store")
229 requirements.append("store")
230 if self.ui.configbool('format', 'usefncache', True):
230 if self.ui.configbool('format', 'usefncache', True):
231 requirements.append("fncache")
231 requirements.append("fncache")
232 if self.ui.configbool('format', 'dotencode', True):
232 if self.ui.configbool('format', 'dotencode', True):
233 requirements.append('dotencode')
233 requirements.append('dotencode')
234 # create an invalid changelog
234 # create an invalid changelog
235 self.vfs.append(
235 self.vfs.append(
236 "00changelog.i",
236 "00changelog.i",
237 '\0\0\0\2' # represents revlogv2
237 '\0\0\0\2' # represents revlogv2
238 ' dummy changelog to prevent using the old repo layout'
238 ' dummy changelog to prevent using the old repo layout'
239 )
239 )
240 if self.ui.configbool('format', 'generaldelta', False):
240 if self.ui.configbool('format', 'generaldelta', False):
241 requirements.append("generaldelta")
241 requirements.append("generaldelta")
242 requirements = set(requirements)
242 requirements = set(requirements)
243 else:
243 else:
244 raise error.RepoError(_("repository %s not found") % path)
244 raise error.RepoError(_("repository %s not found") % path)
245 elif create:
245 elif create:
246 raise error.RepoError(_("repository %s already exists") % path)
246 raise error.RepoError(_("repository %s already exists") % path)
247 else:
247 else:
248 try:
248 try:
249 requirements = scmutil.readrequires(self.vfs, self.supported)
249 requirements = scmutil.readrequires(self.vfs, self.supported)
250 except IOError, inst:
250 except IOError, inst:
251 if inst.errno != errno.ENOENT:
251 if inst.errno != errno.ENOENT:
252 raise
252 raise
253 requirements = set()
253 requirements = set()
254
254
255 self.sharedpath = self.path
255 self.sharedpath = self.path
256 try:
256 try:
257 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
257 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
258 realpath=True)
258 realpath=True)
259 s = vfs.base
259 s = vfs.base
260 if not vfs.exists():
260 if not vfs.exists():
261 raise error.RepoError(
261 raise error.RepoError(
262 _('.hg/sharedpath points to nonexistent directory %s') % s)
262 _('.hg/sharedpath points to nonexistent directory %s') % s)
263 self.sharedpath = s
263 self.sharedpath = s
264 except IOError, inst:
264 except IOError, inst:
265 if inst.errno != errno.ENOENT:
265 if inst.errno != errno.ENOENT:
266 raise
266 raise
267
267
268 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
268 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
269 self.spath = self.store.path
269 self.spath = self.store.path
270 self.svfs = self.store.vfs
270 self.svfs = self.store.vfs
271 self.sopener = self.svfs
271 self.sopener = self.svfs
272 self.sjoin = self.store.join
272 self.sjoin = self.store.join
273 self.vfs.createmode = self.store.createmode
273 self.vfs.createmode = self.store.createmode
274 self._applyrequirements(requirements)
274 self._applyrequirements(requirements)
275 if create:
275 if create:
276 self._writerequirements()
276 self._writerequirements()
277
277
278
278
279 self._branchcaches = {}
279 self._branchcaches = {}
280 self.filterpats = {}
280 self.filterpats = {}
281 self._datafilters = {}
281 self._datafilters = {}
282 self._transref = self._lockref = self._wlockref = None
282 self._transref = self._lockref = self._wlockref = None
283
283
284 # A cache for various files under .hg/ that tracks file changes,
284 # A cache for various files under .hg/ that tracks file changes,
285 # (used by the filecache decorator)
285 # (used by the filecache decorator)
286 #
286 #
287 # Maps a property name to its util.filecacheentry
287 # Maps a property name to its util.filecacheentry
288 self._filecache = {}
288 self._filecache = {}
289
289
290 # hold sets of revision to be filtered
290 # hold sets of revision to be filtered
291 # should be cleared when something might have changed the filter value:
291 # should be cleared when something might have changed the filter value:
292 # - new changesets,
292 # - new changesets,
293 # - phase change,
293 # - phase change,
294 # - new obsolescence marker,
294 # - new obsolescence marker,
295 # - working directory parent change,
295 # - working directory parent change,
296 # - bookmark changes
296 # - bookmark changes
297 self.filteredrevcache = {}
297 self.filteredrevcache = {}
298
298
299 def close(self):
299 def close(self):
300 pass
300 pass
301
301
302 def _restrictcapabilities(self, caps):
302 def _restrictcapabilities(self, caps):
303 # bundle2 is not ready for prime time, drop it unless explicitly
303 # bundle2 is not ready for prime time, drop it unless explicitly
304 # required by the tests (or some brave tester)
304 # required by the tests (or some brave tester)
305 if not self.ui.configbool('server', 'bundle2', False):
305 if not self.ui.configbool('server', 'bundle2', False):
306 caps = set(caps)
306 caps = set(caps)
307 caps.discard('bundle2')
307 caps.discard('bundle2')
308 return caps
308 return caps
309
309
310 def _applyrequirements(self, requirements):
310 def _applyrequirements(self, requirements):
311 self.requirements = requirements
311 self.requirements = requirements
312 self.sopener.options = dict((r, 1) for r in requirements
312 self.sopener.options = dict((r, 1) for r in requirements
313 if r in self.openerreqs)
313 if r in self.openerreqs)
314 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
314 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
315 if chunkcachesize is not None:
315 if chunkcachesize is not None:
316 self.sopener.options['chunkcachesize'] = chunkcachesize
316 self.sopener.options['chunkcachesize'] = chunkcachesize
317
317
318 def _writerequirements(self):
318 def _writerequirements(self):
319 reqfile = self.opener("requires", "w")
319 reqfile = self.opener("requires", "w")
320 for r in sorted(self.requirements):
320 for r in sorted(self.requirements):
321 reqfile.write("%s\n" % r)
321 reqfile.write("%s\n" % r)
322 reqfile.close()
322 reqfile.close()
323
323
324 def _checknested(self, path):
324 def _checknested(self, path):
325 """Determine if path is a legal nested repository."""
325 """Determine if path is a legal nested repository."""
326 if not path.startswith(self.root):
326 if not path.startswith(self.root):
327 return False
327 return False
328 subpath = path[len(self.root) + 1:]
328 subpath = path[len(self.root) + 1:]
329 normsubpath = util.pconvert(subpath)
329 normsubpath = util.pconvert(subpath)
330
330
331 # XXX: Checking against the current working copy is wrong in
331 # XXX: Checking against the current working copy is wrong in
332 # the sense that it can reject things like
332 # the sense that it can reject things like
333 #
333 #
334 # $ hg cat -r 10 sub/x.txt
334 # $ hg cat -r 10 sub/x.txt
335 #
335 #
336 # if sub/ is no longer a subrepository in the working copy
336 # if sub/ is no longer a subrepository in the working copy
337 # parent revision.
337 # parent revision.
338 #
338 #
339 # However, it can of course also allow things that would have
339 # However, it can of course also allow things that would have
340 # been rejected before, such as the above cat command if sub/
340 # been rejected before, such as the above cat command if sub/
341 # is a subrepository now, but was a normal directory before.
341 # is a subrepository now, but was a normal directory before.
342 # The old path auditor would have rejected by mistake since it
342 # The old path auditor would have rejected by mistake since it
343 # panics when it sees sub/.hg/.
343 # panics when it sees sub/.hg/.
344 #
344 #
345 # All in all, checking against the working copy seems sensible
345 # All in all, checking against the working copy seems sensible
346 # since we want to prevent access to nested repositories on
346 # since we want to prevent access to nested repositories on
347 # the filesystem *now*.
347 # the filesystem *now*.
348 ctx = self[None]
348 ctx = self[None]
349 parts = util.splitpath(subpath)
349 parts = util.splitpath(subpath)
350 while parts:
350 while parts:
351 prefix = '/'.join(parts)
351 prefix = '/'.join(parts)
352 if prefix in ctx.substate:
352 if prefix in ctx.substate:
353 if prefix == normsubpath:
353 if prefix == normsubpath:
354 return True
354 return True
355 else:
355 else:
356 sub = ctx.sub(prefix)
356 sub = ctx.sub(prefix)
357 return sub.checknested(subpath[len(prefix) + 1:])
357 return sub.checknested(subpath[len(prefix) + 1:])
358 else:
358 else:
359 parts.pop()
359 parts.pop()
360 return False
360 return False
361
361
362 def peer(self):
362 def peer(self):
363 return localpeer(self) # not cached to avoid reference cycle
363 return localpeer(self) # not cached to avoid reference cycle
364
364
365 def unfiltered(self):
365 def unfiltered(self):
366 """Return unfiltered version of the repository
366 """Return unfiltered version of the repository
367
367
368 Intended to be overwritten by filtered repo."""
368 Intended to be overwritten by filtered repo."""
369 return self
369 return self
370
370
371 def filtered(self, name):
371 def filtered(self, name):
372 """Return a filtered version of a repository"""
372 """Return a filtered version of a repository"""
373 # build a new class with the mixin and the current class
373 # build a new class with the mixin and the current class
374 # (possibly subclass of the repo)
374 # (possibly subclass of the repo)
375 class proxycls(repoview.repoview, self.unfiltered().__class__):
375 class proxycls(repoview.repoview, self.unfiltered().__class__):
376 pass
376 pass
377 return proxycls(self, name)
377 return proxycls(self, name)
378
378
379 @repofilecache('bookmarks')
379 @repofilecache('bookmarks')
380 def _bookmarks(self):
380 def _bookmarks(self):
381 return bookmarks.bmstore(self)
381 return bookmarks.bmstore(self)
382
382
383 @repofilecache('bookmarks.current')
383 @repofilecache('bookmarks.current')
384 def _bookmarkcurrent(self):
384 def _bookmarkcurrent(self):
385 return bookmarks.readcurrent(self)
385 return bookmarks.readcurrent(self)
386
386
387 def bookmarkheads(self, bookmark):
387 def bookmarkheads(self, bookmark):
388 name = bookmark.split('@', 1)[0]
388 name = bookmark.split('@', 1)[0]
389 heads = []
389 heads = []
390 for mark, n in self._bookmarks.iteritems():
390 for mark, n in self._bookmarks.iteritems():
391 if mark.split('@', 1)[0] == name:
391 if mark.split('@', 1)[0] == name:
392 heads.append(n)
392 heads.append(n)
393 return heads
393 return heads
394
394
395 @storecache('phaseroots')
395 @storecache('phaseroots')
396 def _phasecache(self):
396 def _phasecache(self):
397 return phases.phasecache(self, self._phasedefaults)
397 return phases.phasecache(self, self._phasedefaults)
398
398
399 @storecache('obsstore')
399 @storecache('obsstore')
400 def obsstore(self):
400 def obsstore(self):
401 store = obsolete.obsstore(self.sopener)
401 store = obsolete.obsstore(self.sopener)
402 if store and not obsolete._enabled:
402 if store and not obsolete._enabled:
403 # message is rare enough to not be translated
403 # message is rare enough to not be translated
404 msg = 'obsolete feature not enabled but %i markers found!\n'
404 msg = 'obsolete feature not enabled but %i markers found!\n'
405 self.ui.warn(msg % len(list(store)))
405 self.ui.warn(msg % len(list(store)))
406 return store
406 return store
407
407
408 @storecache('00changelog.i')
408 @storecache('00changelog.i')
409 def changelog(self):
409 def changelog(self):
410 c = changelog.changelog(self.sopener)
410 c = changelog.changelog(self.sopener)
411 if 'HG_PENDING' in os.environ:
411 if 'HG_PENDING' in os.environ:
412 p = os.environ['HG_PENDING']
412 p = os.environ['HG_PENDING']
413 if p.startswith(self.root):
413 if p.startswith(self.root):
414 c.readpending('00changelog.i.a')
414 c.readpending('00changelog.i.a')
415 return c
415 return c
416
416
417 @storecache('00manifest.i')
417 @storecache('00manifest.i')
418 def manifest(self):
418 def manifest(self):
419 return manifest.manifest(self.sopener)
419 return manifest.manifest(self.sopener)
420
420
421 @repofilecache('dirstate')
421 @repofilecache('dirstate')
422 def dirstate(self):
422 def dirstate(self):
423 warned = [0]
423 warned = [0]
424 def validate(node):
424 def validate(node):
425 try:
425 try:
426 self.changelog.rev(node)
426 self.changelog.rev(node)
427 return node
427 return node
428 except error.LookupError:
428 except error.LookupError:
429 if not warned[0]:
429 if not warned[0]:
430 warned[0] = True
430 warned[0] = True
431 self.ui.warn(_("warning: ignoring unknown"
431 self.ui.warn(_("warning: ignoring unknown"
432 " working parent %s!\n") % short(node))
432 " working parent %s!\n") % short(node))
433 return nullid
433 return nullid
434
434
435 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
435 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
436
436
437 def __getitem__(self, changeid):
437 def __getitem__(self, changeid):
438 if changeid is None:
438 if changeid is None:
439 return context.workingctx(self)
439 return context.workingctx(self)
440 return context.changectx(self, changeid)
440 return context.changectx(self, changeid)
441
441
442 def __contains__(self, changeid):
442 def __contains__(self, changeid):
443 try:
443 try:
444 return bool(self.lookup(changeid))
444 return bool(self.lookup(changeid))
445 except error.RepoLookupError:
445 except error.RepoLookupError:
446 return False
446 return False
447
447
448 def __nonzero__(self):
448 def __nonzero__(self):
449 return True
449 return True
450
450
451 def __len__(self):
451 def __len__(self):
452 return len(self.changelog)
452 return len(self.changelog)
453
453
454 def __iter__(self):
454 def __iter__(self):
455 return iter(self.changelog)
455 return iter(self.changelog)
456
456
457 def revs(self, expr, *args):
457 def revs(self, expr, *args):
458 '''Return a list of revisions matching the given revset'''
458 '''Return a list of revisions matching the given revset'''
459 expr = revset.formatspec(expr, *args)
459 expr = revset.formatspec(expr, *args)
460 m = revset.match(None, expr)
460 m = revset.match(None, expr)
461 return m(self, revset.spanset(self))
461 return m(self, revset.spanset(self))
462
462
463 def set(self, expr, *args):
463 def set(self, expr, *args):
464 '''
464 '''
465 Yield a context for each matching revision, after doing arg
465 Yield a context for each matching revision, after doing arg
466 replacement via revset.formatspec
466 replacement via revset.formatspec
467 '''
467 '''
468 for r in self.revs(expr, *args):
468 for r in self.revs(expr, *args):
469 yield self[r]
469 yield self[r]
470
470
471 def url(self):
471 def url(self):
472 return 'file:' + self.root
472 return 'file:' + self.root
473
473
474 def hook(self, name, throw=False, **args):
474 def hook(self, name, throw=False, **args):
475 return hook.hook(self.ui, self, name, throw, **args)
475 return hook.hook(self.ui, self, name, throw, **args)
476
476
477 @unfilteredmethod
477 @unfilteredmethod
478 def _tag(self, names, node, message, local, user, date, extra={}):
478 def _tag(self, names, node, message, local, user, date, extra={}):
479 if isinstance(names, str):
479 if isinstance(names, str):
480 names = (names,)
480 names = (names,)
481
481
482 branches = self.branchmap()
482 branches = self.branchmap()
483 for name in names:
483 for name in names:
484 self.hook('pretag', throw=True, node=hex(node), tag=name,
484 self.hook('pretag', throw=True, node=hex(node), tag=name,
485 local=local)
485 local=local)
486 if name in branches:
486 if name in branches:
487 self.ui.warn(_("warning: tag %s conflicts with existing"
487 self.ui.warn(_("warning: tag %s conflicts with existing"
488 " branch name\n") % name)
488 " branch name\n") % name)
489
489
490 def writetags(fp, names, munge, prevtags):
490 def writetags(fp, names, munge, prevtags):
491 fp.seek(0, 2)
491 fp.seek(0, 2)
492 if prevtags and prevtags[-1] != '\n':
492 if prevtags and prevtags[-1] != '\n':
493 fp.write('\n')
493 fp.write('\n')
494 for name in names:
494 for name in names:
495 m = munge and munge(name) or name
495 m = munge and munge(name) or name
496 if (self._tagscache.tagtypes and
496 if (self._tagscache.tagtypes and
497 name in self._tagscache.tagtypes):
497 name in self._tagscache.tagtypes):
498 old = self.tags().get(name, nullid)
498 old = self.tags().get(name, nullid)
499 fp.write('%s %s\n' % (hex(old), m))
499 fp.write('%s %s\n' % (hex(old), m))
500 fp.write('%s %s\n' % (hex(node), m))
500 fp.write('%s %s\n' % (hex(node), m))
501 fp.close()
501 fp.close()
502
502
503 prevtags = ''
503 prevtags = ''
504 if local:
504 if local:
505 try:
505 try:
506 fp = self.opener('localtags', 'r+')
506 fp = self.opener('localtags', 'r+')
507 except IOError:
507 except IOError:
508 fp = self.opener('localtags', 'a')
508 fp = self.opener('localtags', 'a')
509 else:
509 else:
510 prevtags = fp.read()
510 prevtags = fp.read()
511
511
512 # local tags are stored in the current charset
512 # local tags are stored in the current charset
513 writetags(fp, names, None, prevtags)
513 writetags(fp, names, None, prevtags)
514 for name in names:
514 for name in names:
515 self.hook('tag', node=hex(node), tag=name, local=local)
515 self.hook('tag', node=hex(node), tag=name, local=local)
516 return
516 return
517
517
518 try:
518 try:
519 fp = self.wfile('.hgtags', 'rb+')
519 fp = self.wfile('.hgtags', 'rb+')
520 except IOError, e:
520 except IOError, e:
521 if e.errno != errno.ENOENT:
521 if e.errno != errno.ENOENT:
522 raise
522 raise
523 fp = self.wfile('.hgtags', 'ab')
523 fp = self.wfile('.hgtags', 'ab')
524 else:
524 else:
525 prevtags = fp.read()
525 prevtags = fp.read()
526
526
527 # committed tags are stored in UTF-8
527 # committed tags are stored in UTF-8
528 writetags(fp, names, encoding.fromlocal, prevtags)
528 writetags(fp, names, encoding.fromlocal, prevtags)
529
529
530 fp.close()
530 fp.close()
531
531
532 self.invalidatecaches()
532 self.invalidatecaches()
533
533
534 if '.hgtags' not in self.dirstate:
534 if '.hgtags' not in self.dirstate:
535 self[None].add(['.hgtags'])
535 self[None].add(['.hgtags'])
536
536
537 m = matchmod.exact(self.root, '', ['.hgtags'])
537 m = matchmod.exact(self.root, '', ['.hgtags'])
538 tagnode = self.commit(message, user, date, extra=extra, match=m)
538 tagnode = self.commit(message, user, date, extra=extra, match=m)
539
539
540 for name in names:
540 for name in names:
541 self.hook('tag', node=hex(node), tag=name, local=local)
541 self.hook('tag', node=hex(node), tag=name, local=local)
542
542
543 return tagnode
543 return tagnode
544
544
545 def tag(self, names, node, message, local, user, date):
545 def tag(self, names, node, message, local, user, date):
546 '''tag a revision with one or more symbolic names.
546 '''tag a revision with one or more symbolic names.
547
547
548 names is a list of strings or, when adding a single tag, names may be a
548 names is a list of strings or, when adding a single tag, names may be a
549 string.
549 string.
550
550
551 if local is True, the tags are stored in a per-repository file.
551 if local is True, the tags are stored in a per-repository file.
552 otherwise, they are stored in the .hgtags file, and a new
552 otherwise, they are stored in the .hgtags file, and a new
553 changeset is committed with the change.
553 changeset is committed with the change.
554
554
555 keyword arguments:
555 keyword arguments:
556
556
557 local: whether to store tags in non-version-controlled file
557 local: whether to store tags in non-version-controlled file
558 (default False)
558 (default False)
559
559
560 message: commit message to use if committing
560 message: commit message to use if committing
561
561
562 user: name of user to use if committing
562 user: name of user to use if committing
563
563
564 date: date tuple to use if committing'''
564 date: date tuple to use if committing'''
565
565
566 if not local:
566 if not local:
567 for x in self.status()[:5]:
567 for x in self.status()[:5]:
568 if '.hgtags' in x:
568 if '.hgtags' in x:
569 raise util.Abort(_('working copy of .hgtags is changed '
569 raise util.Abort(_('working copy of .hgtags is changed '
570 '(please commit .hgtags manually)'))
570 '(please commit .hgtags manually)'))
571
571
572 self.tags() # instantiate the cache
572 self.tags() # instantiate the cache
573 self._tag(names, node, message, local, user, date)
573 self._tag(names, node, message, local, user, date)
574
574
575 @filteredpropertycache
575 @filteredpropertycache
576 def _tagscache(self):
576 def _tagscache(self):
577 '''Returns a tagscache object that contains various tags related
577 '''Returns a tagscache object that contains various tags related
578 caches.'''
578 caches.'''
579
579
580 # This simplifies its cache management by having one decorated
580 # This simplifies its cache management by having one decorated
581 # function (this one) and the rest simply fetch things from it.
581 # function (this one) and the rest simply fetch things from it.
582 class tagscache(object):
582 class tagscache(object):
583 def __init__(self):
583 def __init__(self):
584 # These two define the set of tags for this repository. tags
584 # These two define the set of tags for this repository. tags
585 # maps tag name to node; tagtypes maps tag name to 'global' or
585 # maps tag name to node; tagtypes maps tag name to 'global' or
586 # 'local'. (Global tags are defined by .hgtags across all
586 # 'local'. (Global tags are defined by .hgtags across all
587 # heads, and local tags are defined in .hg/localtags.)
587 # heads, and local tags are defined in .hg/localtags.)
588 # They constitute the in-memory cache of tags.
588 # They constitute the in-memory cache of tags.
589 self.tags = self.tagtypes = None
589 self.tags = self.tagtypes = None
590
590
591 self.nodetagscache = self.tagslist = None
591 self.nodetagscache = self.tagslist = None
592
592
593 cache = tagscache()
593 cache = tagscache()
594 cache.tags, cache.tagtypes = self._findtags()
594 cache.tags, cache.tagtypes = self._findtags()
595
595
596 return cache
596 return cache
597
597
598 def tags(self):
598 def tags(self):
599 '''return a mapping of tag to node'''
599 '''return a mapping of tag to node'''
600 t = {}
600 t = {}
601 if self.changelog.filteredrevs:
601 if self.changelog.filteredrevs:
602 tags, tt = self._findtags()
602 tags, tt = self._findtags()
603 else:
603 else:
604 tags = self._tagscache.tags
604 tags = self._tagscache.tags
605 for k, v in tags.iteritems():
605 for k, v in tags.iteritems():
606 try:
606 try:
607 # ignore tags to unknown nodes
607 # ignore tags to unknown nodes
608 self.changelog.rev(v)
608 self.changelog.rev(v)
609 t[k] = v
609 t[k] = v
610 except (error.LookupError, ValueError):
610 except (error.LookupError, ValueError):
611 pass
611 pass
612 return t
612 return t
613
613
614 def _findtags(self):
614 def _findtags(self):
615 '''Do the hard work of finding tags. Return a pair of dicts
615 '''Do the hard work of finding tags. Return a pair of dicts
616 (tags, tagtypes) where tags maps tag name to node, and tagtypes
616 (tags, tagtypes) where tags maps tag name to node, and tagtypes
617 maps tag name to a string like \'global\' or \'local\'.
617 maps tag name to a string like \'global\' or \'local\'.
618 Subclasses or extensions are free to add their own tags, but
618 Subclasses or extensions are free to add their own tags, but
619 should be aware that the returned dicts will be retained for the
619 should be aware that the returned dicts will be retained for the
620 duration of the localrepo object.'''
620 duration of the localrepo object.'''
621
621
622 # XXX what tagtype should subclasses/extensions use? Currently
622 # XXX what tagtype should subclasses/extensions use? Currently
623 # mq and bookmarks add tags, but do not set the tagtype at all.
623 # mq and bookmarks add tags, but do not set the tagtype at all.
624 # Should each extension invent its own tag type? Should there
624 # Should each extension invent its own tag type? Should there
625 # be one tagtype for all such "virtual" tags? Or is the status
625 # be one tagtype for all such "virtual" tags? Or is the status
626 # quo fine?
626 # quo fine?
627
627
628 alltags = {} # map tag name to (node, hist)
628 alltags = {} # map tag name to (node, hist)
629 tagtypes = {}
629 tagtypes = {}
630
630
631 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
631 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
632 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
632 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
633
633
634 # Build the return dicts. Have to re-encode tag names because
634 # Build the return dicts. Have to re-encode tag names because
635 # the tags module always uses UTF-8 (in order not to lose info
635 # the tags module always uses UTF-8 (in order not to lose info
636 # writing to the cache), but the rest of Mercurial wants them in
636 # writing to the cache), but the rest of Mercurial wants them in
637 # local encoding.
637 # local encoding.
638 tags = {}
638 tags = {}
639 for (name, (node, hist)) in alltags.iteritems():
639 for (name, (node, hist)) in alltags.iteritems():
640 if node != nullid:
640 if node != nullid:
641 tags[encoding.tolocal(name)] = node
641 tags[encoding.tolocal(name)] = node
642 tags['tip'] = self.changelog.tip()
642 tags['tip'] = self.changelog.tip()
643 tagtypes = dict([(encoding.tolocal(name), value)
643 tagtypes = dict([(encoding.tolocal(name), value)
644 for (name, value) in tagtypes.iteritems()])
644 for (name, value) in tagtypes.iteritems()])
645 return (tags, tagtypes)
645 return (tags, tagtypes)
646
646
647 def tagtype(self, tagname):
647 def tagtype(self, tagname):
648 '''
648 '''
649 return the type of the given tag. result can be:
649 return the type of the given tag. result can be:
650
650
651 'local' : a local tag
651 'local' : a local tag
652 'global' : a global tag
652 'global' : a global tag
653 None : tag does not exist
653 None : tag does not exist
654 '''
654 '''
655
655
656 return self._tagscache.tagtypes.get(tagname)
656 return self._tagscache.tagtypes.get(tagname)
657
657
658 def tagslist(self):
658 def tagslist(self):
659 '''return a list of tags ordered by revision'''
659 '''return a list of tags ordered by revision'''
660 if not self._tagscache.tagslist:
660 if not self._tagscache.tagslist:
661 l = []
661 l = []
662 for t, n in self.tags().iteritems():
662 for t, n in self.tags().iteritems():
663 r = self.changelog.rev(n)
663 r = self.changelog.rev(n)
664 l.append((r, t, n))
664 l.append((r, t, n))
665 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
665 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
666
666
667 return self._tagscache.tagslist
667 return self._tagscache.tagslist
668
668
669 def nodetags(self, node):
669 def nodetags(self, node):
670 '''return the tags associated with a node'''
670 '''return the tags associated with a node'''
671 if not self._tagscache.nodetagscache:
671 if not self._tagscache.nodetagscache:
672 nodetagscache = {}
672 nodetagscache = {}
673 for t, n in self._tagscache.tags.iteritems():
673 for t, n in self._tagscache.tags.iteritems():
674 nodetagscache.setdefault(n, []).append(t)
674 nodetagscache.setdefault(n, []).append(t)
675 for tags in nodetagscache.itervalues():
675 for tags in nodetagscache.itervalues():
676 tags.sort()
676 tags.sort()
677 self._tagscache.nodetagscache = nodetagscache
677 self._tagscache.nodetagscache = nodetagscache
678 return self._tagscache.nodetagscache.get(node, [])
678 return self._tagscache.nodetagscache.get(node, [])
679
679
680 def nodebookmarks(self, node):
680 def nodebookmarks(self, node):
681 marks = []
681 marks = []
682 for bookmark, n in self._bookmarks.iteritems():
682 for bookmark, n in self._bookmarks.iteritems():
683 if n == node:
683 if n == node:
684 marks.append(bookmark)
684 marks.append(bookmark)
685 return sorted(marks)
685 return sorted(marks)
686
686
687 def branchmap(self):
687 def branchmap(self):
688 '''returns a dictionary {branch: [branchheads]} with branchheads
688 '''returns a dictionary {branch: [branchheads]} with branchheads
689 ordered by increasing revision number'''
689 ordered by increasing revision number'''
690 branchmap.updatecache(self)
690 branchmap.updatecache(self)
691 return self._branchcaches[self.filtername]
691 return self._branchcaches[self.filtername]
692
692
693 def branchtip(self, branch):
693 def branchtip(self, branch):
694 '''return the tip node for a given branch'''
694 '''return the tip node for a given branch'''
695 try:
695 try:
696 return self.branchmap().branchtip(branch)
696 return self.branchmap().branchtip(branch)
697 except KeyError:
697 except KeyError:
698 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
698 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
699
699
700 def lookup(self, key):
700 def lookup(self, key):
701 return self[key].node()
701 return self[key].node()
702
702
703 def lookupbranch(self, key, remote=None):
703 def lookupbranch(self, key, remote=None):
704 repo = remote or self
704 repo = remote or self
705 if key in repo.branchmap():
705 if key in repo.branchmap():
706 return key
706 return key
707
707
708 repo = (remote and remote.local()) and remote or self
708 repo = (remote and remote.local()) and remote or self
709 return repo[key].branch()
709 return repo[key].branch()
710
710
711 def known(self, nodes):
711 def known(self, nodes):
712 nm = self.changelog.nodemap
712 nm = self.changelog.nodemap
713 pc = self._phasecache
713 pc = self._phasecache
714 result = []
714 result = []
715 for n in nodes:
715 for n in nodes:
716 r = nm.get(n)
716 r = nm.get(n)
717 resp = not (r is None or pc.phase(self, r) >= phases.secret)
717 resp = not (r is None or pc.phase(self, r) >= phases.secret)
718 result.append(resp)
718 result.append(resp)
719 return result
719 return result
720
720
721 def local(self):
721 def local(self):
722 return self
722 return self
723
723
724 def cancopy(self):
724 def cancopy(self):
725 # so statichttprepo's override of local() works
725 # so statichttprepo's override of local() works
726 if not self.local():
726 if not self.local():
727 return False
727 return False
728 if not self.ui.configbool('phases', 'publish', True):
728 if not self.ui.configbool('phases', 'publish', True):
729 return True
729 return True
730 # if publishing we can't copy if there is filtered content
730 # if publishing we can't copy if there is filtered content
731 return not self.filtered('visible').changelog.filteredrevs
731 return not self.filtered('visible').changelog.filteredrevs
732
732
733 def join(self, f):
733 def join(self, f):
734 return os.path.join(self.path, f)
734 return os.path.join(self.path, f)
735
735
736 def wjoin(self, f):
736 def wjoin(self, f):
737 return os.path.join(self.root, f)
737 return os.path.join(self.root, f)
738
738
739 def file(self, f):
739 def file(self, f):
740 if f[0] == '/':
740 if f[0] == '/':
741 f = f[1:]
741 f = f[1:]
742 return filelog.filelog(self.sopener, f)
742 return filelog.filelog(self.sopener, f)
743
743
744 def changectx(self, changeid):
744 def changectx(self, changeid):
745 return self[changeid]
745 return self[changeid]
746
746
747 def parents(self, changeid=None):
747 def parents(self, changeid=None):
748 '''get list of changectxs for parents of changeid'''
748 '''get list of changectxs for parents of changeid'''
749 return self[changeid].parents()
749 return self[changeid].parents()
750
750
751 def setparents(self, p1, p2=nullid):
751 def setparents(self, p1, p2=nullid):
752 copies = self.dirstate.setparents(p1, p2)
752 copies = self.dirstate.setparents(p1, p2)
753 pctx = self[p1]
753 pctx = self[p1]
754 if copies:
754 if copies:
755 # Adjust copy records, the dirstate cannot do it, it
755 # Adjust copy records, the dirstate cannot do it, it
756 # requires access to parents manifests. Preserve them
756 # requires access to parents manifests. Preserve them
757 # only for entries added to first parent.
757 # only for entries added to first parent.
758 for f in copies:
758 for f in copies:
759 if f not in pctx and copies[f] in pctx:
759 if f not in pctx and copies[f] in pctx:
760 self.dirstate.copy(copies[f], f)
760 self.dirstate.copy(copies[f], f)
761 if p2 == nullid:
761 if p2 == nullid:
762 for f, s in sorted(self.dirstate.copies().items()):
762 for f, s in sorted(self.dirstate.copies().items()):
763 if f not in pctx and s not in pctx:
763 if f not in pctx and s not in pctx:
764 self.dirstate.copy(None, f)
764 self.dirstate.copy(None, f)
765
765
766 def filectx(self, path, changeid=None, fileid=None):
766 def filectx(self, path, changeid=None, fileid=None):
767 """changeid can be a changeset revision, node, or tag.
767 """changeid can be a changeset revision, node, or tag.
768 fileid can be a file revision or node."""
768 fileid can be a file revision or node."""
769 return context.filectx(self, path, changeid, fileid)
769 return context.filectx(self, path, changeid, fileid)
770
770
771 def getcwd(self):
771 def getcwd(self):
772 return self.dirstate.getcwd()
772 return self.dirstate.getcwd()
773
773
774 def pathto(self, f, cwd=None):
774 def pathto(self, f, cwd=None):
775 return self.dirstate.pathto(f, cwd)
775 return self.dirstate.pathto(f, cwd)
776
776
777 def wfile(self, f, mode='r'):
777 def wfile(self, f, mode='r'):
778 return self.wopener(f, mode)
778 return self.wopener(f, mode)
779
779
780 def _link(self, f):
780 def _link(self, f):
781 return self.wvfs.islink(f)
781 return self.wvfs.islink(f)
782
782
783 def _loadfilter(self, filter):
783 def _loadfilter(self, filter):
784 if filter not in self.filterpats:
784 if filter not in self.filterpats:
785 l = []
785 l = []
786 for pat, cmd in self.ui.configitems(filter):
786 for pat, cmd in self.ui.configitems(filter):
787 if cmd == '!':
787 if cmd == '!':
788 continue
788 continue
789 mf = matchmod.match(self.root, '', [pat])
789 mf = matchmod.match(self.root, '', [pat])
790 fn = None
790 fn = None
791 params = cmd
791 params = cmd
792 for name, filterfn in self._datafilters.iteritems():
792 for name, filterfn in self._datafilters.iteritems():
793 if cmd.startswith(name):
793 if cmd.startswith(name):
794 fn = filterfn
794 fn = filterfn
795 params = cmd[len(name):].lstrip()
795 params = cmd[len(name):].lstrip()
796 break
796 break
797 if not fn:
797 if not fn:
798 fn = lambda s, c, **kwargs: util.filter(s, c)
798 fn = lambda s, c, **kwargs: util.filter(s, c)
799 # Wrap old filters not supporting keyword arguments
799 # Wrap old filters not supporting keyword arguments
800 if not inspect.getargspec(fn)[2]:
800 if not inspect.getargspec(fn)[2]:
801 oldfn = fn
801 oldfn = fn
802 fn = lambda s, c, **kwargs: oldfn(s, c)
802 fn = lambda s, c, **kwargs: oldfn(s, c)
803 l.append((mf, fn, params))
803 l.append((mf, fn, params))
804 self.filterpats[filter] = l
804 self.filterpats[filter] = l
805 return self.filterpats[filter]
805 return self.filterpats[filter]
806
806
807 def _filter(self, filterpats, filename, data):
807 def _filter(self, filterpats, filename, data):
808 for mf, fn, cmd in filterpats:
808 for mf, fn, cmd in filterpats:
809 if mf(filename):
809 if mf(filename):
810 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
810 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
811 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
811 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
812 break
812 break
813
813
814 return data
814 return data
815
815
816 @unfilteredpropertycache
816 @unfilteredpropertycache
817 def _encodefilterpats(self):
817 def _encodefilterpats(self):
818 return self._loadfilter('encode')
818 return self._loadfilter('encode')
819
819
820 @unfilteredpropertycache
820 @unfilteredpropertycache
821 def _decodefilterpats(self):
821 def _decodefilterpats(self):
822 return self._loadfilter('decode')
822 return self._loadfilter('decode')
823
823
824 def adddatafilter(self, name, filter):
824 def adddatafilter(self, name, filter):
825 self._datafilters[name] = filter
825 self._datafilters[name] = filter
826
826
827 def wread(self, filename):
827 def wread(self, filename):
828 if self._link(filename):
828 if self._link(filename):
829 data = self.wvfs.readlink(filename)
829 data = self.wvfs.readlink(filename)
830 else:
830 else:
831 data = self.wopener.read(filename)
831 data = self.wopener.read(filename)
832 return self._filter(self._encodefilterpats, filename, data)
832 return self._filter(self._encodefilterpats, filename, data)
833
833
834 def wwrite(self, filename, data, flags):
834 def wwrite(self, filename, data, flags):
835 data = self._filter(self._decodefilterpats, filename, data)
835 data = self._filter(self._decodefilterpats, filename, data)
836 if 'l' in flags:
836 if 'l' in flags:
837 self.wopener.symlink(data, filename)
837 self.wopener.symlink(data, filename)
838 else:
838 else:
839 self.wopener.write(filename, data)
839 self.wopener.write(filename, data)
840 if 'x' in flags:
840 if 'x' in flags:
841 self.wvfs.setflags(filename, False, True)
841 self.wvfs.setflags(filename, False, True)
842
842
843 def wwritedata(self, filename, data):
843 def wwritedata(self, filename, data):
844 return self._filter(self._decodefilterpats, filename, data)
844 return self._filter(self._decodefilterpats, filename, data)
845
845
846 def transaction(self, desc, report=None):
846 def transaction(self, desc, report=None):
847 tr = self._transref and self._transref() or None
847 tr = self._transref and self._transref() or None
848 if tr and tr.running():
848 if tr and tr.running():
849 return tr.nest()
849 return tr.nest()
850
850
851 # abort here if the journal already exists
851 # abort here if the journal already exists
852 if self.svfs.exists("journal"):
852 if self.svfs.exists("journal"):
853 raise error.RepoError(
853 raise error.RepoError(
854 _("abandoned transaction found - run hg recover"))
854 _("abandoned transaction found - run hg recover"))
855
855
856 def onclose():
856 def onclose():
857 self.store.write(tr)
857 self.store.write(tr)
858
858
859 self._writejournal(desc)
859 self._writejournal(desc)
860 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
860 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
861 rp = report and report or self.ui.warn
861 rp = report and report or self.ui.warn
862 tr = transaction.transaction(rp, self.sopener,
862 tr = transaction.transaction(rp, self.sopener,
863 "journal",
863 "journal",
864 aftertrans(renames),
864 aftertrans(renames),
865 self.store.createmode,
865 self.store.createmode,
866 onclose)
866 onclose)
867 self._transref = weakref.ref(tr)
867 self._transref = weakref.ref(tr)
868 return tr
868 return tr
869
869
870 def _journalfiles(self):
870 def _journalfiles(self):
871 return ((self.svfs, 'journal'),
871 return ((self.svfs, 'journal'),
872 (self.vfs, 'journal.dirstate'),
872 (self.vfs, 'journal.dirstate'),
873 (self.vfs, 'journal.branch'),
873 (self.vfs, 'journal.branch'),
874 (self.vfs, 'journal.desc'),
874 (self.vfs, 'journal.desc'),
875 (self.vfs, 'journal.bookmarks'),
875 (self.vfs, 'journal.bookmarks'),
876 (self.svfs, 'journal.phaseroots'))
876 (self.svfs, 'journal.phaseroots'))
877
877
878 def undofiles(self):
878 def undofiles(self):
879 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
879 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
880
880
881 def _writejournal(self, desc):
881 def _writejournal(self, desc):
882 self.opener.write("journal.dirstate",
882 self.opener.write("journal.dirstate",
883 self.opener.tryread("dirstate"))
883 self.opener.tryread("dirstate"))
884 self.opener.write("journal.branch",
884 self.opener.write("journal.branch",
885 encoding.fromlocal(self.dirstate.branch()))
885 encoding.fromlocal(self.dirstate.branch()))
886 self.opener.write("journal.desc",
886 self.opener.write("journal.desc",
887 "%d\n%s\n" % (len(self), desc))
887 "%d\n%s\n" % (len(self), desc))
888 self.opener.write("journal.bookmarks",
888 self.opener.write("journal.bookmarks",
889 self.opener.tryread("bookmarks"))
889 self.opener.tryread("bookmarks"))
890 self.sopener.write("journal.phaseroots",
890 self.sopener.write("journal.phaseroots",
891 self.sopener.tryread("phaseroots"))
891 self.sopener.tryread("phaseroots"))
892
892
893 def recover(self):
893 def recover(self):
894 lock = self.lock()
894 lock = self.lock()
895 try:
895 try:
896 if self.svfs.exists("journal"):
896 if self.svfs.exists("journal"):
897 self.ui.status(_("rolling back interrupted transaction\n"))
897 self.ui.status(_("rolling back interrupted transaction\n"))
898 transaction.rollback(self.sopener, "journal",
898 transaction.rollback(self.sopener, "journal",
899 self.ui.warn)
899 self.ui.warn)
900 self.invalidate()
900 self.invalidate()
901 return True
901 return True
902 else:
902 else:
903 self.ui.warn(_("no interrupted transaction available\n"))
903 self.ui.warn(_("no interrupted transaction available\n"))
904 return False
904 return False
905 finally:
905 finally:
906 lock.release()
906 lock.release()
907
907
908 def rollback(self, dryrun=False, force=False):
908 def rollback(self, dryrun=False, force=False):
909 wlock = lock = None
909 wlock = lock = None
910 try:
910 try:
911 wlock = self.wlock()
911 wlock = self.wlock()
912 lock = self.lock()
912 lock = self.lock()
913 if self.svfs.exists("undo"):
913 if self.svfs.exists("undo"):
914 return self._rollback(dryrun, force)
914 return self._rollback(dryrun, force)
915 else:
915 else:
916 self.ui.warn(_("no rollback information available\n"))
916 self.ui.warn(_("no rollback information available\n"))
917 return 1
917 return 1
918 finally:
918 finally:
919 release(lock, wlock)
919 release(lock, wlock)
920
920
921 @unfilteredmethod # Until we get smarter cache management
921 @unfilteredmethod # Until we get smarter cache management
922 def _rollback(self, dryrun, force):
922 def _rollback(self, dryrun, force):
923 ui = self.ui
923 ui = self.ui
924 try:
924 try:
925 args = self.opener.read('undo.desc').splitlines()
925 args = self.opener.read('undo.desc').splitlines()
926 (oldlen, desc, detail) = (int(args[0]), args[1], None)
926 (oldlen, desc, detail) = (int(args[0]), args[1], None)
927 if len(args) >= 3:
927 if len(args) >= 3:
928 detail = args[2]
928 detail = args[2]
929 oldtip = oldlen - 1
929 oldtip = oldlen - 1
930
930
931 if detail and ui.verbose:
931 if detail and ui.verbose:
932 msg = (_('repository tip rolled back to revision %s'
932 msg = (_('repository tip rolled back to revision %s'
933 ' (undo %s: %s)\n')
933 ' (undo %s: %s)\n')
934 % (oldtip, desc, detail))
934 % (oldtip, desc, detail))
935 else:
935 else:
936 msg = (_('repository tip rolled back to revision %s'
936 msg = (_('repository tip rolled back to revision %s'
937 ' (undo %s)\n')
937 ' (undo %s)\n')
938 % (oldtip, desc))
938 % (oldtip, desc))
939 except IOError:
939 except IOError:
940 msg = _('rolling back unknown transaction\n')
940 msg = _('rolling back unknown transaction\n')
941 desc = None
941 desc = None
942
942
943 if not force and self['.'] != self['tip'] and desc == 'commit':
943 if not force and self['.'] != self['tip'] and desc == 'commit':
944 raise util.Abort(
944 raise util.Abort(
945 _('rollback of last commit while not checked out '
945 _('rollback of last commit while not checked out '
946 'may lose data'), hint=_('use -f to force'))
946 'may lose data'), hint=_('use -f to force'))
947
947
948 ui.status(msg)
948 ui.status(msg)
949 if dryrun:
949 if dryrun:
950 return 0
950 return 0
951
951
952 parents = self.dirstate.parents()
952 parents = self.dirstate.parents()
953 self.destroying()
953 self.destroying()
954 transaction.rollback(self.sopener, 'undo', ui.warn)
954 transaction.rollback(self.sopener, 'undo', ui.warn)
955 if self.vfs.exists('undo.bookmarks'):
955 if self.vfs.exists('undo.bookmarks'):
956 self.vfs.rename('undo.bookmarks', 'bookmarks')
956 self.vfs.rename('undo.bookmarks', 'bookmarks')
957 if self.svfs.exists('undo.phaseroots'):
957 if self.svfs.exists('undo.phaseroots'):
958 self.svfs.rename('undo.phaseroots', 'phaseroots')
958 self.svfs.rename('undo.phaseroots', 'phaseroots')
959 self.invalidate()
959 self.invalidate()
960
960
961 parentgone = (parents[0] not in self.changelog.nodemap or
961 parentgone = (parents[0] not in self.changelog.nodemap or
962 parents[1] not in self.changelog.nodemap)
962 parents[1] not in self.changelog.nodemap)
963 if parentgone:
963 if parentgone:
964 self.vfs.rename('undo.dirstate', 'dirstate')
964 self.vfs.rename('undo.dirstate', 'dirstate')
965 try:
965 try:
966 branch = self.opener.read('undo.branch')
966 branch = self.opener.read('undo.branch')
967 self.dirstate.setbranch(encoding.tolocal(branch))
967 self.dirstate.setbranch(encoding.tolocal(branch))
968 except IOError:
968 except IOError:
969 ui.warn(_('named branch could not be reset: '
969 ui.warn(_('named branch could not be reset: '
970 'current branch is still \'%s\'\n')
970 'current branch is still \'%s\'\n')
971 % self.dirstate.branch())
971 % self.dirstate.branch())
972
972
973 self.dirstate.invalidate()
973 self.dirstate.invalidate()
974 parents = tuple([p.rev() for p in self.parents()])
974 parents = tuple([p.rev() for p in self.parents()])
975 if len(parents) > 1:
975 if len(parents) > 1:
976 ui.status(_('working directory now based on '
976 ui.status(_('working directory now based on '
977 'revisions %d and %d\n') % parents)
977 'revisions %d and %d\n') % parents)
978 else:
978 else:
979 ui.status(_('working directory now based on '
979 ui.status(_('working directory now based on '
980 'revision %d\n') % parents)
980 'revision %d\n') % parents)
981 # TODO: if we know which new heads may result from this rollback, pass
981 # TODO: if we know which new heads may result from this rollback, pass
982 # them to destroy(), which will prevent the branchhead cache from being
982 # them to destroy(), which will prevent the branchhead cache from being
983 # invalidated.
983 # invalidated.
984 self.destroyed()
984 self.destroyed()
985 return 0
985 return 0
986
986
987 def invalidatecaches(self):
987 def invalidatecaches(self):
988
988
989 if '_tagscache' in vars(self):
989 if '_tagscache' in vars(self):
990 # can't use delattr on proxy
990 # can't use delattr on proxy
991 del self.__dict__['_tagscache']
991 del self.__dict__['_tagscache']
992
992
993 self.unfiltered()._branchcaches.clear()
993 self.unfiltered()._branchcaches.clear()
994 self.invalidatevolatilesets()
994 self.invalidatevolatilesets()
995
995
996 def invalidatevolatilesets(self):
996 def invalidatevolatilesets(self):
997 self.filteredrevcache.clear()
997 self.filteredrevcache.clear()
998 obsolete.clearobscaches(self)
998 obsolete.clearobscaches(self)
999
999
1000 def invalidatedirstate(self):
1000 def invalidatedirstate(self):
1001 '''Invalidates the dirstate, causing the next call to dirstate
1001 '''Invalidates the dirstate, causing the next call to dirstate
1002 to check if it was modified since the last time it was read,
1002 to check if it was modified since the last time it was read,
1003 rereading it if it has.
1003 rereading it if it has.
1004
1004
1005 This is different to dirstate.invalidate() that it doesn't always
1005 This is different to dirstate.invalidate() that it doesn't always
1006 rereads the dirstate. Use dirstate.invalidate() if you want to
1006 rereads the dirstate. Use dirstate.invalidate() if you want to
1007 explicitly read the dirstate again (i.e. restoring it to a previous
1007 explicitly read the dirstate again (i.e. restoring it to a previous
1008 known good state).'''
1008 known good state).'''
1009 if hasunfilteredcache(self, 'dirstate'):
1009 if hasunfilteredcache(self, 'dirstate'):
1010 for k in self.dirstate._filecache:
1010 for k in self.dirstate._filecache:
1011 try:
1011 try:
1012 delattr(self.dirstate, k)
1012 delattr(self.dirstate, k)
1013 except AttributeError:
1013 except AttributeError:
1014 pass
1014 pass
1015 delattr(self.unfiltered(), 'dirstate')
1015 delattr(self.unfiltered(), 'dirstate')
1016
1016
1017 def invalidate(self):
1017 def invalidate(self):
1018 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1018 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1019 for k in self._filecache:
1019 for k in self._filecache:
1020 # dirstate is invalidated separately in invalidatedirstate()
1020 # dirstate is invalidated separately in invalidatedirstate()
1021 if k == 'dirstate':
1021 if k == 'dirstate':
1022 continue
1022 continue
1023
1023
1024 try:
1024 try:
1025 delattr(unfiltered, k)
1025 delattr(unfiltered, k)
1026 except AttributeError:
1026 except AttributeError:
1027 pass
1027 pass
1028 self.invalidatecaches()
1028 self.invalidatecaches()
1029 self.store.invalidatecaches()
1029 self.store.invalidatecaches()
1030
1030
1031 def invalidateall(self):
1031 def invalidateall(self):
1032 '''Fully invalidates both store and non-store parts, causing the
1032 '''Fully invalidates both store and non-store parts, causing the
1033 subsequent operation to reread any outside changes.'''
1033 subsequent operation to reread any outside changes.'''
1034 # extension should hook this to invalidate its caches
1034 # extension should hook this to invalidate its caches
1035 self.invalidate()
1035 self.invalidate()
1036 self.invalidatedirstate()
1036 self.invalidatedirstate()
1037
1037
1038 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1038 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1039 try:
1039 try:
1040 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1040 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1041 except error.LockHeld, inst:
1041 except error.LockHeld, inst:
1042 if not wait:
1042 if not wait:
1043 raise
1043 raise
1044 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1044 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1045 (desc, inst.locker))
1045 (desc, inst.locker))
1046 # default to 600 seconds timeout
1046 # default to 600 seconds timeout
1047 l = lockmod.lock(vfs, lockname,
1047 l = lockmod.lock(vfs, lockname,
1048 int(self.ui.config("ui", "timeout", "600")),
1048 int(self.ui.config("ui", "timeout", "600")),
1049 releasefn, desc=desc)
1049 releasefn, desc=desc)
1050 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1050 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1051 if acquirefn:
1051 if acquirefn:
1052 acquirefn()
1052 acquirefn()
1053 return l
1053 return l
1054
1054
1055 def _afterlock(self, callback):
1055 def _afterlock(self, callback):
1056 """add a callback to the current repository lock.
1056 """add a callback to the current repository lock.
1057
1057
1058 The callback will be executed on lock release."""
1058 The callback will be executed on lock release."""
1059 l = self._lockref and self._lockref()
1059 l = self._lockref and self._lockref()
1060 if l:
1060 if l:
1061 l.postrelease.append(callback)
1061 l.postrelease.append(callback)
1062 else:
1062 else:
1063 callback()
1063 callback()
1064
1064
1065 def lock(self, wait=True):
1065 def lock(self, wait=True):
1066 '''Lock the repository store (.hg/store) and return a weak reference
1066 '''Lock the repository store (.hg/store) and return a weak reference
1067 to the lock. Use this before modifying the store (e.g. committing or
1067 to the lock. Use this before modifying the store (e.g. committing or
1068 stripping). If you are opening a transaction, get a lock as well.)'''
1068 stripping). If you are opening a transaction, get a lock as well.)'''
1069 l = self._lockref and self._lockref()
1069 l = self._lockref and self._lockref()
1070 if l is not None and l.held:
1070 if l is not None and l.held:
1071 l.lock()
1071 l.lock()
1072 return l
1072 return l
1073
1073
1074 def unlock():
1074 def unlock():
1075 if hasunfilteredcache(self, '_phasecache'):
1075 if hasunfilteredcache(self, '_phasecache'):
1076 self._phasecache.write()
1076 self._phasecache.write()
1077 for k, ce in self._filecache.items():
1077 for k, ce in self._filecache.items():
1078 if k == 'dirstate' or k not in self.__dict__:
1078 if k == 'dirstate' or k not in self.__dict__:
1079 continue
1079 continue
1080 ce.refresh()
1080 ce.refresh()
1081
1081
1082 l = self._lock(self.svfs, "lock", wait, unlock,
1082 l = self._lock(self.svfs, "lock", wait, unlock,
1083 self.invalidate, _('repository %s') % self.origroot)
1083 self.invalidate, _('repository %s') % self.origroot)
1084 self._lockref = weakref.ref(l)
1084 self._lockref = weakref.ref(l)
1085 return l
1085 return l
1086
1086
1087 def wlock(self, wait=True):
1087 def wlock(self, wait=True):
1088 '''Lock the non-store parts of the repository (everything under
1088 '''Lock the non-store parts of the repository (everything under
1089 .hg except .hg/store) and return a weak reference to the lock.
1089 .hg except .hg/store) and return a weak reference to the lock.
1090 Use this before modifying files in .hg.'''
1090 Use this before modifying files in .hg.'''
1091 l = self._wlockref and self._wlockref()
1091 l = self._wlockref and self._wlockref()
1092 if l is not None and l.held:
1092 if l is not None and l.held:
1093 l.lock()
1093 l.lock()
1094 return l
1094 return l
1095
1095
1096 def unlock():
1096 def unlock():
1097 self.dirstate.write()
1097 self.dirstate.write()
1098 self._filecache['dirstate'].refresh()
1098 self._filecache['dirstate'].refresh()
1099
1099
1100 l = self._lock(self.vfs, "wlock", wait, unlock,
1100 l = self._lock(self.vfs, "wlock", wait, unlock,
1101 self.invalidatedirstate, _('working directory of %s') %
1101 self.invalidatedirstate, _('working directory of %s') %
1102 self.origroot)
1102 self.origroot)
1103 self._wlockref = weakref.ref(l)
1103 self._wlockref = weakref.ref(l)
1104 return l
1104 return l
1105
1105
1106 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1106 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1107 """
1107 """
1108 commit an individual file as part of a larger transaction
1108 commit an individual file as part of a larger transaction
1109 """
1109 """
1110
1110
1111 fname = fctx.path()
1111 fname = fctx.path()
1112 text = fctx.data()
1112 text = fctx.data()
1113 flog = self.file(fname)
1113 flog = self.file(fname)
1114 fparent1 = manifest1.get(fname, nullid)
1114 fparent1 = manifest1.get(fname, nullid)
1115 fparent2 = fparent2o = manifest2.get(fname, nullid)
1115 fparent2 = fparent2o = manifest2.get(fname, nullid)
1116
1116
1117 meta = {}
1117 meta = {}
1118 copy = fctx.renamed()
1118 copy = fctx.renamed()
1119 if copy and copy[0] != fname:
1119 if copy and copy[0] != fname:
1120 # Mark the new revision of this file as a copy of another
1120 # Mark the new revision of this file as a copy of another
1121 # file. This copy data will effectively act as a parent
1121 # file. This copy data will effectively act as a parent
1122 # of this new revision. If this is a merge, the first
1122 # of this new revision. If this is a merge, the first
1123 # parent will be the nullid (meaning "look up the copy data")
1123 # parent will be the nullid (meaning "look up the copy data")
1124 # and the second one will be the other parent. For example:
1124 # and the second one will be the other parent. For example:
1125 #
1125 #
1126 # 0 --- 1 --- 3 rev1 changes file foo
1126 # 0 --- 1 --- 3 rev1 changes file foo
1127 # \ / rev2 renames foo to bar and changes it
1127 # \ / rev2 renames foo to bar and changes it
1128 # \- 2 -/ rev3 should have bar with all changes and
1128 # \- 2 -/ rev3 should have bar with all changes and
1129 # should record that bar descends from
1129 # should record that bar descends from
1130 # bar in rev2 and foo in rev1
1130 # bar in rev2 and foo in rev1
1131 #
1131 #
1132 # this allows this merge to succeed:
1132 # this allows this merge to succeed:
1133 #
1133 #
1134 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1134 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1135 # \ / merging rev3 and rev4 should use bar@rev2
1135 # \ / merging rev3 and rev4 should use bar@rev2
1136 # \- 2 --- 4 as the merge base
1136 # \- 2 --- 4 as the merge base
1137 #
1137 #
1138
1138
1139 cfname = copy[0]
1139 cfname = copy[0]
1140 crev = manifest1.get(cfname)
1140 crev = manifest1.get(cfname)
1141 newfparent = fparent2
1141 newfparent = fparent2
1142
1142
1143 if manifest2: # branch merge
1143 if manifest2: # branch merge
1144 if fparent2 == nullid or crev is None: # copied on remote side
1144 if fparent2 == nullid or crev is None: # copied on remote side
1145 if cfname in manifest2:
1145 if cfname in manifest2:
1146 crev = manifest2[cfname]
1146 crev = manifest2[cfname]
1147 newfparent = fparent1
1147 newfparent = fparent1
1148
1148
1149 # find source in nearest ancestor if we've lost track
1149 # find source in nearest ancestor if we've lost track
1150 if not crev:
1150 if not crev:
1151 self.ui.debug(" %s: searching for copy revision for %s\n" %
1151 self.ui.debug(" %s: searching for copy revision for %s\n" %
1152 (fname, cfname))
1152 (fname, cfname))
1153 for ancestor in self[None].ancestors():
1153 for ancestor in self[None].ancestors():
1154 if cfname in ancestor:
1154 if cfname in ancestor:
1155 crev = ancestor[cfname].filenode()
1155 crev = ancestor[cfname].filenode()
1156 break
1156 break
1157
1157
1158 if crev:
1158 if crev:
1159 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1159 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1160 meta["copy"] = cfname
1160 meta["copy"] = cfname
1161 meta["copyrev"] = hex(crev)
1161 meta["copyrev"] = hex(crev)
1162 fparent1, fparent2 = nullid, newfparent
1162 fparent1, fparent2 = nullid, newfparent
1163 else:
1163 else:
1164 self.ui.warn(_("warning: can't find ancestor for '%s' "
1164 self.ui.warn(_("warning: can't find ancestor for '%s' "
1165 "copied from '%s'!\n") % (fname, cfname))
1165 "copied from '%s'!\n") % (fname, cfname))
1166
1166
1167 elif fparent1 == nullid:
1167 elif fparent1 == nullid:
1168 fparent1, fparent2 = fparent2, nullid
1168 fparent1, fparent2 = fparent2, nullid
1169 elif fparent2 != nullid:
1169 elif fparent2 != nullid:
1170 # is one parent an ancestor of the other?
1170 # is one parent an ancestor of the other?
1171 fparentancestors = flog.commonancestors(fparent1, fparent2)
1171 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1172 if fparent1 in fparentancestors:
1172 if fparent1 in fparentancestors:
1173 fparent1, fparent2 = fparent2, nullid
1173 fparent1, fparent2 = fparent2, nullid
1174 elif fparent2 in fparentancestors:
1174 elif fparent2 in fparentancestors:
1175 fparent2 = nullid
1175 fparent2 = nullid
1176
1176
1177 # is the file changed?
1177 # is the file changed?
1178 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1178 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1179 changelist.append(fname)
1179 changelist.append(fname)
1180 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1180 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1181
1181
1182 # are just the flags changed during merge?
1182 # are just the flags changed during merge?
1183 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1183 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1184 changelist.append(fname)
1184 changelist.append(fname)
1185
1185
1186 return fparent1
1186 return fparent1
1187
1187
1188 @unfilteredmethod
1188 @unfilteredmethod
1189 def commit(self, text="", user=None, date=None, match=None, force=False,
1189 def commit(self, text="", user=None, date=None, match=None, force=False,
1190 editor=False, extra={}):
1190 editor=False, extra={}):
1191 """Add a new revision to current repository.
1191 """Add a new revision to current repository.
1192
1192
1193 Revision information is gathered from the working directory,
1193 Revision information is gathered from the working directory,
1194 match can be used to filter the committed files. If editor is
1194 match can be used to filter the committed files. If editor is
1195 supplied, it is called to get a commit message.
1195 supplied, it is called to get a commit message.
1196 """
1196 """
1197
1197
1198 def fail(f, msg):
1198 def fail(f, msg):
1199 raise util.Abort('%s: %s' % (f, msg))
1199 raise util.Abort('%s: %s' % (f, msg))
1200
1200
1201 if not match:
1201 if not match:
1202 match = matchmod.always(self.root, '')
1202 match = matchmod.always(self.root, '')
1203
1203
1204 if not force:
1204 if not force:
1205 vdirs = []
1205 vdirs = []
1206 match.explicitdir = vdirs.append
1206 match.explicitdir = vdirs.append
1207 match.bad = fail
1207 match.bad = fail
1208
1208
1209 wlock = self.wlock()
1209 wlock = self.wlock()
1210 try:
1210 try:
1211 wctx = self[None]
1211 wctx = self[None]
1212 merge = len(wctx.parents()) > 1
1212 merge = len(wctx.parents()) > 1
1213
1213
1214 if (not force and merge and match and
1214 if (not force and merge and match and
1215 (match.files() or match.anypats())):
1215 (match.files() or match.anypats())):
1216 raise util.Abort(_('cannot partially commit a merge '
1216 raise util.Abort(_('cannot partially commit a merge '
1217 '(do not specify files or patterns)'))
1217 '(do not specify files or patterns)'))
1218
1218
1219 changes = self.status(match=match, clean=force)
1219 changes = self.status(match=match, clean=force)
1220 if force:
1220 if force:
1221 changes[0].extend(changes[6]) # mq may commit unchanged files
1221 changes[0].extend(changes[6]) # mq may commit unchanged files
1222
1222
1223 # check subrepos
1223 # check subrepos
1224 subs = []
1224 subs = []
1225 commitsubs = set()
1225 commitsubs = set()
1226 newstate = wctx.substate.copy()
1226 newstate = wctx.substate.copy()
1227 # only manage subrepos and .hgsubstate if .hgsub is present
1227 # only manage subrepos and .hgsubstate if .hgsub is present
1228 if '.hgsub' in wctx:
1228 if '.hgsub' in wctx:
1229 # we'll decide whether to track this ourselves, thanks
1229 # we'll decide whether to track this ourselves, thanks
1230 for c in changes[:3]:
1230 for c in changes[:3]:
1231 if '.hgsubstate' in c:
1231 if '.hgsubstate' in c:
1232 c.remove('.hgsubstate')
1232 c.remove('.hgsubstate')
1233
1233
1234 # compare current state to last committed state
1234 # compare current state to last committed state
1235 # build new substate based on last committed state
1235 # build new substate based on last committed state
1236 oldstate = wctx.p1().substate
1236 oldstate = wctx.p1().substate
1237 for s in sorted(newstate.keys()):
1237 for s in sorted(newstate.keys()):
1238 if not match(s):
1238 if not match(s):
1239 # ignore working copy, use old state if present
1239 # ignore working copy, use old state if present
1240 if s in oldstate:
1240 if s in oldstate:
1241 newstate[s] = oldstate[s]
1241 newstate[s] = oldstate[s]
1242 continue
1242 continue
1243 if not force:
1243 if not force:
1244 raise util.Abort(
1244 raise util.Abort(
1245 _("commit with new subrepo %s excluded") % s)
1245 _("commit with new subrepo %s excluded") % s)
1246 if wctx.sub(s).dirty(True):
1246 if wctx.sub(s).dirty(True):
1247 if not self.ui.configbool('ui', 'commitsubrepos'):
1247 if not self.ui.configbool('ui', 'commitsubrepos'):
1248 raise util.Abort(
1248 raise util.Abort(
1249 _("uncommitted changes in subrepo %s") % s,
1249 _("uncommitted changes in subrepo %s") % s,
1250 hint=_("use --subrepos for recursive commit"))
1250 hint=_("use --subrepos for recursive commit"))
1251 subs.append(s)
1251 subs.append(s)
1252 commitsubs.add(s)
1252 commitsubs.add(s)
1253 else:
1253 else:
1254 bs = wctx.sub(s).basestate()
1254 bs = wctx.sub(s).basestate()
1255 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1255 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1256 if oldstate.get(s, (None, None, None))[1] != bs:
1256 if oldstate.get(s, (None, None, None))[1] != bs:
1257 subs.append(s)
1257 subs.append(s)
1258
1258
1259 # check for removed subrepos
1259 # check for removed subrepos
1260 for p in wctx.parents():
1260 for p in wctx.parents():
1261 r = [s for s in p.substate if s not in newstate]
1261 r = [s for s in p.substate if s not in newstate]
1262 subs += [s for s in r if match(s)]
1262 subs += [s for s in r if match(s)]
1263 if subs:
1263 if subs:
1264 if (not match('.hgsub') and
1264 if (not match('.hgsub') and
1265 '.hgsub' in (wctx.modified() + wctx.added())):
1265 '.hgsub' in (wctx.modified() + wctx.added())):
1266 raise util.Abort(
1266 raise util.Abort(
1267 _("can't commit subrepos without .hgsub"))
1267 _("can't commit subrepos without .hgsub"))
1268 changes[0].insert(0, '.hgsubstate')
1268 changes[0].insert(0, '.hgsubstate')
1269
1269
1270 elif '.hgsub' in changes[2]:
1270 elif '.hgsub' in changes[2]:
1271 # clean up .hgsubstate when .hgsub is removed
1271 # clean up .hgsubstate when .hgsub is removed
1272 if ('.hgsubstate' in wctx and
1272 if ('.hgsubstate' in wctx and
1273 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1273 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1274 changes[2].insert(0, '.hgsubstate')
1274 changes[2].insert(0, '.hgsubstate')
1275
1275
1276 # make sure all explicit patterns are matched
1276 # make sure all explicit patterns are matched
1277 if not force and match.files():
1277 if not force and match.files():
1278 matched = set(changes[0] + changes[1] + changes[2])
1278 matched = set(changes[0] + changes[1] + changes[2])
1279
1279
1280 for f in match.files():
1280 for f in match.files():
1281 f = self.dirstate.normalize(f)
1281 f = self.dirstate.normalize(f)
1282 if f == '.' or f in matched or f in wctx.substate:
1282 if f == '.' or f in matched or f in wctx.substate:
1283 continue
1283 continue
1284 if f in changes[3]: # missing
1284 if f in changes[3]: # missing
1285 fail(f, _('file not found!'))
1285 fail(f, _('file not found!'))
1286 if f in vdirs: # visited directory
1286 if f in vdirs: # visited directory
1287 d = f + '/'
1287 d = f + '/'
1288 for mf in matched:
1288 for mf in matched:
1289 if mf.startswith(d):
1289 if mf.startswith(d):
1290 break
1290 break
1291 else:
1291 else:
1292 fail(f, _("no match under directory!"))
1292 fail(f, _("no match under directory!"))
1293 elif f not in self.dirstate:
1293 elif f not in self.dirstate:
1294 fail(f, _("file not tracked!"))
1294 fail(f, _("file not tracked!"))
1295
1295
1296 cctx = context.workingctx(self, text, user, date, extra, changes)
1296 cctx = context.workingctx(self, text, user, date, extra, changes)
1297
1297
1298 if (not force and not extra.get("close") and not merge
1298 if (not force and not extra.get("close") and not merge
1299 and not cctx.files()
1299 and not cctx.files()
1300 and wctx.branch() == wctx.p1().branch()):
1300 and wctx.branch() == wctx.p1().branch()):
1301 return None
1301 return None
1302
1302
1303 if merge and cctx.deleted():
1303 if merge and cctx.deleted():
1304 raise util.Abort(_("cannot commit merge with missing files"))
1304 raise util.Abort(_("cannot commit merge with missing files"))
1305
1305
1306 ms = mergemod.mergestate(self)
1306 ms = mergemod.mergestate(self)
1307 for f in changes[0]:
1307 for f in changes[0]:
1308 if f in ms and ms[f] == 'u':
1308 if f in ms and ms[f] == 'u':
1309 raise util.Abort(_("unresolved merge conflicts "
1309 raise util.Abort(_("unresolved merge conflicts "
1310 "(see hg help resolve)"))
1310 "(see hg help resolve)"))
1311
1311
1312 if editor:
1312 if editor:
1313 cctx._text = editor(self, cctx, subs)
1313 cctx._text = editor(self, cctx, subs)
1314 edited = (text != cctx._text)
1314 edited = (text != cctx._text)
1315
1315
1316 # Save commit message in case this transaction gets rolled back
1316 # Save commit message in case this transaction gets rolled back
1317 # (e.g. by a pretxncommit hook). Leave the content alone on
1317 # (e.g. by a pretxncommit hook). Leave the content alone on
1318 # the assumption that the user will use the same editor again.
1318 # the assumption that the user will use the same editor again.
1319 msgfn = self.savecommitmessage(cctx._text)
1319 msgfn = self.savecommitmessage(cctx._text)
1320
1320
1321 # commit subs and write new state
1321 # commit subs and write new state
1322 if subs:
1322 if subs:
1323 for s in sorted(commitsubs):
1323 for s in sorted(commitsubs):
1324 sub = wctx.sub(s)
1324 sub = wctx.sub(s)
1325 self.ui.status(_('committing subrepository %s\n') %
1325 self.ui.status(_('committing subrepository %s\n') %
1326 subrepo.subrelpath(sub))
1326 subrepo.subrelpath(sub))
1327 sr = sub.commit(cctx._text, user, date)
1327 sr = sub.commit(cctx._text, user, date)
1328 newstate[s] = (newstate[s][0], sr)
1328 newstate[s] = (newstate[s][0], sr)
1329 subrepo.writestate(self, newstate)
1329 subrepo.writestate(self, newstate)
1330
1330
1331 p1, p2 = self.dirstate.parents()
1331 p1, p2 = self.dirstate.parents()
1332 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1332 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1333 try:
1333 try:
1334 self.hook("precommit", throw=True, parent1=hookp1,
1334 self.hook("precommit", throw=True, parent1=hookp1,
1335 parent2=hookp2)
1335 parent2=hookp2)
1336 ret = self.commitctx(cctx, True)
1336 ret = self.commitctx(cctx, True)
1337 except: # re-raises
1337 except: # re-raises
1338 if edited:
1338 if edited:
1339 self.ui.write(
1339 self.ui.write(
1340 _('note: commit message saved in %s\n') % msgfn)
1340 _('note: commit message saved in %s\n') % msgfn)
1341 raise
1341 raise
1342
1342
1343 # update bookmarks, dirstate and mergestate
1343 # update bookmarks, dirstate and mergestate
1344 bookmarks.update(self, [p1, p2], ret)
1344 bookmarks.update(self, [p1, p2], ret)
1345 cctx.markcommitted(ret)
1345 cctx.markcommitted(ret)
1346 ms.reset()
1346 ms.reset()
1347 finally:
1347 finally:
1348 wlock.release()
1348 wlock.release()
1349
1349
1350 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1350 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1351 self.hook("commit", node=node, parent1=parent1, parent2=parent2)
1351 self.hook("commit", node=node, parent1=parent1, parent2=parent2)
1352 self._afterlock(commithook)
1352 self._afterlock(commithook)
1353 return ret
1353 return ret
1354
1354
1355 @unfilteredmethod
1355 @unfilteredmethod
1356 def commitctx(self, ctx, error=False):
1356 def commitctx(self, ctx, error=False):
1357 """Add a new revision to current repository.
1357 """Add a new revision to current repository.
1358 Revision information is passed via the context argument.
1358 Revision information is passed via the context argument.
1359 """
1359 """
1360
1360
1361 tr = lock = None
1361 tr = lock = None
1362 removed = list(ctx.removed())
1362 removed = list(ctx.removed())
1363 p1, p2 = ctx.p1(), ctx.p2()
1363 p1, p2 = ctx.p1(), ctx.p2()
1364 user = ctx.user()
1364 user = ctx.user()
1365
1365
1366 lock = self.lock()
1366 lock = self.lock()
1367 try:
1367 try:
1368 tr = self.transaction("commit")
1368 tr = self.transaction("commit")
1369 trp = weakref.proxy(tr)
1369 trp = weakref.proxy(tr)
1370
1370
1371 if ctx.files():
1371 if ctx.files():
1372 m1 = p1.manifest().copy()
1372 m1 = p1.manifest().copy()
1373 m2 = p2.manifest()
1373 m2 = p2.manifest()
1374
1374
1375 # check in files
1375 # check in files
1376 new = {}
1376 new = {}
1377 changed = []
1377 changed = []
1378 linkrev = len(self)
1378 linkrev = len(self)
1379 for f in sorted(ctx.modified() + ctx.added()):
1379 for f in sorted(ctx.modified() + ctx.added()):
1380 self.ui.note(f + "\n")
1380 self.ui.note(f + "\n")
1381 try:
1381 try:
1382 fctx = ctx[f]
1382 fctx = ctx[f]
1383 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1383 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1384 changed)
1384 changed)
1385 m1.set(f, fctx.flags())
1385 m1.set(f, fctx.flags())
1386 except OSError, inst:
1386 except OSError, inst:
1387 self.ui.warn(_("trouble committing %s!\n") % f)
1387 self.ui.warn(_("trouble committing %s!\n") % f)
1388 raise
1388 raise
1389 except IOError, inst:
1389 except IOError, inst:
1390 errcode = getattr(inst, 'errno', errno.ENOENT)
1390 errcode = getattr(inst, 'errno', errno.ENOENT)
1391 if error or errcode and errcode != errno.ENOENT:
1391 if error or errcode and errcode != errno.ENOENT:
1392 self.ui.warn(_("trouble committing %s!\n") % f)
1392 self.ui.warn(_("trouble committing %s!\n") % f)
1393 raise
1393 raise
1394 else:
1394 else:
1395 removed.append(f)
1395 removed.append(f)
1396
1396
1397 # update manifest
1397 # update manifest
1398 m1.update(new)
1398 m1.update(new)
1399 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1399 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1400 drop = [f for f in removed if f in m1]
1400 drop = [f for f in removed if f in m1]
1401 for f in drop:
1401 for f in drop:
1402 del m1[f]
1402 del m1[f]
1403 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1403 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1404 p2.manifestnode(), (new, drop))
1404 p2.manifestnode(), (new, drop))
1405 files = changed + removed
1405 files = changed + removed
1406 else:
1406 else:
1407 mn = p1.manifestnode()
1407 mn = p1.manifestnode()
1408 files = []
1408 files = []
1409
1409
1410 # update changelog
1410 # update changelog
1411 self.changelog.delayupdate()
1411 self.changelog.delayupdate()
1412 n = self.changelog.add(mn, files, ctx.description(),
1412 n = self.changelog.add(mn, files, ctx.description(),
1413 trp, p1.node(), p2.node(),
1413 trp, p1.node(), p2.node(),
1414 user, ctx.date(), ctx.extra().copy())
1414 user, ctx.date(), ctx.extra().copy())
1415 p = lambda: self.changelog.writepending() and self.root or ""
1415 p = lambda: self.changelog.writepending() and self.root or ""
1416 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1416 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1417 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1417 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1418 parent2=xp2, pending=p)
1418 parent2=xp2, pending=p)
1419 self.changelog.finalize(trp)
1419 self.changelog.finalize(trp)
1420 # set the new commit is proper phase
1420 # set the new commit is proper phase
1421 targetphase = subrepo.newcommitphase(self.ui, ctx)
1421 targetphase = subrepo.newcommitphase(self.ui, ctx)
1422 if targetphase:
1422 if targetphase:
1423 # retract boundary do not alter parent changeset.
1423 # retract boundary do not alter parent changeset.
1424 # if a parent have higher the resulting phase will
1424 # if a parent have higher the resulting phase will
1425 # be compliant anyway
1425 # be compliant anyway
1426 #
1426 #
1427 # if minimal phase was 0 we don't need to retract anything
1427 # if minimal phase was 0 we don't need to retract anything
1428 phases.retractboundary(self, targetphase, [n])
1428 phases.retractboundary(self, targetphase, [n])
1429 tr.close()
1429 tr.close()
1430 branchmap.updatecache(self.filtered('served'))
1430 branchmap.updatecache(self.filtered('served'))
1431 return n
1431 return n
1432 finally:
1432 finally:
1433 if tr:
1433 if tr:
1434 tr.release()
1434 tr.release()
1435 lock.release()
1435 lock.release()
1436
1436
1437 @unfilteredmethod
1437 @unfilteredmethod
1438 def destroying(self):
1438 def destroying(self):
1439 '''Inform the repository that nodes are about to be destroyed.
1439 '''Inform the repository that nodes are about to be destroyed.
1440 Intended for use by strip and rollback, so there's a common
1440 Intended for use by strip and rollback, so there's a common
1441 place for anything that has to be done before destroying history.
1441 place for anything that has to be done before destroying history.
1442
1442
1443 This is mostly useful for saving state that is in memory and waiting
1443 This is mostly useful for saving state that is in memory and waiting
1444 to be flushed when the current lock is released. Because a call to
1444 to be flushed when the current lock is released. Because a call to
1445 destroyed is imminent, the repo will be invalidated causing those
1445 destroyed is imminent, the repo will be invalidated causing those
1446 changes to stay in memory (waiting for the next unlock), or vanish
1446 changes to stay in memory (waiting for the next unlock), or vanish
1447 completely.
1447 completely.
1448 '''
1448 '''
1449 # When using the same lock to commit and strip, the phasecache is left
1449 # When using the same lock to commit and strip, the phasecache is left
1450 # dirty after committing. Then when we strip, the repo is invalidated,
1450 # dirty after committing. Then when we strip, the repo is invalidated,
1451 # causing those changes to disappear.
1451 # causing those changes to disappear.
1452 if '_phasecache' in vars(self):
1452 if '_phasecache' in vars(self):
1453 self._phasecache.write()
1453 self._phasecache.write()
1454
1454
1455 @unfilteredmethod
1455 @unfilteredmethod
1456 def destroyed(self):
1456 def destroyed(self):
1457 '''Inform the repository that nodes have been destroyed.
1457 '''Inform the repository that nodes have been destroyed.
1458 Intended for use by strip and rollback, so there's a common
1458 Intended for use by strip and rollback, so there's a common
1459 place for anything that has to be done after destroying history.
1459 place for anything that has to be done after destroying history.
1460 '''
1460 '''
1461 # When one tries to:
1461 # When one tries to:
1462 # 1) destroy nodes thus calling this method (e.g. strip)
1462 # 1) destroy nodes thus calling this method (e.g. strip)
1463 # 2) use phasecache somewhere (e.g. commit)
1463 # 2) use phasecache somewhere (e.g. commit)
1464 #
1464 #
1465 # then 2) will fail because the phasecache contains nodes that were
1465 # then 2) will fail because the phasecache contains nodes that were
1466 # removed. We can either remove phasecache from the filecache,
1466 # removed. We can either remove phasecache from the filecache,
1467 # causing it to reload next time it is accessed, or simply filter
1467 # causing it to reload next time it is accessed, or simply filter
1468 # the removed nodes now and write the updated cache.
1468 # the removed nodes now and write the updated cache.
1469 self._phasecache.filterunknown(self)
1469 self._phasecache.filterunknown(self)
1470 self._phasecache.write()
1470 self._phasecache.write()
1471
1471
1472 # update the 'served' branch cache to help read only server process
1472 # update the 'served' branch cache to help read only server process
1473 # Thanks to branchcache collaboration this is done from the nearest
1473 # Thanks to branchcache collaboration this is done from the nearest
1474 # filtered subset and it is expected to be fast.
1474 # filtered subset and it is expected to be fast.
1475 branchmap.updatecache(self.filtered('served'))
1475 branchmap.updatecache(self.filtered('served'))
1476
1476
1477 # Ensure the persistent tag cache is updated. Doing it now
1477 # Ensure the persistent tag cache is updated. Doing it now
1478 # means that the tag cache only has to worry about destroyed
1478 # means that the tag cache only has to worry about destroyed
1479 # heads immediately after a strip/rollback. That in turn
1479 # heads immediately after a strip/rollback. That in turn
1480 # guarantees that "cachetip == currenttip" (comparing both rev
1480 # guarantees that "cachetip == currenttip" (comparing both rev
1481 # and node) always means no nodes have been added or destroyed.
1481 # and node) always means no nodes have been added or destroyed.
1482
1482
1483 # XXX this is suboptimal when qrefresh'ing: we strip the current
1483 # XXX this is suboptimal when qrefresh'ing: we strip the current
1484 # head, refresh the tag cache, then immediately add a new head.
1484 # head, refresh the tag cache, then immediately add a new head.
1485 # But I think doing it this way is necessary for the "instant
1485 # But I think doing it this way is necessary for the "instant
1486 # tag cache retrieval" case to work.
1486 # tag cache retrieval" case to work.
1487 self.invalidate()
1487 self.invalidate()
1488
1488
1489 def walk(self, match, node=None):
1489 def walk(self, match, node=None):
1490 '''
1490 '''
1491 walk recursively through the directory tree or a given
1491 walk recursively through the directory tree or a given
1492 changeset, finding all files matched by the match
1492 changeset, finding all files matched by the match
1493 function
1493 function
1494 '''
1494 '''
1495 return self[node].walk(match)
1495 return self[node].walk(match)
1496
1496
1497 def status(self, node1='.', node2=None, match=None,
1497 def status(self, node1='.', node2=None, match=None,
1498 ignored=False, clean=False, unknown=False,
1498 ignored=False, clean=False, unknown=False,
1499 listsubrepos=False):
1499 listsubrepos=False):
1500 """return status of files between two nodes or node and working
1500 """return status of files between two nodes or node and working
1501 directory.
1501 directory.
1502
1502
1503 If node1 is None, use the first dirstate parent instead.
1503 If node1 is None, use the first dirstate parent instead.
1504 If node2 is None, compare node1 with working directory.
1504 If node2 is None, compare node1 with working directory.
1505 """
1505 """
1506
1506
1507 def mfmatches(ctx):
1507 def mfmatches(ctx):
1508 mf = ctx.manifest().copy()
1508 mf = ctx.manifest().copy()
1509 if match.always():
1509 if match.always():
1510 return mf
1510 return mf
1511 for fn in mf.keys():
1511 for fn in mf.keys():
1512 if not match(fn):
1512 if not match(fn):
1513 del mf[fn]
1513 del mf[fn]
1514 return mf
1514 return mf
1515
1515
1516 ctx1 = self[node1]
1516 ctx1 = self[node1]
1517 ctx2 = self[node2]
1517 ctx2 = self[node2]
1518
1518
1519 working = ctx2.rev() is None
1519 working = ctx2.rev() is None
1520 parentworking = working and ctx1 == self['.']
1520 parentworking = working and ctx1 == self['.']
1521 match = match or matchmod.always(self.root, self.getcwd())
1521 match = match or matchmod.always(self.root, self.getcwd())
1522 listignored, listclean, listunknown = ignored, clean, unknown
1522 listignored, listclean, listunknown = ignored, clean, unknown
1523
1523
1524 # load earliest manifest first for caching reasons
1524 # load earliest manifest first for caching reasons
1525 if not working and ctx2.rev() < ctx1.rev():
1525 if not working and ctx2.rev() < ctx1.rev():
1526 ctx2.manifest()
1526 ctx2.manifest()
1527
1527
1528 if not parentworking:
1528 if not parentworking:
1529 def bad(f, msg):
1529 def bad(f, msg):
1530 # 'f' may be a directory pattern from 'match.files()',
1530 # 'f' may be a directory pattern from 'match.files()',
1531 # so 'f not in ctx1' is not enough
1531 # so 'f not in ctx1' is not enough
1532 if f not in ctx1 and f not in ctx1.dirs():
1532 if f not in ctx1 and f not in ctx1.dirs():
1533 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1533 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1534 match.bad = bad
1534 match.bad = bad
1535
1535
1536 if working: # we need to scan the working dir
1536 if working: # we need to scan the working dir
1537 subrepos = []
1537 subrepos = []
1538 if '.hgsub' in self.dirstate:
1538 if '.hgsub' in self.dirstate:
1539 subrepos = sorted(ctx2.substate)
1539 subrepos = sorted(ctx2.substate)
1540 s = self.dirstate.status(match, subrepos, listignored,
1540 s = self.dirstate.status(match, subrepos, listignored,
1541 listclean, listunknown)
1541 listclean, listunknown)
1542 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1542 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1543
1543
1544 # check for any possibly clean files
1544 # check for any possibly clean files
1545 if parentworking and cmp:
1545 if parentworking and cmp:
1546 fixup = []
1546 fixup = []
1547 # do a full compare of any files that might have changed
1547 # do a full compare of any files that might have changed
1548 for f in sorted(cmp):
1548 for f in sorted(cmp):
1549 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1549 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1550 or ctx1[f].cmp(ctx2[f])):
1550 or ctx1[f].cmp(ctx2[f])):
1551 modified.append(f)
1551 modified.append(f)
1552 else:
1552 else:
1553 fixup.append(f)
1553 fixup.append(f)
1554
1554
1555 # update dirstate for files that are actually clean
1555 # update dirstate for files that are actually clean
1556 if fixup:
1556 if fixup:
1557 if listclean:
1557 if listclean:
1558 clean += fixup
1558 clean += fixup
1559
1559
1560 try:
1560 try:
1561 # updating the dirstate is optional
1561 # updating the dirstate is optional
1562 # so we don't wait on the lock
1562 # so we don't wait on the lock
1563 wlock = self.wlock(False)
1563 wlock = self.wlock(False)
1564 try:
1564 try:
1565 for f in fixup:
1565 for f in fixup:
1566 self.dirstate.normal(f)
1566 self.dirstate.normal(f)
1567 finally:
1567 finally:
1568 wlock.release()
1568 wlock.release()
1569 except error.LockError:
1569 except error.LockError:
1570 pass
1570 pass
1571
1571
1572 if not parentworking:
1572 if not parentworking:
1573 mf1 = mfmatches(ctx1)
1573 mf1 = mfmatches(ctx1)
1574 if working:
1574 if working:
1575 # we are comparing working dir against non-parent
1575 # we are comparing working dir against non-parent
1576 # generate a pseudo-manifest for the working dir
1576 # generate a pseudo-manifest for the working dir
1577 mf2 = mfmatches(self['.'])
1577 mf2 = mfmatches(self['.'])
1578 for f in cmp + modified + added:
1578 for f in cmp + modified + added:
1579 mf2[f] = None
1579 mf2[f] = None
1580 mf2.set(f, ctx2.flags(f))
1580 mf2.set(f, ctx2.flags(f))
1581 for f in removed:
1581 for f in removed:
1582 if f in mf2:
1582 if f in mf2:
1583 del mf2[f]
1583 del mf2[f]
1584 else:
1584 else:
1585 # we are comparing two revisions
1585 # we are comparing two revisions
1586 deleted, unknown, ignored = [], [], []
1586 deleted, unknown, ignored = [], [], []
1587 mf2 = mfmatches(ctx2)
1587 mf2 = mfmatches(ctx2)
1588
1588
1589 modified, added, clean = [], [], []
1589 modified, added, clean = [], [], []
1590 withflags = mf1.withflags() | mf2.withflags()
1590 withflags = mf1.withflags() | mf2.withflags()
1591 for fn, mf2node in mf2.iteritems():
1591 for fn, mf2node in mf2.iteritems():
1592 if fn in mf1:
1592 if fn in mf1:
1593 if (fn not in deleted and
1593 if (fn not in deleted and
1594 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
1594 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
1595 (mf1[fn] != mf2node and
1595 (mf1[fn] != mf2node and
1596 (mf2node or ctx1[fn].cmp(ctx2[fn]))))):
1596 (mf2node or ctx1[fn].cmp(ctx2[fn]))))):
1597 modified.append(fn)
1597 modified.append(fn)
1598 elif listclean:
1598 elif listclean:
1599 clean.append(fn)
1599 clean.append(fn)
1600 del mf1[fn]
1600 del mf1[fn]
1601 elif fn not in deleted:
1601 elif fn not in deleted:
1602 added.append(fn)
1602 added.append(fn)
1603 removed = mf1.keys()
1603 removed = mf1.keys()
1604
1604
1605 if working and modified and not self.dirstate._checklink:
1605 if working and modified and not self.dirstate._checklink:
1606 # Symlink placeholders may get non-symlink-like contents
1606 # Symlink placeholders may get non-symlink-like contents
1607 # via user error or dereferencing by NFS or Samba servers,
1607 # via user error or dereferencing by NFS or Samba servers,
1608 # so we filter out any placeholders that don't look like a
1608 # so we filter out any placeholders that don't look like a
1609 # symlink
1609 # symlink
1610 sane = []
1610 sane = []
1611 for f in modified:
1611 for f in modified:
1612 if ctx2.flags(f) == 'l':
1612 if ctx2.flags(f) == 'l':
1613 d = ctx2[f].data()
1613 d = ctx2[f].data()
1614 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1614 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1615 self.ui.debug('ignoring suspect symlink placeholder'
1615 self.ui.debug('ignoring suspect symlink placeholder'
1616 ' "%s"\n' % f)
1616 ' "%s"\n' % f)
1617 continue
1617 continue
1618 sane.append(f)
1618 sane.append(f)
1619 modified = sane
1619 modified = sane
1620
1620
1621 r = modified, added, removed, deleted, unknown, ignored, clean
1621 r = modified, added, removed, deleted, unknown, ignored, clean
1622
1622
1623 if listsubrepos:
1623 if listsubrepos:
1624 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1624 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1625 if working:
1625 if working:
1626 rev2 = None
1626 rev2 = None
1627 else:
1627 else:
1628 rev2 = ctx2.substate[subpath][1]
1628 rev2 = ctx2.substate[subpath][1]
1629 try:
1629 try:
1630 submatch = matchmod.narrowmatcher(subpath, match)
1630 submatch = matchmod.narrowmatcher(subpath, match)
1631 s = sub.status(rev2, match=submatch, ignored=listignored,
1631 s = sub.status(rev2, match=submatch, ignored=listignored,
1632 clean=listclean, unknown=listunknown,
1632 clean=listclean, unknown=listunknown,
1633 listsubrepos=True)
1633 listsubrepos=True)
1634 for rfiles, sfiles in zip(r, s):
1634 for rfiles, sfiles in zip(r, s):
1635 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1635 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1636 except error.LookupError:
1636 except error.LookupError:
1637 self.ui.status(_("skipping missing subrepository: %s\n")
1637 self.ui.status(_("skipping missing subrepository: %s\n")
1638 % subpath)
1638 % subpath)
1639
1639
1640 for l in r:
1640 for l in r:
1641 l.sort()
1641 l.sort()
1642 return r
1642 return r
1643
1643
1644 def heads(self, start=None):
1644 def heads(self, start=None):
1645 heads = self.changelog.heads(start)
1645 heads = self.changelog.heads(start)
1646 # sort the output in rev descending order
1646 # sort the output in rev descending order
1647 return sorted(heads, key=self.changelog.rev, reverse=True)
1647 return sorted(heads, key=self.changelog.rev, reverse=True)
1648
1648
1649 def branchheads(self, branch=None, start=None, closed=False):
1649 def branchheads(self, branch=None, start=None, closed=False):
1650 '''return a (possibly filtered) list of heads for the given branch
1650 '''return a (possibly filtered) list of heads for the given branch
1651
1651
1652 Heads are returned in topological order, from newest to oldest.
1652 Heads are returned in topological order, from newest to oldest.
1653 If branch is None, use the dirstate branch.
1653 If branch is None, use the dirstate branch.
1654 If start is not None, return only heads reachable from start.
1654 If start is not None, return only heads reachable from start.
1655 If closed is True, return heads that are marked as closed as well.
1655 If closed is True, return heads that are marked as closed as well.
1656 '''
1656 '''
1657 if branch is None:
1657 if branch is None:
1658 branch = self[None].branch()
1658 branch = self[None].branch()
1659 branches = self.branchmap()
1659 branches = self.branchmap()
1660 if branch not in branches:
1660 if branch not in branches:
1661 return []
1661 return []
1662 # the cache returns heads ordered lowest to highest
1662 # the cache returns heads ordered lowest to highest
1663 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1663 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1664 if start is not None:
1664 if start is not None:
1665 # filter out the heads that cannot be reached from startrev
1665 # filter out the heads that cannot be reached from startrev
1666 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1666 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1667 bheads = [h for h in bheads if h in fbheads]
1667 bheads = [h for h in bheads if h in fbheads]
1668 return bheads
1668 return bheads
1669
1669
1670 def branches(self, nodes):
1670 def branches(self, nodes):
1671 if not nodes:
1671 if not nodes:
1672 nodes = [self.changelog.tip()]
1672 nodes = [self.changelog.tip()]
1673 b = []
1673 b = []
1674 for n in nodes:
1674 for n in nodes:
1675 t = n
1675 t = n
1676 while True:
1676 while True:
1677 p = self.changelog.parents(n)
1677 p = self.changelog.parents(n)
1678 if p[1] != nullid or p[0] == nullid:
1678 if p[1] != nullid or p[0] == nullid:
1679 b.append((t, n, p[0], p[1]))
1679 b.append((t, n, p[0], p[1]))
1680 break
1680 break
1681 n = p[0]
1681 n = p[0]
1682 return b
1682 return b
1683
1683
1684 def between(self, pairs):
1684 def between(self, pairs):
1685 r = []
1685 r = []
1686
1686
1687 for top, bottom in pairs:
1687 for top, bottom in pairs:
1688 n, l, i = top, [], 0
1688 n, l, i = top, [], 0
1689 f = 1
1689 f = 1
1690
1690
1691 while n != bottom and n != nullid:
1691 while n != bottom and n != nullid:
1692 p = self.changelog.parents(n)[0]
1692 p = self.changelog.parents(n)[0]
1693 if i == f:
1693 if i == f:
1694 l.append(n)
1694 l.append(n)
1695 f = f * 2
1695 f = f * 2
1696 n = p
1696 n = p
1697 i += 1
1697 i += 1
1698
1698
1699 r.append(l)
1699 r.append(l)
1700
1700
1701 return r
1701 return r
1702
1702
1703 def pull(self, remote, heads=None, force=False):
1703 def pull(self, remote, heads=None, force=False):
1704 return exchange.pull (self, remote, heads, force)
1704 return exchange.pull (self, remote, heads, force)
1705
1705
1706 def checkpush(self, pushop):
1706 def checkpush(self, pushop):
1707 """Extensions can override this function if additional checks have
1707 """Extensions can override this function if additional checks have
1708 to be performed before pushing, or call it if they override push
1708 to be performed before pushing, or call it if they override push
1709 command.
1709 command.
1710 """
1710 """
1711 pass
1711 pass
1712
1712
1713 @unfilteredpropertycache
1713 @unfilteredpropertycache
1714 def prepushoutgoinghooks(self):
1714 def prepushoutgoinghooks(self):
1715 """Return util.hooks consists of "(repo, remote, outgoing)"
1715 """Return util.hooks consists of "(repo, remote, outgoing)"
1716 functions, which are called before pushing changesets.
1716 functions, which are called before pushing changesets.
1717 """
1717 """
1718 return util.hooks()
1718 return util.hooks()
1719
1719
1720 def push(self, remote, force=False, revs=None, newbranch=False):
1720 def push(self, remote, force=False, revs=None, newbranch=False):
1721 return exchange.push(self, remote, force, revs, newbranch)
1721 return exchange.push(self, remote, force, revs, newbranch)
1722
1722
1723 def stream_in(self, remote, requirements):
1723 def stream_in(self, remote, requirements):
1724 lock = self.lock()
1724 lock = self.lock()
1725 try:
1725 try:
1726 # Save remote branchmap. We will use it later
1726 # Save remote branchmap. We will use it later
1727 # to speed up branchcache creation
1727 # to speed up branchcache creation
1728 rbranchmap = None
1728 rbranchmap = None
1729 if remote.capable("branchmap"):
1729 if remote.capable("branchmap"):
1730 rbranchmap = remote.branchmap()
1730 rbranchmap = remote.branchmap()
1731
1731
1732 fp = remote.stream_out()
1732 fp = remote.stream_out()
1733 l = fp.readline()
1733 l = fp.readline()
1734 try:
1734 try:
1735 resp = int(l)
1735 resp = int(l)
1736 except ValueError:
1736 except ValueError:
1737 raise error.ResponseError(
1737 raise error.ResponseError(
1738 _('unexpected response from remote server:'), l)
1738 _('unexpected response from remote server:'), l)
1739 if resp == 1:
1739 if resp == 1:
1740 raise util.Abort(_('operation forbidden by server'))
1740 raise util.Abort(_('operation forbidden by server'))
1741 elif resp == 2:
1741 elif resp == 2:
1742 raise util.Abort(_('locking the remote repository failed'))
1742 raise util.Abort(_('locking the remote repository failed'))
1743 elif resp != 0:
1743 elif resp != 0:
1744 raise util.Abort(_('the server sent an unknown error code'))
1744 raise util.Abort(_('the server sent an unknown error code'))
1745 self.ui.status(_('streaming all changes\n'))
1745 self.ui.status(_('streaming all changes\n'))
1746 l = fp.readline()
1746 l = fp.readline()
1747 try:
1747 try:
1748 total_files, total_bytes = map(int, l.split(' ', 1))
1748 total_files, total_bytes = map(int, l.split(' ', 1))
1749 except (ValueError, TypeError):
1749 except (ValueError, TypeError):
1750 raise error.ResponseError(
1750 raise error.ResponseError(
1751 _('unexpected response from remote server:'), l)
1751 _('unexpected response from remote server:'), l)
1752 self.ui.status(_('%d files to transfer, %s of data\n') %
1752 self.ui.status(_('%d files to transfer, %s of data\n') %
1753 (total_files, util.bytecount(total_bytes)))
1753 (total_files, util.bytecount(total_bytes)))
1754 handled_bytes = 0
1754 handled_bytes = 0
1755 self.ui.progress(_('clone'), 0, total=total_bytes)
1755 self.ui.progress(_('clone'), 0, total=total_bytes)
1756 start = time.time()
1756 start = time.time()
1757
1757
1758 tr = self.transaction(_('clone'))
1758 tr = self.transaction(_('clone'))
1759 try:
1759 try:
1760 for i in xrange(total_files):
1760 for i in xrange(total_files):
1761 # XXX doesn't support '\n' or '\r' in filenames
1761 # XXX doesn't support '\n' or '\r' in filenames
1762 l = fp.readline()
1762 l = fp.readline()
1763 try:
1763 try:
1764 name, size = l.split('\0', 1)
1764 name, size = l.split('\0', 1)
1765 size = int(size)
1765 size = int(size)
1766 except (ValueError, TypeError):
1766 except (ValueError, TypeError):
1767 raise error.ResponseError(
1767 raise error.ResponseError(
1768 _('unexpected response from remote server:'), l)
1768 _('unexpected response from remote server:'), l)
1769 if self.ui.debugflag:
1769 if self.ui.debugflag:
1770 self.ui.debug('adding %s (%s)\n' %
1770 self.ui.debug('adding %s (%s)\n' %
1771 (name, util.bytecount(size)))
1771 (name, util.bytecount(size)))
1772 # for backwards compat, name was partially encoded
1772 # for backwards compat, name was partially encoded
1773 ofp = self.sopener(store.decodedir(name), 'w')
1773 ofp = self.sopener(store.decodedir(name), 'w')
1774 for chunk in util.filechunkiter(fp, limit=size):
1774 for chunk in util.filechunkiter(fp, limit=size):
1775 handled_bytes += len(chunk)
1775 handled_bytes += len(chunk)
1776 self.ui.progress(_('clone'), handled_bytes,
1776 self.ui.progress(_('clone'), handled_bytes,
1777 total=total_bytes)
1777 total=total_bytes)
1778 ofp.write(chunk)
1778 ofp.write(chunk)
1779 ofp.close()
1779 ofp.close()
1780 tr.close()
1780 tr.close()
1781 finally:
1781 finally:
1782 tr.release()
1782 tr.release()
1783
1783
1784 # Writing straight to files circumvented the inmemory caches
1784 # Writing straight to files circumvented the inmemory caches
1785 self.invalidate()
1785 self.invalidate()
1786
1786
1787 elapsed = time.time() - start
1787 elapsed = time.time() - start
1788 if elapsed <= 0:
1788 if elapsed <= 0:
1789 elapsed = 0.001
1789 elapsed = 0.001
1790 self.ui.progress(_('clone'), None)
1790 self.ui.progress(_('clone'), None)
1791 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1791 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1792 (util.bytecount(total_bytes), elapsed,
1792 (util.bytecount(total_bytes), elapsed,
1793 util.bytecount(total_bytes / elapsed)))
1793 util.bytecount(total_bytes / elapsed)))
1794
1794
1795 # new requirements = old non-format requirements +
1795 # new requirements = old non-format requirements +
1796 # new format-related
1796 # new format-related
1797 # requirements from the streamed-in repository
1797 # requirements from the streamed-in repository
1798 requirements.update(set(self.requirements) - self.supportedformats)
1798 requirements.update(set(self.requirements) - self.supportedformats)
1799 self._applyrequirements(requirements)
1799 self._applyrequirements(requirements)
1800 self._writerequirements()
1800 self._writerequirements()
1801
1801
1802 if rbranchmap:
1802 if rbranchmap:
1803 rbheads = []
1803 rbheads = []
1804 for bheads in rbranchmap.itervalues():
1804 for bheads in rbranchmap.itervalues():
1805 rbheads.extend(bheads)
1805 rbheads.extend(bheads)
1806
1806
1807 if rbheads:
1807 if rbheads:
1808 rtiprev = max((int(self.changelog.rev(node))
1808 rtiprev = max((int(self.changelog.rev(node))
1809 for node in rbheads))
1809 for node in rbheads))
1810 cache = branchmap.branchcache(rbranchmap,
1810 cache = branchmap.branchcache(rbranchmap,
1811 self[rtiprev].node(),
1811 self[rtiprev].node(),
1812 rtiprev)
1812 rtiprev)
1813 # Try to stick it as low as possible
1813 # Try to stick it as low as possible
1814 # filter above served are unlikely to be fetch from a clone
1814 # filter above served are unlikely to be fetch from a clone
1815 for candidate in ('base', 'immutable', 'served'):
1815 for candidate in ('base', 'immutable', 'served'):
1816 rview = self.filtered(candidate)
1816 rview = self.filtered(candidate)
1817 if cache.validfor(rview):
1817 if cache.validfor(rview):
1818 self._branchcaches[candidate] = cache
1818 self._branchcaches[candidate] = cache
1819 cache.write(rview)
1819 cache.write(rview)
1820 break
1820 break
1821 self.invalidate()
1821 self.invalidate()
1822 return len(self.heads()) + 1
1822 return len(self.heads()) + 1
1823 finally:
1823 finally:
1824 lock.release()
1824 lock.release()
1825
1825
1826 def clone(self, remote, heads=[], stream=False):
1826 def clone(self, remote, heads=[], stream=False):
1827 '''clone remote repository.
1827 '''clone remote repository.
1828
1828
1829 keyword arguments:
1829 keyword arguments:
1830 heads: list of revs to clone (forces use of pull)
1830 heads: list of revs to clone (forces use of pull)
1831 stream: use streaming clone if possible'''
1831 stream: use streaming clone if possible'''
1832
1832
1833 # now, all clients that can request uncompressed clones can
1833 # now, all clients that can request uncompressed clones can
1834 # read repo formats supported by all servers that can serve
1834 # read repo formats supported by all servers that can serve
1835 # them.
1835 # them.
1836
1836
1837 # if revlog format changes, client will have to check version
1837 # if revlog format changes, client will have to check version
1838 # and format flags on "stream" capability, and use
1838 # and format flags on "stream" capability, and use
1839 # uncompressed only if compatible.
1839 # uncompressed only if compatible.
1840
1840
1841 if not stream:
1841 if not stream:
1842 # if the server explicitly prefers to stream (for fast LANs)
1842 # if the server explicitly prefers to stream (for fast LANs)
1843 stream = remote.capable('stream-preferred')
1843 stream = remote.capable('stream-preferred')
1844
1844
1845 if stream and not heads:
1845 if stream and not heads:
1846 # 'stream' means remote revlog format is revlogv1 only
1846 # 'stream' means remote revlog format is revlogv1 only
1847 if remote.capable('stream'):
1847 if remote.capable('stream'):
1848 return self.stream_in(remote, set(('revlogv1',)))
1848 return self.stream_in(remote, set(('revlogv1',)))
1849 # otherwise, 'streamreqs' contains the remote revlog format
1849 # otherwise, 'streamreqs' contains the remote revlog format
1850 streamreqs = remote.capable('streamreqs')
1850 streamreqs = remote.capable('streamreqs')
1851 if streamreqs:
1851 if streamreqs:
1852 streamreqs = set(streamreqs.split(','))
1852 streamreqs = set(streamreqs.split(','))
1853 # if we support it, stream in and adjust our requirements
1853 # if we support it, stream in and adjust our requirements
1854 if not streamreqs - self.supportedformats:
1854 if not streamreqs - self.supportedformats:
1855 return self.stream_in(remote, streamreqs)
1855 return self.stream_in(remote, streamreqs)
1856 return self.pull(remote, heads)
1856 return self.pull(remote, heads)
1857
1857
1858 def pushkey(self, namespace, key, old, new):
1858 def pushkey(self, namespace, key, old, new):
1859 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1859 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1860 old=old, new=new)
1860 old=old, new=new)
1861 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1861 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1862 ret = pushkey.push(self, namespace, key, old, new)
1862 ret = pushkey.push(self, namespace, key, old, new)
1863 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1863 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1864 ret=ret)
1864 ret=ret)
1865 return ret
1865 return ret
1866
1866
1867 def listkeys(self, namespace):
1867 def listkeys(self, namespace):
1868 self.hook('prelistkeys', throw=True, namespace=namespace)
1868 self.hook('prelistkeys', throw=True, namespace=namespace)
1869 self.ui.debug('listing keys for "%s"\n' % namespace)
1869 self.ui.debug('listing keys for "%s"\n' % namespace)
1870 values = pushkey.list(self, namespace)
1870 values = pushkey.list(self, namespace)
1871 self.hook('listkeys', namespace=namespace, values=values)
1871 self.hook('listkeys', namespace=namespace, values=values)
1872 return values
1872 return values
1873
1873
1874 def debugwireargs(self, one, two, three=None, four=None, five=None):
1874 def debugwireargs(self, one, two, three=None, four=None, five=None):
1875 '''used to test argument passing over the wire'''
1875 '''used to test argument passing over the wire'''
1876 return "%s %s %s %s %s" % (one, two, three, four, five)
1876 return "%s %s %s %s %s" % (one, two, three, four, five)
1877
1877
1878 def savecommitmessage(self, text):
1878 def savecommitmessage(self, text):
1879 fp = self.opener('last-message.txt', 'wb')
1879 fp = self.opener('last-message.txt', 'wb')
1880 try:
1880 try:
1881 fp.write(text)
1881 fp.write(text)
1882 finally:
1882 finally:
1883 fp.close()
1883 fp.close()
1884 return self.pathto(fp.name[len(self.root) + 1:])
1884 return self.pathto(fp.name[len(self.root) + 1:])
1885
1885
1886 # used to avoid circular references so destructors work
1886 # used to avoid circular references so destructors work
1887 def aftertrans(files):
1887 def aftertrans(files):
1888 renamefiles = [tuple(t) for t in files]
1888 renamefiles = [tuple(t) for t in files]
1889 def a():
1889 def a():
1890 for vfs, src, dest in renamefiles:
1890 for vfs, src, dest in renamefiles:
1891 try:
1891 try:
1892 vfs.rename(src, dest)
1892 vfs.rename(src, dest)
1893 except OSError: # journal file does not yet exist
1893 except OSError: # journal file does not yet exist
1894 pass
1894 pass
1895 return a
1895 return a
1896
1896
1897 def undoname(fn):
1897 def undoname(fn):
1898 base, name = os.path.split(fn)
1898 base, name = os.path.split(fn)
1899 assert name.startswith('journal')
1899 assert name.startswith('journal')
1900 return os.path.join(base, name.replace('journal', 'undo', 1))
1900 return os.path.join(base, name.replace('journal', 'undo', 1))
1901
1901
1902 def instance(ui, path, create):
1902 def instance(ui, path, create):
1903 return localrepository(ui, util.urllocalpath(path), create)
1903 return localrepository(ui, util.urllocalpath(path), create)
1904
1904
1905 def islocal(path):
1905 def islocal(path):
1906 return True
1906 return True
General Comments 0
You need to be logged in to leave comments. Login now