##// END OF EJS Templates
repoview: extract a factory function of proxy class...
Yuya Nishihara -
r35248:c752fbe2 default
parent child Browse files
Show More
@@ -1,2289 +1,2274 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import inspect
12 import inspect
13 import os
13 import os
14 import random
14 import random
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 hex,
20 hex,
21 nullid,
21 nullid,
22 short,
22 short,
23 )
23 )
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 branchmap,
26 branchmap,
27 bundle2,
27 bundle2,
28 changegroup,
28 changegroup,
29 changelog,
29 changelog,
30 color,
30 color,
31 context,
31 context,
32 dirstate,
32 dirstate,
33 dirstateguard,
33 dirstateguard,
34 discovery,
34 discovery,
35 encoding,
35 encoding,
36 error,
36 error,
37 exchange,
37 exchange,
38 extensions,
38 extensions,
39 filelog,
39 filelog,
40 hook,
40 hook,
41 lock as lockmod,
41 lock as lockmod,
42 manifest,
42 manifest,
43 match as matchmod,
43 match as matchmod,
44 merge as mergemod,
44 merge as mergemod,
45 mergeutil,
45 mergeutil,
46 namespaces,
46 namespaces,
47 obsolete,
47 obsolete,
48 pathutil,
48 pathutil,
49 peer,
49 peer,
50 phases,
50 phases,
51 pushkey,
51 pushkey,
52 pycompat,
52 pycompat,
53 repository,
53 repository,
54 repoview,
54 repoview,
55 revset,
55 revset,
56 revsetlang,
56 revsetlang,
57 scmutil,
57 scmutil,
58 sparse,
58 sparse,
59 store,
59 store,
60 subrepo,
60 subrepo,
61 tags as tagsmod,
61 tags as tagsmod,
62 transaction,
62 transaction,
63 txnutil,
63 txnutil,
64 util,
64 util,
65 vfs as vfsmod,
65 vfs as vfsmod,
66 )
66 )
67
67
68 release = lockmod.release
68 release = lockmod.release
69 urlerr = util.urlerr
69 urlerr = util.urlerr
70 urlreq = util.urlreq
70 urlreq = util.urlreq
71
71
72 # set of (path, vfs-location) tuples. vfs-location is:
72 # set of (path, vfs-location) tuples. vfs-location is:
73 # - 'plain for vfs relative paths
73 # - 'plain for vfs relative paths
74 # - '' for svfs relative paths
74 # - '' for svfs relative paths
75 _cachedfiles = set()
75 _cachedfiles = set()
76
76
77 class _basefilecache(scmutil.filecache):
77 class _basefilecache(scmutil.filecache):
78 """All filecache usage on repo are done for logic that should be unfiltered
78 """All filecache usage on repo are done for logic that should be unfiltered
79 """
79 """
80 def __get__(self, repo, type=None):
80 def __get__(self, repo, type=None):
81 if repo is None:
81 if repo is None:
82 return self
82 return self
83 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
83 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
84 def __set__(self, repo, value):
84 def __set__(self, repo, value):
85 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
85 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
86 def __delete__(self, repo):
86 def __delete__(self, repo):
87 return super(_basefilecache, self).__delete__(repo.unfiltered())
87 return super(_basefilecache, self).__delete__(repo.unfiltered())
88
88
89 class repofilecache(_basefilecache):
89 class repofilecache(_basefilecache):
90 """filecache for files in .hg but outside of .hg/store"""
90 """filecache for files in .hg but outside of .hg/store"""
91 def __init__(self, *paths):
91 def __init__(self, *paths):
92 super(repofilecache, self).__init__(*paths)
92 super(repofilecache, self).__init__(*paths)
93 for path in paths:
93 for path in paths:
94 _cachedfiles.add((path, 'plain'))
94 _cachedfiles.add((path, 'plain'))
95
95
96 def join(self, obj, fname):
96 def join(self, obj, fname):
97 return obj.vfs.join(fname)
97 return obj.vfs.join(fname)
98
98
99 class storecache(_basefilecache):
99 class storecache(_basefilecache):
100 """filecache for files in the store"""
100 """filecache for files in the store"""
101 def __init__(self, *paths):
101 def __init__(self, *paths):
102 super(storecache, self).__init__(*paths)
102 super(storecache, self).__init__(*paths)
103 for path in paths:
103 for path in paths:
104 _cachedfiles.add((path, ''))
104 _cachedfiles.add((path, ''))
105
105
106 def join(self, obj, fname):
106 def join(self, obj, fname):
107 return obj.sjoin(fname)
107 return obj.sjoin(fname)
108
108
109 def isfilecached(repo, name):
109 def isfilecached(repo, name):
110 """check if a repo has already cached "name" filecache-ed property
110 """check if a repo has already cached "name" filecache-ed property
111
111
112 This returns (cachedobj-or-None, iscached) tuple.
112 This returns (cachedobj-or-None, iscached) tuple.
113 """
113 """
114 cacheentry = repo.unfiltered()._filecache.get(name, None)
114 cacheentry = repo.unfiltered()._filecache.get(name, None)
115 if not cacheentry:
115 if not cacheentry:
116 return None, False
116 return None, False
117 return cacheentry.obj, True
117 return cacheentry.obj, True
118
118
119 class unfilteredpropertycache(util.propertycache):
119 class unfilteredpropertycache(util.propertycache):
120 """propertycache that apply to unfiltered repo only"""
120 """propertycache that apply to unfiltered repo only"""
121
121
122 def __get__(self, repo, type=None):
122 def __get__(self, repo, type=None):
123 unfi = repo.unfiltered()
123 unfi = repo.unfiltered()
124 if unfi is repo:
124 if unfi is repo:
125 return super(unfilteredpropertycache, self).__get__(unfi)
125 return super(unfilteredpropertycache, self).__get__(unfi)
126 return getattr(unfi, self.name)
126 return getattr(unfi, self.name)
127
127
128 class filteredpropertycache(util.propertycache):
128 class filteredpropertycache(util.propertycache):
129 """propertycache that must take filtering in account"""
129 """propertycache that must take filtering in account"""
130
130
131 def cachevalue(self, obj, value):
131 def cachevalue(self, obj, value):
132 object.__setattr__(obj, self.name, value)
132 object.__setattr__(obj, self.name, value)
133
133
134
134
135 def hasunfilteredcache(repo, name):
135 def hasunfilteredcache(repo, name):
136 """check if a repo has an unfilteredpropertycache value for <name>"""
136 """check if a repo has an unfilteredpropertycache value for <name>"""
137 return name in vars(repo.unfiltered())
137 return name in vars(repo.unfiltered())
138
138
139 def unfilteredmethod(orig):
139 def unfilteredmethod(orig):
140 """decorate method that always need to be run on unfiltered version"""
140 """decorate method that always need to be run on unfiltered version"""
141 def wrapper(repo, *args, **kwargs):
141 def wrapper(repo, *args, **kwargs):
142 return orig(repo.unfiltered(), *args, **kwargs)
142 return orig(repo.unfiltered(), *args, **kwargs)
143 return wrapper
143 return wrapper
144
144
145 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
145 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
146 'unbundle'}
146 'unbundle'}
147 legacycaps = moderncaps.union({'changegroupsubset'})
147 legacycaps = moderncaps.union({'changegroupsubset'})
148
148
149 class localpeer(repository.peer):
149 class localpeer(repository.peer):
150 '''peer for a local repo; reflects only the most recent API'''
150 '''peer for a local repo; reflects only the most recent API'''
151
151
152 def __init__(self, repo, caps=None):
152 def __init__(self, repo, caps=None):
153 super(localpeer, self).__init__()
153 super(localpeer, self).__init__()
154
154
155 if caps is None:
155 if caps is None:
156 caps = moderncaps.copy()
156 caps = moderncaps.copy()
157 self._repo = repo.filtered('served')
157 self._repo = repo.filtered('served')
158 self._ui = repo.ui
158 self._ui = repo.ui
159 self._caps = repo._restrictcapabilities(caps)
159 self._caps = repo._restrictcapabilities(caps)
160
160
161 # Begin of _basepeer interface.
161 # Begin of _basepeer interface.
162
162
163 @util.propertycache
163 @util.propertycache
164 def ui(self):
164 def ui(self):
165 return self._ui
165 return self._ui
166
166
167 def url(self):
167 def url(self):
168 return self._repo.url()
168 return self._repo.url()
169
169
170 def local(self):
170 def local(self):
171 return self._repo
171 return self._repo
172
172
173 def peer(self):
173 def peer(self):
174 return self
174 return self
175
175
176 def canpush(self):
176 def canpush(self):
177 return True
177 return True
178
178
179 def close(self):
179 def close(self):
180 self._repo.close()
180 self._repo.close()
181
181
182 # End of _basepeer interface.
182 # End of _basepeer interface.
183
183
184 # Begin of _basewirecommands interface.
184 # Begin of _basewirecommands interface.
185
185
186 def branchmap(self):
186 def branchmap(self):
187 return self._repo.branchmap()
187 return self._repo.branchmap()
188
188
189 def capabilities(self):
189 def capabilities(self):
190 return self._caps
190 return self._caps
191
191
192 def debugwireargs(self, one, two, three=None, four=None, five=None):
192 def debugwireargs(self, one, two, three=None, four=None, five=None):
193 """Used to test argument passing over the wire"""
193 """Used to test argument passing over the wire"""
194 return "%s %s %s %s %s" % (one, two, three, four, five)
194 return "%s %s %s %s %s" % (one, two, three, four, five)
195
195
196 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
196 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
197 **kwargs):
197 **kwargs):
198 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
198 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
199 common=common, bundlecaps=bundlecaps,
199 common=common, bundlecaps=bundlecaps,
200 **kwargs)
200 **kwargs)
201 cb = util.chunkbuffer(chunks)
201 cb = util.chunkbuffer(chunks)
202
202
203 if exchange.bundle2requested(bundlecaps):
203 if exchange.bundle2requested(bundlecaps):
204 # When requesting a bundle2, getbundle returns a stream to make the
204 # When requesting a bundle2, getbundle returns a stream to make the
205 # wire level function happier. We need to build a proper object
205 # wire level function happier. We need to build a proper object
206 # from it in local peer.
206 # from it in local peer.
207 return bundle2.getunbundler(self.ui, cb)
207 return bundle2.getunbundler(self.ui, cb)
208 else:
208 else:
209 return changegroup.getunbundler('01', cb, None)
209 return changegroup.getunbundler('01', cb, None)
210
210
211 def heads(self):
211 def heads(self):
212 return self._repo.heads()
212 return self._repo.heads()
213
213
214 def known(self, nodes):
214 def known(self, nodes):
215 return self._repo.known(nodes)
215 return self._repo.known(nodes)
216
216
217 def listkeys(self, namespace):
217 def listkeys(self, namespace):
218 return self._repo.listkeys(namespace)
218 return self._repo.listkeys(namespace)
219
219
220 def lookup(self, key):
220 def lookup(self, key):
221 return self._repo.lookup(key)
221 return self._repo.lookup(key)
222
222
223 def pushkey(self, namespace, key, old, new):
223 def pushkey(self, namespace, key, old, new):
224 return self._repo.pushkey(namespace, key, old, new)
224 return self._repo.pushkey(namespace, key, old, new)
225
225
226 def stream_out(self):
226 def stream_out(self):
227 raise error.Abort(_('cannot perform stream clone against local '
227 raise error.Abort(_('cannot perform stream clone against local '
228 'peer'))
228 'peer'))
229
229
230 def unbundle(self, cg, heads, url):
230 def unbundle(self, cg, heads, url):
231 """apply a bundle on a repo
231 """apply a bundle on a repo
232
232
233 This function handles the repo locking itself."""
233 This function handles the repo locking itself."""
234 try:
234 try:
235 try:
235 try:
236 cg = exchange.readbundle(self.ui, cg, None)
236 cg = exchange.readbundle(self.ui, cg, None)
237 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
237 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
238 if util.safehasattr(ret, 'getchunks'):
238 if util.safehasattr(ret, 'getchunks'):
239 # This is a bundle20 object, turn it into an unbundler.
239 # This is a bundle20 object, turn it into an unbundler.
240 # This little dance should be dropped eventually when the
240 # This little dance should be dropped eventually when the
241 # API is finally improved.
241 # API is finally improved.
242 stream = util.chunkbuffer(ret.getchunks())
242 stream = util.chunkbuffer(ret.getchunks())
243 ret = bundle2.getunbundler(self.ui, stream)
243 ret = bundle2.getunbundler(self.ui, stream)
244 return ret
244 return ret
245 except Exception as exc:
245 except Exception as exc:
246 # If the exception contains output salvaged from a bundle2
246 # If the exception contains output salvaged from a bundle2
247 # reply, we need to make sure it is printed before continuing
247 # reply, we need to make sure it is printed before continuing
248 # to fail. So we build a bundle2 with such output and consume
248 # to fail. So we build a bundle2 with such output and consume
249 # it directly.
249 # it directly.
250 #
250 #
251 # This is not very elegant but allows a "simple" solution for
251 # This is not very elegant but allows a "simple" solution for
252 # issue4594
252 # issue4594
253 output = getattr(exc, '_bundle2salvagedoutput', ())
253 output = getattr(exc, '_bundle2salvagedoutput', ())
254 if output:
254 if output:
255 bundler = bundle2.bundle20(self._repo.ui)
255 bundler = bundle2.bundle20(self._repo.ui)
256 for out in output:
256 for out in output:
257 bundler.addpart(out)
257 bundler.addpart(out)
258 stream = util.chunkbuffer(bundler.getchunks())
258 stream = util.chunkbuffer(bundler.getchunks())
259 b = bundle2.getunbundler(self.ui, stream)
259 b = bundle2.getunbundler(self.ui, stream)
260 bundle2.processbundle(self._repo, b)
260 bundle2.processbundle(self._repo, b)
261 raise
261 raise
262 except error.PushRaced as exc:
262 except error.PushRaced as exc:
263 raise error.ResponseError(_('push failed:'), str(exc))
263 raise error.ResponseError(_('push failed:'), str(exc))
264
264
265 # End of _basewirecommands interface.
265 # End of _basewirecommands interface.
266
266
267 # Begin of peer interface.
267 # Begin of peer interface.
268
268
269 def iterbatch(self):
269 def iterbatch(self):
270 return peer.localiterbatcher(self)
270 return peer.localiterbatcher(self)
271
271
272 # End of peer interface.
272 # End of peer interface.
273
273
274 class locallegacypeer(repository.legacypeer, localpeer):
274 class locallegacypeer(repository.legacypeer, localpeer):
275 '''peer extension which implements legacy methods too; used for tests with
275 '''peer extension which implements legacy methods too; used for tests with
276 restricted capabilities'''
276 restricted capabilities'''
277
277
278 def __init__(self, repo):
278 def __init__(self, repo):
279 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
279 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
280
280
281 # Begin of baselegacywirecommands interface.
281 # Begin of baselegacywirecommands interface.
282
282
283 def between(self, pairs):
283 def between(self, pairs):
284 return self._repo.between(pairs)
284 return self._repo.between(pairs)
285
285
286 def branches(self, nodes):
286 def branches(self, nodes):
287 return self._repo.branches(nodes)
287 return self._repo.branches(nodes)
288
288
289 def changegroup(self, basenodes, source):
289 def changegroup(self, basenodes, source):
290 outgoing = discovery.outgoing(self._repo, missingroots=basenodes,
290 outgoing = discovery.outgoing(self._repo, missingroots=basenodes,
291 missingheads=self._repo.heads())
291 missingheads=self._repo.heads())
292 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
292 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
293
293
294 def changegroupsubset(self, bases, heads, source):
294 def changegroupsubset(self, bases, heads, source):
295 outgoing = discovery.outgoing(self._repo, missingroots=bases,
295 outgoing = discovery.outgoing(self._repo, missingroots=bases,
296 missingheads=heads)
296 missingheads=heads)
297 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
297 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
298
298
299 # End of baselegacywirecommands interface.
299 # End of baselegacywirecommands interface.
300
300
301 # Increment the sub-version when the revlog v2 format changes to lock out old
301 # Increment the sub-version when the revlog v2 format changes to lock out old
302 # clients.
302 # clients.
303 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
303 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
304
304
305 class localrepository(object):
305 class localrepository(object):
306
306
307 supportedformats = {
307 supportedformats = {
308 'revlogv1',
308 'revlogv1',
309 'generaldelta',
309 'generaldelta',
310 'treemanifest',
310 'treemanifest',
311 'manifestv2',
311 'manifestv2',
312 REVLOGV2_REQUIREMENT,
312 REVLOGV2_REQUIREMENT,
313 }
313 }
314 _basesupported = supportedformats | {
314 _basesupported = supportedformats | {
315 'store',
315 'store',
316 'fncache',
316 'fncache',
317 'shared',
317 'shared',
318 'relshared',
318 'relshared',
319 'dotencode',
319 'dotencode',
320 'exp-sparse',
320 'exp-sparse',
321 }
321 }
322 openerreqs = {
322 openerreqs = {
323 'revlogv1',
323 'revlogv1',
324 'generaldelta',
324 'generaldelta',
325 'treemanifest',
325 'treemanifest',
326 'manifestv2',
326 'manifestv2',
327 }
327 }
328
328
329 # a list of (ui, featureset) functions.
329 # a list of (ui, featureset) functions.
330 # only functions defined in module of enabled extensions are invoked
330 # only functions defined in module of enabled extensions are invoked
331 featuresetupfuncs = set()
331 featuresetupfuncs = set()
332
332
333 # list of prefix for file which can be written without 'wlock'
333 # list of prefix for file which can be written without 'wlock'
334 # Extensions should extend this list when needed
334 # Extensions should extend this list when needed
335 _wlockfreeprefix = {
335 _wlockfreeprefix = {
336 # We migh consider requiring 'wlock' for the next
336 # We migh consider requiring 'wlock' for the next
337 # two, but pretty much all the existing code assume
337 # two, but pretty much all the existing code assume
338 # wlock is not needed so we keep them excluded for
338 # wlock is not needed so we keep them excluded for
339 # now.
339 # now.
340 'hgrc',
340 'hgrc',
341 'requires',
341 'requires',
342 # XXX cache is a complicatged business someone
342 # XXX cache is a complicatged business someone
343 # should investigate this in depth at some point
343 # should investigate this in depth at some point
344 'cache/',
344 'cache/',
345 # XXX shouldn't be dirstate covered by the wlock?
345 # XXX shouldn't be dirstate covered by the wlock?
346 'dirstate',
346 'dirstate',
347 # XXX bisect was still a bit too messy at the time
347 # XXX bisect was still a bit too messy at the time
348 # this changeset was introduced. Someone should fix
348 # this changeset was introduced. Someone should fix
349 # the remainig bit and drop this line
349 # the remainig bit and drop this line
350 'bisect.state',
350 'bisect.state',
351 }
351 }
352
352
353 def __init__(self, baseui, path, create=False):
353 def __init__(self, baseui, path, create=False):
354 self.requirements = set()
354 self.requirements = set()
355 self.filtername = None
355 self.filtername = None
356 # wvfs: rooted at the repository root, used to access the working copy
356 # wvfs: rooted at the repository root, used to access the working copy
357 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
357 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
358 # vfs: rooted at .hg, used to access repo files outside of .hg/store
358 # vfs: rooted at .hg, used to access repo files outside of .hg/store
359 self.vfs = None
359 self.vfs = None
360 # svfs: usually rooted at .hg/store, used to access repository history
360 # svfs: usually rooted at .hg/store, used to access repository history
361 # If this is a shared repository, this vfs may point to another
361 # If this is a shared repository, this vfs may point to another
362 # repository's .hg/store directory.
362 # repository's .hg/store directory.
363 self.svfs = None
363 self.svfs = None
364 self.root = self.wvfs.base
364 self.root = self.wvfs.base
365 self.path = self.wvfs.join(".hg")
365 self.path = self.wvfs.join(".hg")
366 self.origroot = path
366 self.origroot = path
367 # This is only used by context.workingctx.match in order to
367 # This is only used by context.workingctx.match in order to
368 # detect files in subrepos.
368 # detect files in subrepos.
369 self.auditor = pathutil.pathauditor(
369 self.auditor = pathutil.pathauditor(
370 self.root, callback=self._checknested)
370 self.root, callback=self._checknested)
371 # This is only used by context.basectx.match in order to detect
371 # This is only used by context.basectx.match in order to detect
372 # files in subrepos.
372 # files in subrepos.
373 self.nofsauditor = pathutil.pathauditor(
373 self.nofsauditor = pathutil.pathauditor(
374 self.root, callback=self._checknested, realfs=False, cached=True)
374 self.root, callback=self._checknested, realfs=False, cached=True)
375 self.baseui = baseui
375 self.baseui = baseui
376 self.ui = baseui.copy()
376 self.ui = baseui.copy()
377 self.ui.copy = baseui.copy # prevent copying repo configuration
377 self.ui.copy = baseui.copy # prevent copying repo configuration
378 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
378 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
379 if (self.ui.configbool('devel', 'all-warnings') or
379 if (self.ui.configbool('devel', 'all-warnings') or
380 self.ui.configbool('devel', 'check-locks')):
380 self.ui.configbool('devel', 'check-locks')):
381 self.vfs.audit = self._getvfsward(self.vfs.audit)
381 self.vfs.audit = self._getvfsward(self.vfs.audit)
382 # A list of callback to shape the phase if no data were found.
382 # A list of callback to shape the phase if no data were found.
383 # Callback are in the form: func(repo, roots) --> processed root.
383 # Callback are in the form: func(repo, roots) --> processed root.
384 # This list it to be filled by extension during repo setup
384 # This list it to be filled by extension during repo setup
385 self._phasedefaults = []
385 self._phasedefaults = []
386 try:
386 try:
387 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
387 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
388 self._loadextensions()
388 self._loadextensions()
389 except IOError:
389 except IOError:
390 pass
390 pass
391
391
392 if self.featuresetupfuncs:
392 if self.featuresetupfuncs:
393 self.supported = set(self._basesupported) # use private copy
393 self.supported = set(self._basesupported) # use private copy
394 extmods = set(m.__name__ for n, m
394 extmods = set(m.__name__ for n, m
395 in extensions.extensions(self.ui))
395 in extensions.extensions(self.ui))
396 for setupfunc in self.featuresetupfuncs:
396 for setupfunc in self.featuresetupfuncs:
397 if setupfunc.__module__ in extmods:
397 if setupfunc.__module__ in extmods:
398 setupfunc(self.ui, self.supported)
398 setupfunc(self.ui, self.supported)
399 else:
399 else:
400 self.supported = self._basesupported
400 self.supported = self._basesupported
401 color.setup(self.ui)
401 color.setup(self.ui)
402
402
403 # Add compression engines.
403 # Add compression engines.
404 for name in util.compengines:
404 for name in util.compengines:
405 engine = util.compengines[name]
405 engine = util.compengines[name]
406 if engine.revlogheader():
406 if engine.revlogheader():
407 self.supported.add('exp-compression-%s' % name)
407 self.supported.add('exp-compression-%s' % name)
408
408
409 if not self.vfs.isdir():
409 if not self.vfs.isdir():
410 if create:
410 if create:
411 self.requirements = newreporequirements(self)
411 self.requirements = newreporequirements(self)
412
412
413 if not self.wvfs.exists():
413 if not self.wvfs.exists():
414 self.wvfs.makedirs()
414 self.wvfs.makedirs()
415 self.vfs.makedir(notindexed=True)
415 self.vfs.makedir(notindexed=True)
416
416
417 if 'store' in self.requirements:
417 if 'store' in self.requirements:
418 self.vfs.mkdir("store")
418 self.vfs.mkdir("store")
419
419
420 # create an invalid changelog
420 # create an invalid changelog
421 self.vfs.append(
421 self.vfs.append(
422 "00changelog.i",
422 "00changelog.i",
423 '\0\0\0\2' # represents revlogv2
423 '\0\0\0\2' # represents revlogv2
424 ' dummy changelog to prevent using the old repo layout'
424 ' dummy changelog to prevent using the old repo layout'
425 )
425 )
426 else:
426 else:
427 raise error.RepoError(_("repository %s not found") % path)
427 raise error.RepoError(_("repository %s not found") % path)
428 elif create:
428 elif create:
429 raise error.RepoError(_("repository %s already exists") % path)
429 raise error.RepoError(_("repository %s already exists") % path)
430 else:
430 else:
431 try:
431 try:
432 self.requirements = scmutil.readrequires(
432 self.requirements = scmutil.readrequires(
433 self.vfs, self.supported)
433 self.vfs, self.supported)
434 except IOError as inst:
434 except IOError as inst:
435 if inst.errno != errno.ENOENT:
435 if inst.errno != errno.ENOENT:
436 raise
436 raise
437
437
438 cachepath = self.vfs.join('cache')
438 cachepath = self.vfs.join('cache')
439 self.sharedpath = self.path
439 self.sharedpath = self.path
440 try:
440 try:
441 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
441 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
442 if 'relshared' in self.requirements:
442 if 'relshared' in self.requirements:
443 sharedpath = self.vfs.join(sharedpath)
443 sharedpath = self.vfs.join(sharedpath)
444 vfs = vfsmod.vfs(sharedpath, realpath=True)
444 vfs = vfsmod.vfs(sharedpath, realpath=True)
445 cachepath = vfs.join('cache')
445 cachepath = vfs.join('cache')
446 s = vfs.base
446 s = vfs.base
447 if not vfs.exists():
447 if not vfs.exists():
448 raise error.RepoError(
448 raise error.RepoError(
449 _('.hg/sharedpath points to nonexistent directory %s') % s)
449 _('.hg/sharedpath points to nonexistent directory %s') % s)
450 self.sharedpath = s
450 self.sharedpath = s
451 except IOError as inst:
451 except IOError as inst:
452 if inst.errno != errno.ENOENT:
452 if inst.errno != errno.ENOENT:
453 raise
453 raise
454
454
455 if 'exp-sparse' in self.requirements and not sparse.enabled:
455 if 'exp-sparse' in self.requirements and not sparse.enabled:
456 raise error.RepoError(_('repository is using sparse feature but '
456 raise error.RepoError(_('repository is using sparse feature but '
457 'sparse is not enabled; enable the '
457 'sparse is not enabled; enable the '
458 '"sparse" extensions to access'))
458 '"sparse" extensions to access'))
459
459
460 self.store = store.store(
460 self.store = store.store(
461 self.requirements, self.sharedpath,
461 self.requirements, self.sharedpath,
462 lambda base: vfsmod.vfs(base, cacheaudited=True))
462 lambda base: vfsmod.vfs(base, cacheaudited=True))
463 self.spath = self.store.path
463 self.spath = self.store.path
464 self.svfs = self.store.vfs
464 self.svfs = self.store.vfs
465 self.sjoin = self.store.join
465 self.sjoin = self.store.join
466 self.vfs.createmode = self.store.createmode
466 self.vfs.createmode = self.store.createmode
467 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
467 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
468 self.cachevfs.createmode = self.store.createmode
468 self.cachevfs.createmode = self.store.createmode
469 if (self.ui.configbool('devel', 'all-warnings') or
469 if (self.ui.configbool('devel', 'all-warnings') or
470 self.ui.configbool('devel', 'check-locks')):
470 self.ui.configbool('devel', 'check-locks')):
471 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
471 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
472 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
472 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
473 else: # standard vfs
473 else: # standard vfs
474 self.svfs.audit = self._getsvfsward(self.svfs.audit)
474 self.svfs.audit = self._getsvfsward(self.svfs.audit)
475 self._applyopenerreqs()
475 self._applyopenerreqs()
476 if create:
476 if create:
477 self._writerequirements()
477 self._writerequirements()
478
478
479 self._dirstatevalidatewarned = False
479 self._dirstatevalidatewarned = False
480
480
481 self._branchcaches = {}
481 self._branchcaches = {}
482 self._revbranchcache = None
482 self._revbranchcache = None
483 self.filterpats = {}
483 self.filterpats = {}
484 self._datafilters = {}
484 self._datafilters = {}
485 self._transref = self._lockref = self._wlockref = None
485 self._transref = self._lockref = self._wlockref = None
486
486
487 # A cache for various files under .hg/ that tracks file changes,
487 # A cache for various files under .hg/ that tracks file changes,
488 # (used by the filecache decorator)
488 # (used by the filecache decorator)
489 #
489 #
490 # Maps a property name to its util.filecacheentry
490 # Maps a property name to its util.filecacheentry
491 self._filecache = {}
491 self._filecache = {}
492
492
493 # hold sets of revision to be filtered
493 # hold sets of revision to be filtered
494 # should be cleared when something might have changed the filter value:
494 # should be cleared when something might have changed the filter value:
495 # - new changesets,
495 # - new changesets,
496 # - phase change,
496 # - phase change,
497 # - new obsolescence marker,
497 # - new obsolescence marker,
498 # - working directory parent change,
498 # - working directory parent change,
499 # - bookmark changes
499 # - bookmark changes
500 self.filteredrevcache = {}
500 self.filteredrevcache = {}
501
501
502 # post-dirstate-status hooks
502 # post-dirstate-status hooks
503 self._postdsstatus = []
503 self._postdsstatus = []
504
504
505 # Cache of types representing filtered repos.
506 self._filteredrepotypes = weakref.WeakKeyDictionary()
507
508 # generic mapping between names and nodes
505 # generic mapping between names and nodes
509 self.names = namespaces.namespaces()
506 self.names = namespaces.namespaces()
510
507
511 # Key to signature value.
508 # Key to signature value.
512 self._sparsesignaturecache = {}
509 self._sparsesignaturecache = {}
513 # Signature to cached matcher instance.
510 # Signature to cached matcher instance.
514 self._sparsematchercache = {}
511 self._sparsematchercache = {}
515
512
516 def _getvfsward(self, origfunc):
513 def _getvfsward(self, origfunc):
517 """build a ward for self.vfs"""
514 """build a ward for self.vfs"""
518 rref = weakref.ref(self)
515 rref = weakref.ref(self)
519 def checkvfs(path, mode=None):
516 def checkvfs(path, mode=None):
520 ret = origfunc(path, mode=mode)
517 ret = origfunc(path, mode=mode)
521 repo = rref()
518 repo = rref()
522 if (repo is None
519 if (repo is None
523 or not util.safehasattr(repo, '_wlockref')
520 or not util.safehasattr(repo, '_wlockref')
524 or not util.safehasattr(repo, '_lockref')):
521 or not util.safehasattr(repo, '_lockref')):
525 return
522 return
526 if mode in (None, 'r', 'rb'):
523 if mode in (None, 'r', 'rb'):
527 return
524 return
528 if path.startswith(repo.path):
525 if path.startswith(repo.path):
529 # truncate name relative to the repository (.hg)
526 # truncate name relative to the repository (.hg)
530 path = path[len(repo.path) + 1:]
527 path = path[len(repo.path) + 1:]
531 if path.startswith('cache/'):
528 if path.startswith('cache/'):
532 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
529 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
533 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
530 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
534 if path.startswith('journal.'):
531 if path.startswith('journal.'):
535 # journal is covered by 'lock'
532 # journal is covered by 'lock'
536 if repo._currentlock(repo._lockref) is None:
533 if repo._currentlock(repo._lockref) is None:
537 repo.ui.develwarn('write with no lock: "%s"' % path,
534 repo.ui.develwarn('write with no lock: "%s"' % path,
538 stacklevel=2, config='check-locks')
535 stacklevel=2, config='check-locks')
539 elif repo._currentlock(repo._wlockref) is None:
536 elif repo._currentlock(repo._wlockref) is None:
540 # rest of vfs files are covered by 'wlock'
537 # rest of vfs files are covered by 'wlock'
541 #
538 #
542 # exclude special files
539 # exclude special files
543 for prefix in self._wlockfreeprefix:
540 for prefix in self._wlockfreeprefix:
544 if path.startswith(prefix):
541 if path.startswith(prefix):
545 return
542 return
546 repo.ui.develwarn('write with no wlock: "%s"' % path,
543 repo.ui.develwarn('write with no wlock: "%s"' % path,
547 stacklevel=2, config='check-locks')
544 stacklevel=2, config='check-locks')
548 return ret
545 return ret
549 return checkvfs
546 return checkvfs
550
547
551 def _getsvfsward(self, origfunc):
548 def _getsvfsward(self, origfunc):
552 """build a ward for self.svfs"""
549 """build a ward for self.svfs"""
553 rref = weakref.ref(self)
550 rref = weakref.ref(self)
554 def checksvfs(path, mode=None):
551 def checksvfs(path, mode=None):
555 ret = origfunc(path, mode=mode)
552 ret = origfunc(path, mode=mode)
556 repo = rref()
553 repo = rref()
557 if repo is None or not util.safehasattr(repo, '_lockref'):
554 if repo is None or not util.safehasattr(repo, '_lockref'):
558 return
555 return
559 if mode in (None, 'r', 'rb'):
556 if mode in (None, 'r', 'rb'):
560 return
557 return
561 if path.startswith(repo.sharedpath):
558 if path.startswith(repo.sharedpath):
562 # truncate name relative to the repository (.hg)
559 # truncate name relative to the repository (.hg)
563 path = path[len(repo.sharedpath) + 1:]
560 path = path[len(repo.sharedpath) + 1:]
564 if repo._currentlock(repo._lockref) is None:
561 if repo._currentlock(repo._lockref) is None:
565 repo.ui.develwarn('write with no lock: "%s"' % path,
562 repo.ui.develwarn('write with no lock: "%s"' % path,
566 stacklevel=3)
563 stacklevel=3)
567 return ret
564 return ret
568 return checksvfs
565 return checksvfs
569
566
570 def close(self):
567 def close(self):
571 self._writecaches()
568 self._writecaches()
572
569
573 def _loadextensions(self):
570 def _loadextensions(self):
574 extensions.loadall(self.ui)
571 extensions.loadall(self.ui)
575
572
576 def _writecaches(self):
573 def _writecaches(self):
577 if self._revbranchcache:
574 if self._revbranchcache:
578 self._revbranchcache.write()
575 self._revbranchcache.write()
579
576
580 def _restrictcapabilities(self, caps):
577 def _restrictcapabilities(self, caps):
581 if self.ui.configbool('experimental', 'bundle2-advertise'):
578 if self.ui.configbool('experimental', 'bundle2-advertise'):
582 caps = set(caps)
579 caps = set(caps)
583 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
580 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
584 caps.add('bundle2=' + urlreq.quote(capsblob))
581 caps.add('bundle2=' + urlreq.quote(capsblob))
585 return caps
582 return caps
586
583
587 def _applyopenerreqs(self):
584 def _applyopenerreqs(self):
588 self.svfs.options = dict((r, 1) for r in self.requirements
585 self.svfs.options = dict((r, 1) for r in self.requirements
589 if r in self.openerreqs)
586 if r in self.openerreqs)
590 # experimental config: format.chunkcachesize
587 # experimental config: format.chunkcachesize
591 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
588 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
592 if chunkcachesize is not None:
589 if chunkcachesize is not None:
593 self.svfs.options['chunkcachesize'] = chunkcachesize
590 self.svfs.options['chunkcachesize'] = chunkcachesize
594 # experimental config: format.maxchainlen
591 # experimental config: format.maxchainlen
595 maxchainlen = self.ui.configint('format', 'maxchainlen')
592 maxchainlen = self.ui.configint('format', 'maxchainlen')
596 if maxchainlen is not None:
593 if maxchainlen is not None:
597 self.svfs.options['maxchainlen'] = maxchainlen
594 self.svfs.options['maxchainlen'] = maxchainlen
598 # experimental config: format.manifestcachesize
595 # experimental config: format.manifestcachesize
599 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
596 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
600 if manifestcachesize is not None:
597 if manifestcachesize is not None:
601 self.svfs.options['manifestcachesize'] = manifestcachesize
598 self.svfs.options['manifestcachesize'] = manifestcachesize
602 # experimental config: format.aggressivemergedeltas
599 # experimental config: format.aggressivemergedeltas
603 aggressivemergedeltas = self.ui.configbool('format',
600 aggressivemergedeltas = self.ui.configbool('format',
604 'aggressivemergedeltas')
601 'aggressivemergedeltas')
605 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
602 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
606 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
603 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
607 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
604 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
608 if 0 <= chainspan:
605 if 0 <= chainspan:
609 self.svfs.options['maxdeltachainspan'] = chainspan
606 self.svfs.options['maxdeltachainspan'] = chainspan
610 mmapindexthreshold = self.ui.configbytes('experimental',
607 mmapindexthreshold = self.ui.configbytes('experimental',
611 'mmapindexthreshold')
608 'mmapindexthreshold')
612 if mmapindexthreshold is not None:
609 if mmapindexthreshold is not None:
613 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
610 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
614 withsparseread = self.ui.configbool('experimental', 'sparse-read')
611 withsparseread = self.ui.configbool('experimental', 'sparse-read')
615 srdensitythres = float(self.ui.config('experimental',
612 srdensitythres = float(self.ui.config('experimental',
616 'sparse-read.density-threshold'))
613 'sparse-read.density-threshold'))
617 srmingapsize = self.ui.configbytes('experimental',
614 srmingapsize = self.ui.configbytes('experimental',
618 'sparse-read.min-gap-size')
615 'sparse-read.min-gap-size')
619 self.svfs.options['with-sparse-read'] = withsparseread
616 self.svfs.options['with-sparse-read'] = withsparseread
620 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
617 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
621 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
618 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
622
619
623 for r in self.requirements:
620 for r in self.requirements:
624 if r.startswith('exp-compression-'):
621 if r.startswith('exp-compression-'):
625 self.svfs.options['compengine'] = r[len('exp-compression-'):]
622 self.svfs.options['compengine'] = r[len('exp-compression-'):]
626
623
627 # TODO move "revlogv2" to openerreqs once finalized.
624 # TODO move "revlogv2" to openerreqs once finalized.
628 if REVLOGV2_REQUIREMENT in self.requirements:
625 if REVLOGV2_REQUIREMENT in self.requirements:
629 self.svfs.options['revlogv2'] = True
626 self.svfs.options['revlogv2'] = True
630
627
631 def _writerequirements(self):
628 def _writerequirements(self):
632 scmutil.writerequires(self.vfs, self.requirements)
629 scmutil.writerequires(self.vfs, self.requirements)
633
630
634 def _checknested(self, path):
631 def _checknested(self, path):
635 """Determine if path is a legal nested repository."""
632 """Determine if path is a legal nested repository."""
636 if not path.startswith(self.root):
633 if not path.startswith(self.root):
637 return False
634 return False
638 subpath = path[len(self.root) + 1:]
635 subpath = path[len(self.root) + 1:]
639 normsubpath = util.pconvert(subpath)
636 normsubpath = util.pconvert(subpath)
640
637
641 # XXX: Checking against the current working copy is wrong in
638 # XXX: Checking against the current working copy is wrong in
642 # the sense that it can reject things like
639 # the sense that it can reject things like
643 #
640 #
644 # $ hg cat -r 10 sub/x.txt
641 # $ hg cat -r 10 sub/x.txt
645 #
642 #
646 # if sub/ is no longer a subrepository in the working copy
643 # if sub/ is no longer a subrepository in the working copy
647 # parent revision.
644 # parent revision.
648 #
645 #
649 # However, it can of course also allow things that would have
646 # However, it can of course also allow things that would have
650 # been rejected before, such as the above cat command if sub/
647 # been rejected before, such as the above cat command if sub/
651 # is a subrepository now, but was a normal directory before.
648 # is a subrepository now, but was a normal directory before.
652 # The old path auditor would have rejected by mistake since it
649 # The old path auditor would have rejected by mistake since it
653 # panics when it sees sub/.hg/.
650 # panics when it sees sub/.hg/.
654 #
651 #
655 # All in all, checking against the working copy seems sensible
652 # All in all, checking against the working copy seems sensible
656 # since we want to prevent access to nested repositories on
653 # since we want to prevent access to nested repositories on
657 # the filesystem *now*.
654 # the filesystem *now*.
658 ctx = self[None]
655 ctx = self[None]
659 parts = util.splitpath(subpath)
656 parts = util.splitpath(subpath)
660 while parts:
657 while parts:
661 prefix = '/'.join(parts)
658 prefix = '/'.join(parts)
662 if prefix in ctx.substate:
659 if prefix in ctx.substate:
663 if prefix == normsubpath:
660 if prefix == normsubpath:
664 return True
661 return True
665 else:
662 else:
666 sub = ctx.sub(prefix)
663 sub = ctx.sub(prefix)
667 return sub.checknested(subpath[len(prefix) + 1:])
664 return sub.checknested(subpath[len(prefix) + 1:])
668 else:
665 else:
669 parts.pop()
666 parts.pop()
670 return False
667 return False
671
668
672 def peer(self):
669 def peer(self):
673 return localpeer(self) # not cached to avoid reference cycle
670 return localpeer(self) # not cached to avoid reference cycle
674
671
675 def unfiltered(self):
672 def unfiltered(self):
676 """Return unfiltered version of the repository
673 """Return unfiltered version of the repository
677
674
678 Intended to be overwritten by filtered repo."""
675 Intended to be overwritten by filtered repo."""
679 return self
676 return self
680
677
681 def filtered(self, name):
678 def filtered(self, name):
682 """Return a filtered version of a repository"""
679 """Return a filtered version of a repository"""
683 # Python <3.4 easily leaks types via __mro__. See
680 cls = repoview.newtype(self.unfiltered().__class__)
684 # https://bugs.python.org/issue17950. We cache dynamically
681 return cls(self, name)
685 # created types so this method doesn't leak on every
686 # invocation.
687
688 key = self.unfiltered().__class__
689 if key not in self._filteredrepotypes:
690 # Build a new type with the repoview mixin and the base
691 # class of this repo.
692 class filteredrepo(repoview.repoview, key):
693 pass
694 self._filteredrepotypes[key] = filteredrepo
695
696 return self._filteredrepotypes[key](self, name)
697
682
698 @repofilecache('bookmarks', 'bookmarks.current')
683 @repofilecache('bookmarks', 'bookmarks.current')
699 def _bookmarks(self):
684 def _bookmarks(self):
700 return bookmarks.bmstore(self)
685 return bookmarks.bmstore(self)
701
686
702 @property
687 @property
703 def _activebookmark(self):
688 def _activebookmark(self):
704 return self._bookmarks.active
689 return self._bookmarks.active
705
690
706 # _phaserevs and _phasesets depend on changelog. what we need is to
691 # _phaserevs and _phasesets depend on changelog. what we need is to
707 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
692 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
708 # can't be easily expressed in filecache mechanism.
693 # can't be easily expressed in filecache mechanism.
709 @storecache('phaseroots', '00changelog.i')
694 @storecache('phaseroots', '00changelog.i')
710 def _phasecache(self):
695 def _phasecache(self):
711 return phases.phasecache(self, self._phasedefaults)
696 return phases.phasecache(self, self._phasedefaults)
712
697
713 @storecache('obsstore')
698 @storecache('obsstore')
714 def obsstore(self):
699 def obsstore(self):
715 return obsolete.makestore(self.ui, self)
700 return obsolete.makestore(self.ui, self)
716
701
717 @storecache('00changelog.i')
702 @storecache('00changelog.i')
718 def changelog(self):
703 def changelog(self):
719 return changelog.changelog(self.svfs,
704 return changelog.changelog(self.svfs,
720 trypending=txnutil.mayhavepending(self.root))
705 trypending=txnutil.mayhavepending(self.root))
721
706
722 def _constructmanifest(self):
707 def _constructmanifest(self):
723 # This is a temporary function while we migrate from manifest to
708 # This is a temporary function while we migrate from manifest to
724 # manifestlog. It allows bundlerepo and unionrepo to intercept the
709 # manifestlog. It allows bundlerepo and unionrepo to intercept the
725 # manifest creation.
710 # manifest creation.
726 return manifest.manifestrevlog(self.svfs)
711 return manifest.manifestrevlog(self.svfs)
727
712
728 @storecache('00manifest.i')
713 @storecache('00manifest.i')
729 def manifestlog(self):
714 def manifestlog(self):
730 return manifest.manifestlog(self.svfs, self)
715 return manifest.manifestlog(self.svfs, self)
731
716
732 @repofilecache('dirstate')
717 @repofilecache('dirstate')
733 def dirstate(self):
718 def dirstate(self):
734 sparsematchfn = lambda: sparse.matcher(self)
719 sparsematchfn = lambda: sparse.matcher(self)
735
720
736 return dirstate.dirstate(self.vfs, self.ui, self.root,
721 return dirstate.dirstate(self.vfs, self.ui, self.root,
737 self._dirstatevalidate, sparsematchfn)
722 self._dirstatevalidate, sparsematchfn)
738
723
739 def _dirstatevalidate(self, node):
724 def _dirstatevalidate(self, node):
740 try:
725 try:
741 self.changelog.rev(node)
726 self.changelog.rev(node)
742 return node
727 return node
743 except error.LookupError:
728 except error.LookupError:
744 if not self._dirstatevalidatewarned:
729 if not self._dirstatevalidatewarned:
745 self._dirstatevalidatewarned = True
730 self._dirstatevalidatewarned = True
746 self.ui.warn(_("warning: ignoring unknown"
731 self.ui.warn(_("warning: ignoring unknown"
747 " working parent %s!\n") % short(node))
732 " working parent %s!\n") % short(node))
748 return nullid
733 return nullid
749
734
750 def __getitem__(self, changeid):
735 def __getitem__(self, changeid):
751 if changeid is None:
736 if changeid is None:
752 return context.workingctx(self)
737 return context.workingctx(self)
753 if isinstance(changeid, slice):
738 if isinstance(changeid, slice):
754 # wdirrev isn't contiguous so the slice shouldn't include it
739 # wdirrev isn't contiguous so the slice shouldn't include it
755 return [context.changectx(self, i)
740 return [context.changectx(self, i)
756 for i in xrange(*changeid.indices(len(self)))
741 for i in xrange(*changeid.indices(len(self)))
757 if i not in self.changelog.filteredrevs]
742 if i not in self.changelog.filteredrevs]
758 try:
743 try:
759 return context.changectx(self, changeid)
744 return context.changectx(self, changeid)
760 except error.WdirUnsupported:
745 except error.WdirUnsupported:
761 return context.workingctx(self)
746 return context.workingctx(self)
762
747
763 def __contains__(self, changeid):
748 def __contains__(self, changeid):
764 """True if the given changeid exists
749 """True if the given changeid exists
765
750
766 error.LookupError is raised if an ambiguous node specified.
751 error.LookupError is raised if an ambiguous node specified.
767 """
752 """
768 try:
753 try:
769 self[changeid]
754 self[changeid]
770 return True
755 return True
771 except error.RepoLookupError:
756 except error.RepoLookupError:
772 return False
757 return False
773
758
774 def __nonzero__(self):
759 def __nonzero__(self):
775 return True
760 return True
776
761
777 __bool__ = __nonzero__
762 __bool__ = __nonzero__
778
763
779 def __len__(self):
764 def __len__(self):
780 return len(self.changelog)
765 return len(self.changelog)
781
766
782 def __iter__(self):
767 def __iter__(self):
783 return iter(self.changelog)
768 return iter(self.changelog)
784
769
785 def revs(self, expr, *args):
770 def revs(self, expr, *args):
786 '''Find revisions matching a revset.
771 '''Find revisions matching a revset.
787
772
788 The revset is specified as a string ``expr`` that may contain
773 The revset is specified as a string ``expr`` that may contain
789 %-formatting to escape certain types. See ``revsetlang.formatspec``.
774 %-formatting to escape certain types. See ``revsetlang.formatspec``.
790
775
791 Revset aliases from the configuration are not expanded. To expand
776 Revset aliases from the configuration are not expanded. To expand
792 user aliases, consider calling ``scmutil.revrange()`` or
777 user aliases, consider calling ``scmutil.revrange()`` or
793 ``repo.anyrevs([expr], user=True)``.
778 ``repo.anyrevs([expr], user=True)``.
794
779
795 Returns a revset.abstractsmartset, which is a list-like interface
780 Returns a revset.abstractsmartset, which is a list-like interface
796 that contains integer revisions.
781 that contains integer revisions.
797 '''
782 '''
798 expr = revsetlang.formatspec(expr, *args)
783 expr = revsetlang.formatspec(expr, *args)
799 m = revset.match(None, expr)
784 m = revset.match(None, expr)
800 return m(self)
785 return m(self)
801
786
802 def set(self, expr, *args):
787 def set(self, expr, *args):
803 '''Find revisions matching a revset and emit changectx instances.
788 '''Find revisions matching a revset and emit changectx instances.
804
789
805 This is a convenience wrapper around ``revs()`` that iterates the
790 This is a convenience wrapper around ``revs()`` that iterates the
806 result and is a generator of changectx instances.
791 result and is a generator of changectx instances.
807
792
808 Revset aliases from the configuration are not expanded. To expand
793 Revset aliases from the configuration are not expanded. To expand
809 user aliases, consider calling ``scmutil.revrange()``.
794 user aliases, consider calling ``scmutil.revrange()``.
810 '''
795 '''
811 for r in self.revs(expr, *args):
796 for r in self.revs(expr, *args):
812 yield self[r]
797 yield self[r]
813
798
814 def anyrevs(self, specs, user=False, localalias=None):
799 def anyrevs(self, specs, user=False, localalias=None):
815 '''Find revisions matching one of the given revsets.
800 '''Find revisions matching one of the given revsets.
816
801
817 Revset aliases from the configuration are not expanded by default. To
802 Revset aliases from the configuration are not expanded by default. To
818 expand user aliases, specify ``user=True``. To provide some local
803 expand user aliases, specify ``user=True``. To provide some local
819 definitions overriding user aliases, set ``localalias`` to
804 definitions overriding user aliases, set ``localalias`` to
820 ``{name: definitionstring}``.
805 ``{name: definitionstring}``.
821 '''
806 '''
822 if user:
807 if user:
823 m = revset.matchany(self.ui, specs, repo=self,
808 m = revset.matchany(self.ui, specs, repo=self,
824 localalias=localalias)
809 localalias=localalias)
825 else:
810 else:
826 m = revset.matchany(None, specs, localalias=localalias)
811 m = revset.matchany(None, specs, localalias=localalias)
827 return m(self)
812 return m(self)
828
813
829 def url(self):
814 def url(self):
830 return 'file:' + self.root
815 return 'file:' + self.root
831
816
832 def hook(self, name, throw=False, **args):
817 def hook(self, name, throw=False, **args):
833 """Call a hook, passing this repo instance.
818 """Call a hook, passing this repo instance.
834
819
835 This a convenience method to aid invoking hooks. Extensions likely
820 This a convenience method to aid invoking hooks. Extensions likely
836 won't call this unless they have registered a custom hook or are
821 won't call this unless they have registered a custom hook or are
837 replacing code that is expected to call a hook.
822 replacing code that is expected to call a hook.
838 """
823 """
839 return hook.hook(self.ui, self, name, throw, **args)
824 return hook.hook(self.ui, self, name, throw, **args)
840
825
841 @filteredpropertycache
826 @filteredpropertycache
842 def _tagscache(self):
827 def _tagscache(self):
843 '''Returns a tagscache object that contains various tags related
828 '''Returns a tagscache object that contains various tags related
844 caches.'''
829 caches.'''
845
830
846 # This simplifies its cache management by having one decorated
831 # This simplifies its cache management by having one decorated
847 # function (this one) and the rest simply fetch things from it.
832 # function (this one) and the rest simply fetch things from it.
848 class tagscache(object):
833 class tagscache(object):
849 def __init__(self):
834 def __init__(self):
850 # These two define the set of tags for this repository. tags
835 # These two define the set of tags for this repository. tags
851 # maps tag name to node; tagtypes maps tag name to 'global' or
836 # maps tag name to node; tagtypes maps tag name to 'global' or
852 # 'local'. (Global tags are defined by .hgtags across all
837 # 'local'. (Global tags are defined by .hgtags across all
853 # heads, and local tags are defined in .hg/localtags.)
838 # heads, and local tags are defined in .hg/localtags.)
854 # They constitute the in-memory cache of tags.
839 # They constitute the in-memory cache of tags.
855 self.tags = self.tagtypes = None
840 self.tags = self.tagtypes = None
856
841
857 self.nodetagscache = self.tagslist = None
842 self.nodetagscache = self.tagslist = None
858
843
859 cache = tagscache()
844 cache = tagscache()
860 cache.tags, cache.tagtypes = self._findtags()
845 cache.tags, cache.tagtypes = self._findtags()
861
846
862 return cache
847 return cache
863
848
864 def tags(self):
849 def tags(self):
865 '''return a mapping of tag to node'''
850 '''return a mapping of tag to node'''
866 t = {}
851 t = {}
867 if self.changelog.filteredrevs:
852 if self.changelog.filteredrevs:
868 tags, tt = self._findtags()
853 tags, tt = self._findtags()
869 else:
854 else:
870 tags = self._tagscache.tags
855 tags = self._tagscache.tags
871 for k, v in tags.iteritems():
856 for k, v in tags.iteritems():
872 try:
857 try:
873 # ignore tags to unknown nodes
858 # ignore tags to unknown nodes
874 self.changelog.rev(v)
859 self.changelog.rev(v)
875 t[k] = v
860 t[k] = v
876 except (error.LookupError, ValueError):
861 except (error.LookupError, ValueError):
877 pass
862 pass
878 return t
863 return t
879
864
880 def _findtags(self):
865 def _findtags(self):
881 '''Do the hard work of finding tags. Return a pair of dicts
866 '''Do the hard work of finding tags. Return a pair of dicts
882 (tags, tagtypes) where tags maps tag name to node, and tagtypes
867 (tags, tagtypes) where tags maps tag name to node, and tagtypes
883 maps tag name to a string like \'global\' or \'local\'.
868 maps tag name to a string like \'global\' or \'local\'.
884 Subclasses or extensions are free to add their own tags, but
869 Subclasses or extensions are free to add their own tags, but
885 should be aware that the returned dicts will be retained for the
870 should be aware that the returned dicts will be retained for the
886 duration of the localrepo object.'''
871 duration of the localrepo object.'''
887
872
888 # XXX what tagtype should subclasses/extensions use? Currently
873 # XXX what tagtype should subclasses/extensions use? Currently
889 # mq and bookmarks add tags, but do not set the tagtype at all.
874 # mq and bookmarks add tags, but do not set the tagtype at all.
890 # Should each extension invent its own tag type? Should there
875 # Should each extension invent its own tag type? Should there
891 # be one tagtype for all such "virtual" tags? Or is the status
876 # be one tagtype for all such "virtual" tags? Or is the status
892 # quo fine?
877 # quo fine?
893
878
894
879
895 # map tag name to (node, hist)
880 # map tag name to (node, hist)
896 alltags = tagsmod.findglobaltags(self.ui, self)
881 alltags = tagsmod.findglobaltags(self.ui, self)
897 # map tag name to tag type
882 # map tag name to tag type
898 tagtypes = dict((tag, 'global') for tag in alltags)
883 tagtypes = dict((tag, 'global') for tag in alltags)
899
884
900 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
885 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
901
886
902 # Build the return dicts. Have to re-encode tag names because
887 # Build the return dicts. Have to re-encode tag names because
903 # the tags module always uses UTF-8 (in order not to lose info
888 # the tags module always uses UTF-8 (in order not to lose info
904 # writing to the cache), but the rest of Mercurial wants them in
889 # writing to the cache), but the rest of Mercurial wants them in
905 # local encoding.
890 # local encoding.
906 tags = {}
891 tags = {}
907 for (name, (node, hist)) in alltags.iteritems():
892 for (name, (node, hist)) in alltags.iteritems():
908 if node != nullid:
893 if node != nullid:
909 tags[encoding.tolocal(name)] = node
894 tags[encoding.tolocal(name)] = node
910 tags['tip'] = self.changelog.tip()
895 tags['tip'] = self.changelog.tip()
911 tagtypes = dict([(encoding.tolocal(name), value)
896 tagtypes = dict([(encoding.tolocal(name), value)
912 for (name, value) in tagtypes.iteritems()])
897 for (name, value) in tagtypes.iteritems()])
913 return (tags, tagtypes)
898 return (tags, tagtypes)
914
899
915 def tagtype(self, tagname):
900 def tagtype(self, tagname):
916 '''
901 '''
917 return the type of the given tag. result can be:
902 return the type of the given tag. result can be:
918
903
919 'local' : a local tag
904 'local' : a local tag
920 'global' : a global tag
905 'global' : a global tag
921 None : tag does not exist
906 None : tag does not exist
922 '''
907 '''
923
908
924 return self._tagscache.tagtypes.get(tagname)
909 return self._tagscache.tagtypes.get(tagname)
925
910
926 def tagslist(self):
911 def tagslist(self):
927 '''return a list of tags ordered by revision'''
912 '''return a list of tags ordered by revision'''
928 if not self._tagscache.tagslist:
913 if not self._tagscache.tagslist:
929 l = []
914 l = []
930 for t, n in self.tags().iteritems():
915 for t, n in self.tags().iteritems():
931 l.append((self.changelog.rev(n), t, n))
916 l.append((self.changelog.rev(n), t, n))
932 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
917 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
933
918
934 return self._tagscache.tagslist
919 return self._tagscache.tagslist
935
920
936 def nodetags(self, node):
921 def nodetags(self, node):
937 '''return the tags associated with a node'''
922 '''return the tags associated with a node'''
938 if not self._tagscache.nodetagscache:
923 if not self._tagscache.nodetagscache:
939 nodetagscache = {}
924 nodetagscache = {}
940 for t, n in self._tagscache.tags.iteritems():
925 for t, n in self._tagscache.tags.iteritems():
941 nodetagscache.setdefault(n, []).append(t)
926 nodetagscache.setdefault(n, []).append(t)
942 for tags in nodetagscache.itervalues():
927 for tags in nodetagscache.itervalues():
943 tags.sort()
928 tags.sort()
944 self._tagscache.nodetagscache = nodetagscache
929 self._tagscache.nodetagscache = nodetagscache
945 return self._tagscache.nodetagscache.get(node, [])
930 return self._tagscache.nodetagscache.get(node, [])
946
931
947 def nodebookmarks(self, node):
932 def nodebookmarks(self, node):
948 """return the list of bookmarks pointing to the specified node"""
933 """return the list of bookmarks pointing to the specified node"""
949 marks = []
934 marks = []
950 for bookmark, n in self._bookmarks.iteritems():
935 for bookmark, n in self._bookmarks.iteritems():
951 if n == node:
936 if n == node:
952 marks.append(bookmark)
937 marks.append(bookmark)
953 return sorted(marks)
938 return sorted(marks)
954
939
955 def branchmap(self):
940 def branchmap(self):
956 '''returns a dictionary {branch: [branchheads]} with branchheads
941 '''returns a dictionary {branch: [branchheads]} with branchheads
957 ordered by increasing revision number'''
942 ordered by increasing revision number'''
958 branchmap.updatecache(self)
943 branchmap.updatecache(self)
959 return self._branchcaches[self.filtername]
944 return self._branchcaches[self.filtername]
960
945
961 @unfilteredmethod
946 @unfilteredmethod
962 def revbranchcache(self):
947 def revbranchcache(self):
963 if not self._revbranchcache:
948 if not self._revbranchcache:
964 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
949 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
965 return self._revbranchcache
950 return self._revbranchcache
966
951
967 def branchtip(self, branch, ignoremissing=False):
952 def branchtip(self, branch, ignoremissing=False):
968 '''return the tip node for a given branch
953 '''return the tip node for a given branch
969
954
970 If ignoremissing is True, then this method will not raise an error.
955 If ignoremissing is True, then this method will not raise an error.
971 This is helpful for callers that only expect None for a missing branch
956 This is helpful for callers that only expect None for a missing branch
972 (e.g. namespace).
957 (e.g. namespace).
973
958
974 '''
959 '''
975 try:
960 try:
976 return self.branchmap().branchtip(branch)
961 return self.branchmap().branchtip(branch)
977 except KeyError:
962 except KeyError:
978 if not ignoremissing:
963 if not ignoremissing:
979 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
964 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
980 else:
965 else:
981 pass
966 pass
982
967
983 def lookup(self, key):
968 def lookup(self, key):
984 return self[key].node()
969 return self[key].node()
985
970
986 def lookupbranch(self, key, remote=None):
971 def lookupbranch(self, key, remote=None):
987 repo = remote or self
972 repo = remote or self
988 if key in repo.branchmap():
973 if key in repo.branchmap():
989 return key
974 return key
990
975
991 repo = (remote and remote.local()) and remote or self
976 repo = (remote and remote.local()) and remote or self
992 return repo[key].branch()
977 return repo[key].branch()
993
978
994 def known(self, nodes):
979 def known(self, nodes):
995 cl = self.changelog
980 cl = self.changelog
996 nm = cl.nodemap
981 nm = cl.nodemap
997 filtered = cl.filteredrevs
982 filtered = cl.filteredrevs
998 result = []
983 result = []
999 for n in nodes:
984 for n in nodes:
1000 r = nm.get(n)
985 r = nm.get(n)
1001 resp = not (r is None or r in filtered)
986 resp = not (r is None or r in filtered)
1002 result.append(resp)
987 result.append(resp)
1003 return result
988 return result
1004
989
1005 def local(self):
990 def local(self):
1006 return self
991 return self
1007
992
1008 def publishing(self):
993 def publishing(self):
1009 # it's safe (and desirable) to trust the publish flag unconditionally
994 # it's safe (and desirable) to trust the publish flag unconditionally
1010 # so that we don't finalize changes shared between users via ssh or nfs
995 # so that we don't finalize changes shared between users via ssh or nfs
1011 return self.ui.configbool('phases', 'publish', untrusted=True)
996 return self.ui.configbool('phases', 'publish', untrusted=True)
1012
997
1013 def cancopy(self):
998 def cancopy(self):
1014 # so statichttprepo's override of local() works
999 # so statichttprepo's override of local() works
1015 if not self.local():
1000 if not self.local():
1016 return False
1001 return False
1017 if not self.publishing():
1002 if not self.publishing():
1018 return True
1003 return True
1019 # if publishing we can't copy if there is filtered content
1004 # if publishing we can't copy if there is filtered content
1020 return not self.filtered('visible').changelog.filteredrevs
1005 return not self.filtered('visible').changelog.filteredrevs
1021
1006
1022 def shared(self):
1007 def shared(self):
1023 '''the type of shared repository (None if not shared)'''
1008 '''the type of shared repository (None if not shared)'''
1024 if self.sharedpath != self.path:
1009 if self.sharedpath != self.path:
1025 return 'store'
1010 return 'store'
1026 return None
1011 return None
1027
1012
1028 def wjoin(self, f, *insidef):
1013 def wjoin(self, f, *insidef):
1029 return self.vfs.reljoin(self.root, f, *insidef)
1014 return self.vfs.reljoin(self.root, f, *insidef)
1030
1015
1031 def file(self, f):
1016 def file(self, f):
1032 if f[0] == '/':
1017 if f[0] == '/':
1033 f = f[1:]
1018 f = f[1:]
1034 return filelog.filelog(self.svfs, f)
1019 return filelog.filelog(self.svfs, f)
1035
1020
1036 def changectx(self, changeid):
1021 def changectx(self, changeid):
1037 return self[changeid]
1022 return self[changeid]
1038
1023
1039 def setparents(self, p1, p2=nullid):
1024 def setparents(self, p1, p2=nullid):
1040 with self.dirstate.parentchange():
1025 with self.dirstate.parentchange():
1041 copies = self.dirstate.setparents(p1, p2)
1026 copies = self.dirstate.setparents(p1, p2)
1042 pctx = self[p1]
1027 pctx = self[p1]
1043 if copies:
1028 if copies:
1044 # Adjust copy records, the dirstate cannot do it, it
1029 # Adjust copy records, the dirstate cannot do it, it
1045 # requires access to parents manifests. Preserve them
1030 # requires access to parents manifests. Preserve them
1046 # only for entries added to first parent.
1031 # only for entries added to first parent.
1047 for f in copies:
1032 for f in copies:
1048 if f not in pctx and copies[f] in pctx:
1033 if f not in pctx and copies[f] in pctx:
1049 self.dirstate.copy(copies[f], f)
1034 self.dirstate.copy(copies[f], f)
1050 if p2 == nullid:
1035 if p2 == nullid:
1051 for f, s in sorted(self.dirstate.copies().items()):
1036 for f, s in sorted(self.dirstate.copies().items()):
1052 if f not in pctx and s not in pctx:
1037 if f not in pctx and s not in pctx:
1053 self.dirstate.copy(None, f)
1038 self.dirstate.copy(None, f)
1054
1039
1055 def filectx(self, path, changeid=None, fileid=None):
1040 def filectx(self, path, changeid=None, fileid=None):
1056 """changeid can be a changeset revision, node, or tag.
1041 """changeid can be a changeset revision, node, or tag.
1057 fileid can be a file revision or node."""
1042 fileid can be a file revision or node."""
1058 return context.filectx(self, path, changeid, fileid)
1043 return context.filectx(self, path, changeid, fileid)
1059
1044
1060 def getcwd(self):
1045 def getcwd(self):
1061 return self.dirstate.getcwd()
1046 return self.dirstate.getcwd()
1062
1047
1063 def pathto(self, f, cwd=None):
1048 def pathto(self, f, cwd=None):
1064 return self.dirstate.pathto(f, cwd)
1049 return self.dirstate.pathto(f, cwd)
1065
1050
1066 def _loadfilter(self, filter):
1051 def _loadfilter(self, filter):
1067 if filter not in self.filterpats:
1052 if filter not in self.filterpats:
1068 l = []
1053 l = []
1069 for pat, cmd in self.ui.configitems(filter):
1054 for pat, cmd in self.ui.configitems(filter):
1070 if cmd == '!':
1055 if cmd == '!':
1071 continue
1056 continue
1072 mf = matchmod.match(self.root, '', [pat])
1057 mf = matchmod.match(self.root, '', [pat])
1073 fn = None
1058 fn = None
1074 params = cmd
1059 params = cmd
1075 for name, filterfn in self._datafilters.iteritems():
1060 for name, filterfn in self._datafilters.iteritems():
1076 if cmd.startswith(name):
1061 if cmd.startswith(name):
1077 fn = filterfn
1062 fn = filterfn
1078 params = cmd[len(name):].lstrip()
1063 params = cmd[len(name):].lstrip()
1079 break
1064 break
1080 if not fn:
1065 if not fn:
1081 fn = lambda s, c, **kwargs: util.filter(s, c)
1066 fn = lambda s, c, **kwargs: util.filter(s, c)
1082 # Wrap old filters not supporting keyword arguments
1067 # Wrap old filters not supporting keyword arguments
1083 if not inspect.getargspec(fn)[2]:
1068 if not inspect.getargspec(fn)[2]:
1084 oldfn = fn
1069 oldfn = fn
1085 fn = lambda s, c, **kwargs: oldfn(s, c)
1070 fn = lambda s, c, **kwargs: oldfn(s, c)
1086 l.append((mf, fn, params))
1071 l.append((mf, fn, params))
1087 self.filterpats[filter] = l
1072 self.filterpats[filter] = l
1088 return self.filterpats[filter]
1073 return self.filterpats[filter]
1089
1074
1090 def _filter(self, filterpats, filename, data):
1075 def _filter(self, filterpats, filename, data):
1091 for mf, fn, cmd in filterpats:
1076 for mf, fn, cmd in filterpats:
1092 if mf(filename):
1077 if mf(filename):
1093 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1078 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1094 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1079 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1095 break
1080 break
1096
1081
1097 return data
1082 return data
1098
1083
1099 @unfilteredpropertycache
1084 @unfilteredpropertycache
1100 def _encodefilterpats(self):
1085 def _encodefilterpats(self):
1101 return self._loadfilter('encode')
1086 return self._loadfilter('encode')
1102
1087
1103 @unfilteredpropertycache
1088 @unfilteredpropertycache
1104 def _decodefilterpats(self):
1089 def _decodefilterpats(self):
1105 return self._loadfilter('decode')
1090 return self._loadfilter('decode')
1106
1091
1107 def adddatafilter(self, name, filter):
1092 def adddatafilter(self, name, filter):
1108 self._datafilters[name] = filter
1093 self._datafilters[name] = filter
1109
1094
1110 def wread(self, filename):
1095 def wread(self, filename):
1111 if self.wvfs.islink(filename):
1096 if self.wvfs.islink(filename):
1112 data = self.wvfs.readlink(filename)
1097 data = self.wvfs.readlink(filename)
1113 else:
1098 else:
1114 data = self.wvfs.read(filename)
1099 data = self.wvfs.read(filename)
1115 return self._filter(self._encodefilterpats, filename, data)
1100 return self._filter(self._encodefilterpats, filename, data)
1116
1101
1117 def wwrite(self, filename, data, flags, backgroundclose=False):
1102 def wwrite(self, filename, data, flags, backgroundclose=False):
1118 """write ``data`` into ``filename`` in the working directory
1103 """write ``data`` into ``filename`` in the working directory
1119
1104
1120 This returns length of written (maybe decoded) data.
1105 This returns length of written (maybe decoded) data.
1121 """
1106 """
1122 data = self._filter(self._decodefilterpats, filename, data)
1107 data = self._filter(self._decodefilterpats, filename, data)
1123 if 'l' in flags:
1108 if 'l' in flags:
1124 self.wvfs.symlink(data, filename)
1109 self.wvfs.symlink(data, filename)
1125 else:
1110 else:
1126 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1111 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1127 if 'x' in flags:
1112 if 'x' in flags:
1128 self.wvfs.setflags(filename, False, True)
1113 self.wvfs.setflags(filename, False, True)
1129 return len(data)
1114 return len(data)
1130
1115
1131 def wwritedata(self, filename, data):
1116 def wwritedata(self, filename, data):
1132 return self._filter(self._decodefilterpats, filename, data)
1117 return self._filter(self._decodefilterpats, filename, data)
1133
1118
1134 def currenttransaction(self):
1119 def currenttransaction(self):
1135 """return the current transaction or None if non exists"""
1120 """return the current transaction or None if non exists"""
1136 if self._transref:
1121 if self._transref:
1137 tr = self._transref()
1122 tr = self._transref()
1138 else:
1123 else:
1139 tr = None
1124 tr = None
1140
1125
1141 if tr and tr.running():
1126 if tr and tr.running():
1142 return tr
1127 return tr
1143 return None
1128 return None
1144
1129
1145 def transaction(self, desc, report=None):
1130 def transaction(self, desc, report=None):
1146 if (self.ui.configbool('devel', 'all-warnings')
1131 if (self.ui.configbool('devel', 'all-warnings')
1147 or self.ui.configbool('devel', 'check-locks')):
1132 or self.ui.configbool('devel', 'check-locks')):
1148 if self._currentlock(self._lockref) is None:
1133 if self._currentlock(self._lockref) is None:
1149 raise error.ProgrammingError('transaction requires locking')
1134 raise error.ProgrammingError('transaction requires locking')
1150 tr = self.currenttransaction()
1135 tr = self.currenttransaction()
1151 if tr is not None:
1136 if tr is not None:
1152 scmutil.registersummarycallback(self, tr, desc)
1137 scmutil.registersummarycallback(self, tr, desc)
1153 return tr.nest()
1138 return tr.nest()
1154
1139
1155 # abort here if the journal already exists
1140 # abort here if the journal already exists
1156 if self.svfs.exists("journal"):
1141 if self.svfs.exists("journal"):
1157 raise error.RepoError(
1142 raise error.RepoError(
1158 _("abandoned transaction found"),
1143 _("abandoned transaction found"),
1159 hint=_("run 'hg recover' to clean up transaction"))
1144 hint=_("run 'hg recover' to clean up transaction"))
1160
1145
1161 idbase = "%.40f#%f" % (random.random(), time.time())
1146 idbase = "%.40f#%f" % (random.random(), time.time())
1162 ha = hex(hashlib.sha1(idbase).digest())
1147 ha = hex(hashlib.sha1(idbase).digest())
1163 txnid = 'TXN:' + ha
1148 txnid = 'TXN:' + ha
1164 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1149 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1165
1150
1166 self._writejournal(desc)
1151 self._writejournal(desc)
1167 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1152 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1168 if report:
1153 if report:
1169 rp = report
1154 rp = report
1170 else:
1155 else:
1171 rp = self.ui.warn
1156 rp = self.ui.warn
1172 vfsmap = {'plain': self.vfs} # root of .hg/
1157 vfsmap = {'plain': self.vfs} # root of .hg/
1173 # we must avoid cyclic reference between repo and transaction.
1158 # we must avoid cyclic reference between repo and transaction.
1174 reporef = weakref.ref(self)
1159 reporef = weakref.ref(self)
1175 # Code to track tag movement
1160 # Code to track tag movement
1176 #
1161 #
1177 # Since tags are all handled as file content, it is actually quite hard
1162 # Since tags are all handled as file content, it is actually quite hard
1178 # to track these movement from a code perspective. So we fallback to a
1163 # to track these movement from a code perspective. So we fallback to a
1179 # tracking at the repository level. One could envision to track changes
1164 # tracking at the repository level. One could envision to track changes
1180 # to the '.hgtags' file through changegroup apply but that fails to
1165 # to the '.hgtags' file through changegroup apply but that fails to
1181 # cope with case where transaction expose new heads without changegroup
1166 # cope with case where transaction expose new heads without changegroup
1182 # being involved (eg: phase movement).
1167 # being involved (eg: phase movement).
1183 #
1168 #
1184 # For now, We gate the feature behind a flag since this likely comes
1169 # For now, We gate the feature behind a flag since this likely comes
1185 # with performance impacts. The current code run more often than needed
1170 # with performance impacts. The current code run more often than needed
1186 # and do not use caches as much as it could. The current focus is on
1171 # and do not use caches as much as it could. The current focus is on
1187 # the behavior of the feature so we disable it by default. The flag
1172 # the behavior of the feature so we disable it by default. The flag
1188 # will be removed when we are happy with the performance impact.
1173 # will be removed when we are happy with the performance impact.
1189 #
1174 #
1190 # Once this feature is no longer experimental move the following
1175 # Once this feature is no longer experimental move the following
1191 # documentation to the appropriate help section:
1176 # documentation to the appropriate help section:
1192 #
1177 #
1193 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1178 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1194 # tags (new or changed or deleted tags). In addition the details of
1179 # tags (new or changed or deleted tags). In addition the details of
1195 # these changes are made available in a file at:
1180 # these changes are made available in a file at:
1196 # ``REPOROOT/.hg/changes/tags.changes``.
1181 # ``REPOROOT/.hg/changes/tags.changes``.
1197 # Make sure you check for HG_TAG_MOVED before reading that file as it
1182 # Make sure you check for HG_TAG_MOVED before reading that file as it
1198 # might exist from a previous transaction even if no tag were touched
1183 # might exist from a previous transaction even if no tag were touched
1199 # in this one. Changes are recorded in a line base format::
1184 # in this one. Changes are recorded in a line base format::
1200 #
1185 #
1201 # <action> <hex-node> <tag-name>\n
1186 # <action> <hex-node> <tag-name>\n
1202 #
1187 #
1203 # Actions are defined as follow:
1188 # Actions are defined as follow:
1204 # "-R": tag is removed,
1189 # "-R": tag is removed,
1205 # "+A": tag is added,
1190 # "+A": tag is added,
1206 # "-M": tag is moved (old value),
1191 # "-M": tag is moved (old value),
1207 # "+M": tag is moved (new value),
1192 # "+M": tag is moved (new value),
1208 tracktags = lambda x: None
1193 tracktags = lambda x: None
1209 # experimental config: experimental.hook-track-tags
1194 # experimental config: experimental.hook-track-tags
1210 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1195 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1211 if desc != 'strip' and shouldtracktags:
1196 if desc != 'strip' and shouldtracktags:
1212 oldheads = self.changelog.headrevs()
1197 oldheads = self.changelog.headrevs()
1213 def tracktags(tr2):
1198 def tracktags(tr2):
1214 repo = reporef()
1199 repo = reporef()
1215 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1200 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1216 newheads = repo.changelog.headrevs()
1201 newheads = repo.changelog.headrevs()
1217 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1202 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1218 # notes: we compare lists here.
1203 # notes: we compare lists here.
1219 # As we do it only once buiding set would not be cheaper
1204 # As we do it only once buiding set would not be cheaper
1220 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1205 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1221 if changes:
1206 if changes:
1222 tr2.hookargs['tag_moved'] = '1'
1207 tr2.hookargs['tag_moved'] = '1'
1223 with repo.vfs('changes/tags.changes', 'w',
1208 with repo.vfs('changes/tags.changes', 'w',
1224 atomictemp=True) as changesfile:
1209 atomictemp=True) as changesfile:
1225 # note: we do not register the file to the transaction
1210 # note: we do not register the file to the transaction
1226 # because we needs it to still exist on the transaction
1211 # because we needs it to still exist on the transaction
1227 # is close (for txnclose hooks)
1212 # is close (for txnclose hooks)
1228 tagsmod.writediff(changesfile, changes)
1213 tagsmod.writediff(changesfile, changes)
1229 def validate(tr2):
1214 def validate(tr2):
1230 """will run pre-closing hooks"""
1215 """will run pre-closing hooks"""
1231 # XXX the transaction API is a bit lacking here so we take a hacky
1216 # XXX the transaction API is a bit lacking here so we take a hacky
1232 # path for now
1217 # path for now
1233 #
1218 #
1234 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1219 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1235 # dict is copied before these run. In addition we needs the data
1220 # dict is copied before these run. In addition we needs the data
1236 # available to in memory hooks too.
1221 # available to in memory hooks too.
1237 #
1222 #
1238 # Moreover, we also need to make sure this runs before txnclose
1223 # Moreover, we also need to make sure this runs before txnclose
1239 # hooks and there is no "pending" mechanism that would execute
1224 # hooks and there is no "pending" mechanism that would execute
1240 # logic only if hooks are about to run.
1225 # logic only if hooks are about to run.
1241 #
1226 #
1242 # Fixing this limitation of the transaction is also needed to track
1227 # Fixing this limitation of the transaction is also needed to track
1243 # other families of changes (bookmarks, phases, obsolescence).
1228 # other families of changes (bookmarks, phases, obsolescence).
1244 #
1229 #
1245 # This will have to be fixed before we remove the experimental
1230 # This will have to be fixed before we remove the experimental
1246 # gating.
1231 # gating.
1247 tracktags(tr2)
1232 tracktags(tr2)
1248 repo = reporef()
1233 repo = reporef()
1249 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1234 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1250 scmutil.enforcesinglehead(repo, tr2, desc)
1235 scmutil.enforcesinglehead(repo, tr2, desc)
1251 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1236 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1252 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1237 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1253 args = tr.hookargs.copy()
1238 args = tr.hookargs.copy()
1254 args.update(bookmarks.preparehookargs(name, old, new))
1239 args.update(bookmarks.preparehookargs(name, old, new))
1255 repo.hook('pretxnclose-bookmark', throw=True,
1240 repo.hook('pretxnclose-bookmark', throw=True,
1256 txnname=desc,
1241 txnname=desc,
1257 **pycompat.strkwargs(args))
1242 **pycompat.strkwargs(args))
1258 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1243 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1259 cl = repo.unfiltered().changelog
1244 cl = repo.unfiltered().changelog
1260 for rev, (old, new) in tr.changes['phases'].items():
1245 for rev, (old, new) in tr.changes['phases'].items():
1261 args = tr.hookargs.copy()
1246 args = tr.hookargs.copy()
1262 node = hex(cl.node(rev))
1247 node = hex(cl.node(rev))
1263 args.update(phases.preparehookargs(node, old, new))
1248 args.update(phases.preparehookargs(node, old, new))
1264 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1249 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1265 **pycompat.strkwargs(args))
1250 **pycompat.strkwargs(args))
1266
1251
1267 repo.hook('pretxnclose', throw=True,
1252 repo.hook('pretxnclose', throw=True,
1268 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1253 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1269 def releasefn(tr, success):
1254 def releasefn(tr, success):
1270 repo = reporef()
1255 repo = reporef()
1271 if success:
1256 if success:
1272 # this should be explicitly invoked here, because
1257 # this should be explicitly invoked here, because
1273 # in-memory changes aren't written out at closing
1258 # in-memory changes aren't written out at closing
1274 # transaction, if tr.addfilegenerator (via
1259 # transaction, if tr.addfilegenerator (via
1275 # dirstate.write or so) isn't invoked while
1260 # dirstate.write or so) isn't invoked while
1276 # transaction running
1261 # transaction running
1277 repo.dirstate.write(None)
1262 repo.dirstate.write(None)
1278 else:
1263 else:
1279 # discard all changes (including ones already written
1264 # discard all changes (including ones already written
1280 # out) in this transaction
1265 # out) in this transaction
1281 repo.dirstate.restorebackup(None, 'journal.dirstate')
1266 repo.dirstate.restorebackup(None, 'journal.dirstate')
1282
1267
1283 repo.invalidate(clearfilecache=True)
1268 repo.invalidate(clearfilecache=True)
1284
1269
1285 tr = transaction.transaction(rp, self.svfs, vfsmap,
1270 tr = transaction.transaction(rp, self.svfs, vfsmap,
1286 "journal",
1271 "journal",
1287 "undo",
1272 "undo",
1288 aftertrans(renames),
1273 aftertrans(renames),
1289 self.store.createmode,
1274 self.store.createmode,
1290 validator=validate,
1275 validator=validate,
1291 releasefn=releasefn,
1276 releasefn=releasefn,
1292 checkambigfiles=_cachedfiles)
1277 checkambigfiles=_cachedfiles)
1293 tr.changes['revs'] = set()
1278 tr.changes['revs'] = set()
1294 tr.changes['obsmarkers'] = set()
1279 tr.changes['obsmarkers'] = set()
1295 tr.changes['phases'] = {}
1280 tr.changes['phases'] = {}
1296 tr.changes['bookmarks'] = {}
1281 tr.changes['bookmarks'] = {}
1297
1282
1298 tr.hookargs['txnid'] = txnid
1283 tr.hookargs['txnid'] = txnid
1299 # note: writing the fncache only during finalize mean that the file is
1284 # note: writing the fncache only during finalize mean that the file is
1300 # outdated when running hooks. As fncache is used for streaming clone,
1285 # outdated when running hooks. As fncache is used for streaming clone,
1301 # this is not expected to break anything that happen during the hooks.
1286 # this is not expected to break anything that happen during the hooks.
1302 tr.addfinalize('flush-fncache', self.store.write)
1287 tr.addfinalize('flush-fncache', self.store.write)
1303 def txnclosehook(tr2):
1288 def txnclosehook(tr2):
1304 """To be run if transaction is successful, will schedule a hook run
1289 """To be run if transaction is successful, will schedule a hook run
1305 """
1290 """
1306 # Don't reference tr2 in hook() so we don't hold a reference.
1291 # Don't reference tr2 in hook() so we don't hold a reference.
1307 # This reduces memory consumption when there are multiple
1292 # This reduces memory consumption when there are multiple
1308 # transactions per lock. This can likely go away if issue5045
1293 # transactions per lock. This can likely go away if issue5045
1309 # fixes the function accumulation.
1294 # fixes the function accumulation.
1310 hookargs = tr2.hookargs
1295 hookargs = tr2.hookargs
1311
1296
1312 def hookfunc():
1297 def hookfunc():
1313 repo = reporef()
1298 repo = reporef()
1314 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1299 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1315 bmchanges = sorted(tr.changes['bookmarks'].items())
1300 bmchanges = sorted(tr.changes['bookmarks'].items())
1316 for name, (old, new) in bmchanges:
1301 for name, (old, new) in bmchanges:
1317 args = tr.hookargs.copy()
1302 args = tr.hookargs.copy()
1318 args.update(bookmarks.preparehookargs(name, old, new))
1303 args.update(bookmarks.preparehookargs(name, old, new))
1319 repo.hook('txnclose-bookmark', throw=False,
1304 repo.hook('txnclose-bookmark', throw=False,
1320 txnname=desc, **pycompat.strkwargs(args))
1305 txnname=desc, **pycompat.strkwargs(args))
1321
1306
1322 if hook.hashook(repo.ui, 'txnclose-phase'):
1307 if hook.hashook(repo.ui, 'txnclose-phase'):
1323 cl = repo.unfiltered().changelog
1308 cl = repo.unfiltered().changelog
1324 phasemv = sorted(tr.changes['phases'].items())
1309 phasemv = sorted(tr.changes['phases'].items())
1325 for rev, (old, new) in phasemv:
1310 for rev, (old, new) in phasemv:
1326 args = tr.hookargs.copy()
1311 args = tr.hookargs.copy()
1327 node = hex(cl.node(rev))
1312 node = hex(cl.node(rev))
1328 args.update(phases.preparehookargs(node, old, new))
1313 args.update(phases.preparehookargs(node, old, new))
1329 repo.hook('txnclose-phase', throw=False, txnname=desc,
1314 repo.hook('txnclose-phase', throw=False, txnname=desc,
1330 **pycompat.strkwargs(args))
1315 **pycompat.strkwargs(args))
1331
1316
1332 repo.hook('txnclose', throw=False, txnname=desc,
1317 repo.hook('txnclose', throw=False, txnname=desc,
1333 **pycompat.strkwargs(hookargs))
1318 **pycompat.strkwargs(hookargs))
1334 reporef()._afterlock(hookfunc)
1319 reporef()._afterlock(hookfunc)
1335 tr.addfinalize('txnclose-hook', txnclosehook)
1320 tr.addfinalize('txnclose-hook', txnclosehook)
1336 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1321 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1337 def txnaborthook(tr2):
1322 def txnaborthook(tr2):
1338 """To be run if transaction is aborted
1323 """To be run if transaction is aborted
1339 """
1324 """
1340 reporef().hook('txnabort', throw=False, txnname=desc,
1325 reporef().hook('txnabort', throw=False, txnname=desc,
1341 **tr2.hookargs)
1326 **tr2.hookargs)
1342 tr.addabort('txnabort-hook', txnaborthook)
1327 tr.addabort('txnabort-hook', txnaborthook)
1343 # avoid eager cache invalidation. in-memory data should be identical
1328 # avoid eager cache invalidation. in-memory data should be identical
1344 # to stored data if transaction has no error.
1329 # to stored data if transaction has no error.
1345 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1330 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1346 self._transref = weakref.ref(tr)
1331 self._transref = weakref.ref(tr)
1347 scmutil.registersummarycallback(self, tr, desc)
1332 scmutil.registersummarycallback(self, tr, desc)
1348 return tr
1333 return tr
1349
1334
1350 def _journalfiles(self):
1335 def _journalfiles(self):
1351 return ((self.svfs, 'journal'),
1336 return ((self.svfs, 'journal'),
1352 (self.vfs, 'journal.dirstate'),
1337 (self.vfs, 'journal.dirstate'),
1353 (self.vfs, 'journal.branch'),
1338 (self.vfs, 'journal.branch'),
1354 (self.vfs, 'journal.desc'),
1339 (self.vfs, 'journal.desc'),
1355 (self.vfs, 'journal.bookmarks'),
1340 (self.vfs, 'journal.bookmarks'),
1356 (self.svfs, 'journal.phaseroots'))
1341 (self.svfs, 'journal.phaseroots'))
1357
1342
1358 def undofiles(self):
1343 def undofiles(self):
1359 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1344 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1360
1345
1361 @unfilteredmethod
1346 @unfilteredmethod
1362 def _writejournal(self, desc):
1347 def _writejournal(self, desc):
1363 self.dirstate.savebackup(None, 'journal.dirstate')
1348 self.dirstate.savebackup(None, 'journal.dirstate')
1364 self.vfs.write("journal.branch",
1349 self.vfs.write("journal.branch",
1365 encoding.fromlocal(self.dirstate.branch()))
1350 encoding.fromlocal(self.dirstate.branch()))
1366 self.vfs.write("journal.desc",
1351 self.vfs.write("journal.desc",
1367 "%d\n%s\n" % (len(self), desc))
1352 "%d\n%s\n" % (len(self), desc))
1368 self.vfs.write("journal.bookmarks",
1353 self.vfs.write("journal.bookmarks",
1369 self.vfs.tryread("bookmarks"))
1354 self.vfs.tryread("bookmarks"))
1370 self.svfs.write("journal.phaseroots",
1355 self.svfs.write("journal.phaseroots",
1371 self.svfs.tryread("phaseroots"))
1356 self.svfs.tryread("phaseroots"))
1372
1357
1373 def recover(self):
1358 def recover(self):
1374 with self.lock():
1359 with self.lock():
1375 if self.svfs.exists("journal"):
1360 if self.svfs.exists("journal"):
1376 self.ui.status(_("rolling back interrupted transaction\n"))
1361 self.ui.status(_("rolling back interrupted transaction\n"))
1377 vfsmap = {'': self.svfs,
1362 vfsmap = {'': self.svfs,
1378 'plain': self.vfs,}
1363 'plain': self.vfs,}
1379 transaction.rollback(self.svfs, vfsmap, "journal",
1364 transaction.rollback(self.svfs, vfsmap, "journal",
1380 self.ui.warn,
1365 self.ui.warn,
1381 checkambigfiles=_cachedfiles)
1366 checkambigfiles=_cachedfiles)
1382 self.invalidate()
1367 self.invalidate()
1383 return True
1368 return True
1384 else:
1369 else:
1385 self.ui.warn(_("no interrupted transaction available\n"))
1370 self.ui.warn(_("no interrupted transaction available\n"))
1386 return False
1371 return False
1387
1372
1388 def rollback(self, dryrun=False, force=False):
1373 def rollback(self, dryrun=False, force=False):
1389 wlock = lock = dsguard = None
1374 wlock = lock = dsguard = None
1390 try:
1375 try:
1391 wlock = self.wlock()
1376 wlock = self.wlock()
1392 lock = self.lock()
1377 lock = self.lock()
1393 if self.svfs.exists("undo"):
1378 if self.svfs.exists("undo"):
1394 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1379 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1395
1380
1396 return self._rollback(dryrun, force, dsguard)
1381 return self._rollback(dryrun, force, dsguard)
1397 else:
1382 else:
1398 self.ui.warn(_("no rollback information available\n"))
1383 self.ui.warn(_("no rollback information available\n"))
1399 return 1
1384 return 1
1400 finally:
1385 finally:
1401 release(dsguard, lock, wlock)
1386 release(dsguard, lock, wlock)
1402
1387
1403 @unfilteredmethod # Until we get smarter cache management
1388 @unfilteredmethod # Until we get smarter cache management
1404 def _rollback(self, dryrun, force, dsguard):
1389 def _rollback(self, dryrun, force, dsguard):
1405 ui = self.ui
1390 ui = self.ui
1406 try:
1391 try:
1407 args = self.vfs.read('undo.desc').splitlines()
1392 args = self.vfs.read('undo.desc').splitlines()
1408 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1393 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1409 if len(args) >= 3:
1394 if len(args) >= 3:
1410 detail = args[2]
1395 detail = args[2]
1411 oldtip = oldlen - 1
1396 oldtip = oldlen - 1
1412
1397
1413 if detail and ui.verbose:
1398 if detail and ui.verbose:
1414 msg = (_('repository tip rolled back to revision %d'
1399 msg = (_('repository tip rolled back to revision %d'
1415 ' (undo %s: %s)\n')
1400 ' (undo %s: %s)\n')
1416 % (oldtip, desc, detail))
1401 % (oldtip, desc, detail))
1417 else:
1402 else:
1418 msg = (_('repository tip rolled back to revision %d'
1403 msg = (_('repository tip rolled back to revision %d'
1419 ' (undo %s)\n')
1404 ' (undo %s)\n')
1420 % (oldtip, desc))
1405 % (oldtip, desc))
1421 except IOError:
1406 except IOError:
1422 msg = _('rolling back unknown transaction\n')
1407 msg = _('rolling back unknown transaction\n')
1423 desc = None
1408 desc = None
1424
1409
1425 if not force and self['.'] != self['tip'] and desc == 'commit':
1410 if not force and self['.'] != self['tip'] and desc == 'commit':
1426 raise error.Abort(
1411 raise error.Abort(
1427 _('rollback of last commit while not checked out '
1412 _('rollback of last commit while not checked out '
1428 'may lose data'), hint=_('use -f to force'))
1413 'may lose data'), hint=_('use -f to force'))
1429
1414
1430 ui.status(msg)
1415 ui.status(msg)
1431 if dryrun:
1416 if dryrun:
1432 return 0
1417 return 0
1433
1418
1434 parents = self.dirstate.parents()
1419 parents = self.dirstate.parents()
1435 self.destroying()
1420 self.destroying()
1436 vfsmap = {'plain': self.vfs, '': self.svfs}
1421 vfsmap = {'plain': self.vfs, '': self.svfs}
1437 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1422 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1438 checkambigfiles=_cachedfiles)
1423 checkambigfiles=_cachedfiles)
1439 if self.vfs.exists('undo.bookmarks'):
1424 if self.vfs.exists('undo.bookmarks'):
1440 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1425 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1441 if self.svfs.exists('undo.phaseroots'):
1426 if self.svfs.exists('undo.phaseroots'):
1442 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1427 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1443 self.invalidate()
1428 self.invalidate()
1444
1429
1445 parentgone = (parents[0] not in self.changelog.nodemap or
1430 parentgone = (parents[0] not in self.changelog.nodemap or
1446 parents[1] not in self.changelog.nodemap)
1431 parents[1] not in self.changelog.nodemap)
1447 if parentgone:
1432 if parentgone:
1448 # prevent dirstateguard from overwriting already restored one
1433 # prevent dirstateguard from overwriting already restored one
1449 dsguard.close()
1434 dsguard.close()
1450
1435
1451 self.dirstate.restorebackup(None, 'undo.dirstate')
1436 self.dirstate.restorebackup(None, 'undo.dirstate')
1452 try:
1437 try:
1453 branch = self.vfs.read('undo.branch')
1438 branch = self.vfs.read('undo.branch')
1454 self.dirstate.setbranch(encoding.tolocal(branch))
1439 self.dirstate.setbranch(encoding.tolocal(branch))
1455 except IOError:
1440 except IOError:
1456 ui.warn(_('named branch could not be reset: '
1441 ui.warn(_('named branch could not be reset: '
1457 'current branch is still \'%s\'\n')
1442 'current branch is still \'%s\'\n')
1458 % self.dirstate.branch())
1443 % self.dirstate.branch())
1459
1444
1460 parents = tuple([p.rev() for p in self[None].parents()])
1445 parents = tuple([p.rev() for p in self[None].parents()])
1461 if len(parents) > 1:
1446 if len(parents) > 1:
1462 ui.status(_('working directory now based on '
1447 ui.status(_('working directory now based on '
1463 'revisions %d and %d\n') % parents)
1448 'revisions %d and %d\n') % parents)
1464 else:
1449 else:
1465 ui.status(_('working directory now based on '
1450 ui.status(_('working directory now based on '
1466 'revision %d\n') % parents)
1451 'revision %d\n') % parents)
1467 mergemod.mergestate.clean(self, self['.'].node())
1452 mergemod.mergestate.clean(self, self['.'].node())
1468
1453
1469 # TODO: if we know which new heads may result from this rollback, pass
1454 # TODO: if we know which new heads may result from this rollback, pass
1470 # them to destroy(), which will prevent the branchhead cache from being
1455 # them to destroy(), which will prevent the branchhead cache from being
1471 # invalidated.
1456 # invalidated.
1472 self.destroyed()
1457 self.destroyed()
1473 return 0
1458 return 0
1474
1459
1475 def _buildcacheupdater(self, newtransaction):
1460 def _buildcacheupdater(self, newtransaction):
1476 """called during transaction to build the callback updating cache
1461 """called during transaction to build the callback updating cache
1477
1462
1478 Lives on the repository to help extension who might want to augment
1463 Lives on the repository to help extension who might want to augment
1479 this logic. For this purpose, the created transaction is passed to the
1464 this logic. For this purpose, the created transaction is passed to the
1480 method.
1465 method.
1481 """
1466 """
1482 # we must avoid cyclic reference between repo and transaction.
1467 # we must avoid cyclic reference between repo and transaction.
1483 reporef = weakref.ref(self)
1468 reporef = weakref.ref(self)
1484 def updater(tr):
1469 def updater(tr):
1485 repo = reporef()
1470 repo = reporef()
1486 repo.updatecaches(tr)
1471 repo.updatecaches(tr)
1487 return updater
1472 return updater
1488
1473
1489 @unfilteredmethod
1474 @unfilteredmethod
1490 def updatecaches(self, tr=None):
1475 def updatecaches(self, tr=None):
1491 """warm appropriate caches
1476 """warm appropriate caches
1492
1477
1493 If this function is called after a transaction closed. The transaction
1478 If this function is called after a transaction closed. The transaction
1494 will be available in the 'tr' argument. This can be used to selectively
1479 will be available in the 'tr' argument. This can be used to selectively
1495 update caches relevant to the changes in that transaction.
1480 update caches relevant to the changes in that transaction.
1496 """
1481 """
1497 if tr is not None and tr.hookargs.get('source') == 'strip':
1482 if tr is not None and tr.hookargs.get('source') == 'strip':
1498 # During strip, many caches are invalid but
1483 # During strip, many caches are invalid but
1499 # later call to `destroyed` will refresh them.
1484 # later call to `destroyed` will refresh them.
1500 return
1485 return
1501
1486
1502 if tr is None or tr.changes['revs']:
1487 if tr is None or tr.changes['revs']:
1503 # updating the unfiltered branchmap should refresh all the others,
1488 # updating the unfiltered branchmap should refresh all the others,
1504 self.ui.debug('updating the branch cache\n')
1489 self.ui.debug('updating the branch cache\n')
1505 branchmap.updatecache(self.filtered('served'))
1490 branchmap.updatecache(self.filtered('served'))
1506
1491
1507 def invalidatecaches(self):
1492 def invalidatecaches(self):
1508
1493
1509 if '_tagscache' in vars(self):
1494 if '_tagscache' in vars(self):
1510 # can't use delattr on proxy
1495 # can't use delattr on proxy
1511 del self.__dict__['_tagscache']
1496 del self.__dict__['_tagscache']
1512
1497
1513 self.unfiltered()._branchcaches.clear()
1498 self.unfiltered()._branchcaches.clear()
1514 self.invalidatevolatilesets()
1499 self.invalidatevolatilesets()
1515 self._sparsesignaturecache.clear()
1500 self._sparsesignaturecache.clear()
1516
1501
1517 def invalidatevolatilesets(self):
1502 def invalidatevolatilesets(self):
1518 self.filteredrevcache.clear()
1503 self.filteredrevcache.clear()
1519 obsolete.clearobscaches(self)
1504 obsolete.clearobscaches(self)
1520
1505
1521 def invalidatedirstate(self):
1506 def invalidatedirstate(self):
1522 '''Invalidates the dirstate, causing the next call to dirstate
1507 '''Invalidates the dirstate, causing the next call to dirstate
1523 to check if it was modified since the last time it was read,
1508 to check if it was modified since the last time it was read,
1524 rereading it if it has.
1509 rereading it if it has.
1525
1510
1526 This is different to dirstate.invalidate() that it doesn't always
1511 This is different to dirstate.invalidate() that it doesn't always
1527 rereads the dirstate. Use dirstate.invalidate() if you want to
1512 rereads the dirstate. Use dirstate.invalidate() if you want to
1528 explicitly read the dirstate again (i.e. restoring it to a previous
1513 explicitly read the dirstate again (i.e. restoring it to a previous
1529 known good state).'''
1514 known good state).'''
1530 if hasunfilteredcache(self, 'dirstate'):
1515 if hasunfilteredcache(self, 'dirstate'):
1531 for k in self.dirstate._filecache:
1516 for k in self.dirstate._filecache:
1532 try:
1517 try:
1533 delattr(self.dirstate, k)
1518 delattr(self.dirstate, k)
1534 except AttributeError:
1519 except AttributeError:
1535 pass
1520 pass
1536 delattr(self.unfiltered(), 'dirstate')
1521 delattr(self.unfiltered(), 'dirstate')
1537
1522
1538 def invalidate(self, clearfilecache=False):
1523 def invalidate(self, clearfilecache=False):
1539 '''Invalidates both store and non-store parts other than dirstate
1524 '''Invalidates both store and non-store parts other than dirstate
1540
1525
1541 If a transaction is running, invalidation of store is omitted,
1526 If a transaction is running, invalidation of store is omitted,
1542 because discarding in-memory changes might cause inconsistency
1527 because discarding in-memory changes might cause inconsistency
1543 (e.g. incomplete fncache causes unintentional failure, but
1528 (e.g. incomplete fncache causes unintentional failure, but
1544 redundant one doesn't).
1529 redundant one doesn't).
1545 '''
1530 '''
1546 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1531 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1547 for k in list(self._filecache.keys()):
1532 for k in list(self._filecache.keys()):
1548 # dirstate is invalidated separately in invalidatedirstate()
1533 # dirstate is invalidated separately in invalidatedirstate()
1549 if k == 'dirstate':
1534 if k == 'dirstate':
1550 continue
1535 continue
1551 if (k == 'changelog' and
1536 if (k == 'changelog' and
1552 self.currenttransaction() and
1537 self.currenttransaction() and
1553 self.changelog._delayed):
1538 self.changelog._delayed):
1554 # The changelog object may store unwritten revisions. We don't
1539 # The changelog object may store unwritten revisions. We don't
1555 # want to lose them.
1540 # want to lose them.
1556 # TODO: Solve the problem instead of working around it.
1541 # TODO: Solve the problem instead of working around it.
1557 continue
1542 continue
1558
1543
1559 if clearfilecache:
1544 if clearfilecache:
1560 del self._filecache[k]
1545 del self._filecache[k]
1561 try:
1546 try:
1562 delattr(unfiltered, k)
1547 delattr(unfiltered, k)
1563 except AttributeError:
1548 except AttributeError:
1564 pass
1549 pass
1565 self.invalidatecaches()
1550 self.invalidatecaches()
1566 if not self.currenttransaction():
1551 if not self.currenttransaction():
1567 # TODO: Changing contents of store outside transaction
1552 # TODO: Changing contents of store outside transaction
1568 # causes inconsistency. We should make in-memory store
1553 # causes inconsistency. We should make in-memory store
1569 # changes detectable, and abort if changed.
1554 # changes detectable, and abort if changed.
1570 self.store.invalidatecaches()
1555 self.store.invalidatecaches()
1571
1556
1572 def invalidateall(self):
1557 def invalidateall(self):
1573 '''Fully invalidates both store and non-store parts, causing the
1558 '''Fully invalidates both store and non-store parts, causing the
1574 subsequent operation to reread any outside changes.'''
1559 subsequent operation to reread any outside changes.'''
1575 # extension should hook this to invalidate its caches
1560 # extension should hook this to invalidate its caches
1576 self.invalidate()
1561 self.invalidate()
1577 self.invalidatedirstate()
1562 self.invalidatedirstate()
1578
1563
1579 @unfilteredmethod
1564 @unfilteredmethod
1580 def _refreshfilecachestats(self, tr):
1565 def _refreshfilecachestats(self, tr):
1581 """Reload stats of cached files so that they are flagged as valid"""
1566 """Reload stats of cached files so that they are flagged as valid"""
1582 for k, ce in self._filecache.items():
1567 for k, ce in self._filecache.items():
1583 if k == 'dirstate' or k not in self.__dict__:
1568 if k == 'dirstate' or k not in self.__dict__:
1584 continue
1569 continue
1585 ce.refresh()
1570 ce.refresh()
1586
1571
1587 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1572 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1588 inheritchecker=None, parentenvvar=None):
1573 inheritchecker=None, parentenvvar=None):
1589 parentlock = None
1574 parentlock = None
1590 # the contents of parentenvvar are used by the underlying lock to
1575 # the contents of parentenvvar are used by the underlying lock to
1591 # determine whether it can be inherited
1576 # determine whether it can be inherited
1592 if parentenvvar is not None:
1577 if parentenvvar is not None:
1593 parentlock = encoding.environ.get(parentenvvar)
1578 parentlock = encoding.environ.get(parentenvvar)
1594
1579
1595 timeout = 0
1580 timeout = 0
1596 warntimeout = 0
1581 warntimeout = 0
1597 if wait:
1582 if wait:
1598 timeout = self.ui.configint("ui", "timeout")
1583 timeout = self.ui.configint("ui", "timeout")
1599 warntimeout = self.ui.configint("ui", "timeout.warn")
1584 warntimeout = self.ui.configint("ui", "timeout.warn")
1600
1585
1601 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1586 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1602 releasefn=releasefn,
1587 releasefn=releasefn,
1603 acquirefn=acquirefn, desc=desc,
1588 acquirefn=acquirefn, desc=desc,
1604 inheritchecker=inheritchecker,
1589 inheritchecker=inheritchecker,
1605 parentlock=parentlock)
1590 parentlock=parentlock)
1606 return l
1591 return l
1607
1592
1608 def _afterlock(self, callback):
1593 def _afterlock(self, callback):
1609 """add a callback to be run when the repository is fully unlocked
1594 """add a callback to be run when the repository is fully unlocked
1610
1595
1611 The callback will be executed when the outermost lock is released
1596 The callback will be executed when the outermost lock is released
1612 (with wlock being higher level than 'lock')."""
1597 (with wlock being higher level than 'lock')."""
1613 for ref in (self._wlockref, self._lockref):
1598 for ref in (self._wlockref, self._lockref):
1614 l = ref and ref()
1599 l = ref and ref()
1615 if l and l.held:
1600 if l and l.held:
1616 l.postrelease.append(callback)
1601 l.postrelease.append(callback)
1617 break
1602 break
1618 else: # no lock have been found.
1603 else: # no lock have been found.
1619 callback()
1604 callback()
1620
1605
1621 def lock(self, wait=True):
1606 def lock(self, wait=True):
1622 '''Lock the repository store (.hg/store) and return a weak reference
1607 '''Lock the repository store (.hg/store) and return a weak reference
1623 to the lock. Use this before modifying the store (e.g. committing or
1608 to the lock. Use this before modifying the store (e.g. committing or
1624 stripping). If you are opening a transaction, get a lock as well.)
1609 stripping). If you are opening a transaction, get a lock as well.)
1625
1610
1626 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1611 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1627 'wlock' first to avoid a dead-lock hazard.'''
1612 'wlock' first to avoid a dead-lock hazard.'''
1628 l = self._currentlock(self._lockref)
1613 l = self._currentlock(self._lockref)
1629 if l is not None:
1614 if l is not None:
1630 l.lock()
1615 l.lock()
1631 return l
1616 return l
1632
1617
1633 l = self._lock(self.svfs, "lock", wait, None,
1618 l = self._lock(self.svfs, "lock", wait, None,
1634 self.invalidate, _('repository %s') % self.origroot)
1619 self.invalidate, _('repository %s') % self.origroot)
1635 self._lockref = weakref.ref(l)
1620 self._lockref = weakref.ref(l)
1636 return l
1621 return l
1637
1622
1638 def _wlockchecktransaction(self):
1623 def _wlockchecktransaction(self):
1639 if self.currenttransaction() is not None:
1624 if self.currenttransaction() is not None:
1640 raise error.LockInheritanceContractViolation(
1625 raise error.LockInheritanceContractViolation(
1641 'wlock cannot be inherited in the middle of a transaction')
1626 'wlock cannot be inherited in the middle of a transaction')
1642
1627
1643 def wlock(self, wait=True):
1628 def wlock(self, wait=True):
1644 '''Lock the non-store parts of the repository (everything under
1629 '''Lock the non-store parts of the repository (everything under
1645 .hg except .hg/store) and return a weak reference to the lock.
1630 .hg except .hg/store) and return a weak reference to the lock.
1646
1631
1647 Use this before modifying files in .hg.
1632 Use this before modifying files in .hg.
1648
1633
1649 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1634 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1650 'wlock' first to avoid a dead-lock hazard.'''
1635 'wlock' first to avoid a dead-lock hazard.'''
1651 l = self._wlockref and self._wlockref()
1636 l = self._wlockref and self._wlockref()
1652 if l is not None and l.held:
1637 if l is not None and l.held:
1653 l.lock()
1638 l.lock()
1654 return l
1639 return l
1655
1640
1656 # We do not need to check for non-waiting lock acquisition. Such
1641 # We do not need to check for non-waiting lock acquisition. Such
1657 # acquisition would not cause dead-lock as they would just fail.
1642 # acquisition would not cause dead-lock as they would just fail.
1658 if wait and (self.ui.configbool('devel', 'all-warnings')
1643 if wait and (self.ui.configbool('devel', 'all-warnings')
1659 or self.ui.configbool('devel', 'check-locks')):
1644 or self.ui.configbool('devel', 'check-locks')):
1660 if self._currentlock(self._lockref) is not None:
1645 if self._currentlock(self._lockref) is not None:
1661 self.ui.develwarn('"wlock" acquired after "lock"')
1646 self.ui.develwarn('"wlock" acquired after "lock"')
1662
1647
1663 def unlock():
1648 def unlock():
1664 if self.dirstate.pendingparentchange():
1649 if self.dirstate.pendingparentchange():
1665 self.dirstate.invalidate()
1650 self.dirstate.invalidate()
1666 else:
1651 else:
1667 self.dirstate.write(None)
1652 self.dirstate.write(None)
1668
1653
1669 self._filecache['dirstate'].refresh()
1654 self._filecache['dirstate'].refresh()
1670
1655
1671 l = self._lock(self.vfs, "wlock", wait, unlock,
1656 l = self._lock(self.vfs, "wlock", wait, unlock,
1672 self.invalidatedirstate, _('working directory of %s') %
1657 self.invalidatedirstate, _('working directory of %s') %
1673 self.origroot,
1658 self.origroot,
1674 inheritchecker=self._wlockchecktransaction,
1659 inheritchecker=self._wlockchecktransaction,
1675 parentenvvar='HG_WLOCK_LOCKER')
1660 parentenvvar='HG_WLOCK_LOCKER')
1676 self._wlockref = weakref.ref(l)
1661 self._wlockref = weakref.ref(l)
1677 return l
1662 return l
1678
1663
1679 def _currentlock(self, lockref):
1664 def _currentlock(self, lockref):
1680 """Returns the lock if it's held, or None if it's not."""
1665 """Returns the lock if it's held, or None if it's not."""
1681 if lockref is None:
1666 if lockref is None:
1682 return None
1667 return None
1683 l = lockref()
1668 l = lockref()
1684 if l is None or not l.held:
1669 if l is None or not l.held:
1685 return None
1670 return None
1686 return l
1671 return l
1687
1672
1688 def currentwlock(self):
1673 def currentwlock(self):
1689 """Returns the wlock if it's held, or None if it's not."""
1674 """Returns the wlock if it's held, or None if it's not."""
1690 return self._currentlock(self._wlockref)
1675 return self._currentlock(self._wlockref)
1691
1676
1692 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1677 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1693 """
1678 """
1694 commit an individual file as part of a larger transaction
1679 commit an individual file as part of a larger transaction
1695 """
1680 """
1696
1681
1697 fname = fctx.path()
1682 fname = fctx.path()
1698 fparent1 = manifest1.get(fname, nullid)
1683 fparent1 = manifest1.get(fname, nullid)
1699 fparent2 = manifest2.get(fname, nullid)
1684 fparent2 = manifest2.get(fname, nullid)
1700 if isinstance(fctx, context.filectx):
1685 if isinstance(fctx, context.filectx):
1701 node = fctx.filenode()
1686 node = fctx.filenode()
1702 if node in [fparent1, fparent2]:
1687 if node in [fparent1, fparent2]:
1703 self.ui.debug('reusing %s filelog entry\n' % fname)
1688 self.ui.debug('reusing %s filelog entry\n' % fname)
1704 if manifest1.flags(fname) != fctx.flags():
1689 if manifest1.flags(fname) != fctx.flags():
1705 changelist.append(fname)
1690 changelist.append(fname)
1706 return node
1691 return node
1707
1692
1708 flog = self.file(fname)
1693 flog = self.file(fname)
1709 meta = {}
1694 meta = {}
1710 copy = fctx.renamed()
1695 copy = fctx.renamed()
1711 if copy and copy[0] != fname:
1696 if copy and copy[0] != fname:
1712 # Mark the new revision of this file as a copy of another
1697 # Mark the new revision of this file as a copy of another
1713 # file. This copy data will effectively act as a parent
1698 # file. This copy data will effectively act as a parent
1714 # of this new revision. If this is a merge, the first
1699 # of this new revision. If this is a merge, the first
1715 # parent will be the nullid (meaning "look up the copy data")
1700 # parent will be the nullid (meaning "look up the copy data")
1716 # and the second one will be the other parent. For example:
1701 # and the second one will be the other parent. For example:
1717 #
1702 #
1718 # 0 --- 1 --- 3 rev1 changes file foo
1703 # 0 --- 1 --- 3 rev1 changes file foo
1719 # \ / rev2 renames foo to bar and changes it
1704 # \ / rev2 renames foo to bar and changes it
1720 # \- 2 -/ rev3 should have bar with all changes and
1705 # \- 2 -/ rev3 should have bar with all changes and
1721 # should record that bar descends from
1706 # should record that bar descends from
1722 # bar in rev2 and foo in rev1
1707 # bar in rev2 and foo in rev1
1723 #
1708 #
1724 # this allows this merge to succeed:
1709 # this allows this merge to succeed:
1725 #
1710 #
1726 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1711 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1727 # \ / merging rev3 and rev4 should use bar@rev2
1712 # \ / merging rev3 and rev4 should use bar@rev2
1728 # \- 2 --- 4 as the merge base
1713 # \- 2 --- 4 as the merge base
1729 #
1714 #
1730
1715
1731 cfname = copy[0]
1716 cfname = copy[0]
1732 crev = manifest1.get(cfname)
1717 crev = manifest1.get(cfname)
1733 newfparent = fparent2
1718 newfparent = fparent2
1734
1719
1735 if manifest2: # branch merge
1720 if manifest2: # branch merge
1736 if fparent2 == nullid or crev is None: # copied on remote side
1721 if fparent2 == nullid or crev is None: # copied on remote side
1737 if cfname in manifest2:
1722 if cfname in manifest2:
1738 crev = manifest2[cfname]
1723 crev = manifest2[cfname]
1739 newfparent = fparent1
1724 newfparent = fparent1
1740
1725
1741 # Here, we used to search backwards through history to try to find
1726 # Here, we used to search backwards through history to try to find
1742 # where the file copy came from if the source of a copy was not in
1727 # where the file copy came from if the source of a copy was not in
1743 # the parent directory. However, this doesn't actually make sense to
1728 # the parent directory. However, this doesn't actually make sense to
1744 # do (what does a copy from something not in your working copy even
1729 # do (what does a copy from something not in your working copy even
1745 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1730 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1746 # the user that copy information was dropped, so if they didn't
1731 # the user that copy information was dropped, so if they didn't
1747 # expect this outcome it can be fixed, but this is the correct
1732 # expect this outcome it can be fixed, but this is the correct
1748 # behavior in this circumstance.
1733 # behavior in this circumstance.
1749
1734
1750 if crev:
1735 if crev:
1751 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1736 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1752 meta["copy"] = cfname
1737 meta["copy"] = cfname
1753 meta["copyrev"] = hex(crev)
1738 meta["copyrev"] = hex(crev)
1754 fparent1, fparent2 = nullid, newfparent
1739 fparent1, fparent2 = nullid, newfparent
1755 else:
1740 else:
1756 self.ui.warn(_("warning: can't find ancestor for '%s' "
1741 self.ui.warn(_("warning: can't find ancestor for '%s' "
1757 "copied from '%s'!\n") % (fname, cfname))
1742 "copied from '%s'!\n") % (fname, cfname))
1758
1743
1759 elif fparent1 == nullid:
1744 elif fparent1 == nullid:
1760 fparent1, fparent2 = fparent2, nullid
1745 fparent1, fparent2 = fparent2, nullid
1761 elif fparent2 != nullid:
1746 elif fparent2 != nullid:
1762 # is one parent an ancestor of the other?
1747 # is one parent an ancestor of the other?
1763 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1748 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1764 if fparent1 in fparentancestors:
1749 if fparent1 in fparentancestors:
1765 fparent1, fparent2 = fparent2, nullid
1750 fparent1, fparent2 = fparent2, nullid
1766 elif fparent2 in fparentancestors:
1751 elif fparent2 in fparentancestors:
1767 fparent2 = nullid
1752 fparent2 = nullid
1768
1753
1769 # is the file changed?
1754 # is the file changed?
1770 text = fctx.data()
1755 text = fctx.data()
1771 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1756 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1772 changelist.append(fname)
1757 changelist.append(fname)
1773 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1758 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1774 # are just the flags changed during merge?
1759 # are just the flags changed during merge?
1775 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1760 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1776 changelist.append(fname)
1761 changelist.append(fname)
1777
1762
1778 return fparent1
1763 return fparent1
1779
1764
1780 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1765 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1781 """check for commit arguments that aren't committable"""
1766 """check for commit arguments that aren't committable"""
1782 if match.isexact() or match.prefix():
1767 if match.isexact() or match.prefix():
1783 matched = set(status.modified + status.added + status.removed)
1768 matched = set(status.modified + status.added + status.removed)
1784
1769
1785 for f in match.files():
1770 for f in match.files():
1786 f = self.dirstate.normalize(f)
1771 f = self.dirstate.normalize(f)
1787 if f == '.' or f in matched or f in wctx.substate:
1772 if f == '.' or f in matched or f in wctx.substate:
1788 continue
1773 continue
1789 if f in status.deleted:
1774 if f in status.deleted:
1790 fail(f, _('file not found!'))
1775 fail(f, _('file not found!'))
1791 if f in vdirs: # visited directory
1776 if f in vdirs: # visited directory
1792 d = f + '/'
1777 d = f + '/'
1793 for mf in matched:
1778 for mf in matched:
1794 if mf.startswith(d):
1779 if mf.startswith(d):
1795 break
1780 break
1796 else:
1781 else:
1797 fail(f, _("no match under directory!"))
1782 fail(f, _("no match under directory!"))
1798 elif f not in self.dirstate:
1783 elif f not in self.dirstate:
1799 fail(f, _("file not tracked!"))
1784 fail(f, _("file not tracked!"))
1800
1785
1801 @unfilteredmethod
1786 @unfilteredmethod
1802 def commit(self, text="", user=None, date=None, match=None, force=False,
1787 def commit(self, text="", user=None, date=None, match=None, force=False,
1803 editor=False, extra=None):
1788 editor=False, extra=None):
1804 """Add a new revision to current repository.
1789 """Add a new revision to current repository.
1805
1790
1806 Revision information is gathered from the working directory,
1791 Revision information is gathered from the working directory,
1807 match can be used to filter the committed files. If editor is
1792 match can be used to filter the committed files. If editor is
1808 supplied, it is called to get a commit message.
1793 supplied, it is called to get a commit message.
1809 """
1794 """
1810 if extra is None:
1795 if extra is None:
1811 extra = {}
1796 extra = {}
1812
1797
1813 def fail(f, msg):
1798 def fail(f, msg):
1814 raise error.Abort('%s: %s' % (f, msg))
1799 raise error.Abort('%s: %s' % (f, msg))
1815
1800
1816 if not match:
1801 if not match:
1817 match = matchmod.always(self.root, '')
1802 match = matchmod.always(self.root, '')
1818
1803
1819 if not force:
1804 if not force:
1820 vdirs = []
1805 vdirs = []
1821 match.explicitdir = vdirs.append
1806 match.explicitdir = vdirs.append
1822 match.bad = fail
1807 match.bad = fail
1823
1808
1824 wlock = lock = tr = None
1809 wlock = lock = tr = None
1825 try:
1810 try:
1826 wlock = self.wlock()
1811 wlock = self.wlock()
1827 lock = self.lock() # for recent changelog (see issue4368)
1812 lock = self.lock() # for recent changelog (see issue4368)
1828
1813
1829 wctx = self[None]
1814 wctx = self[None]
1830 merge = len(wctx.parents()) > 1
1815 merge = len(wctx.parents()) > 1
1831
1816
1832 if not force and merge and not match.always():
1817 if not force and merge and not match.always():
1833 raise error.Abort(_('cannot partially commit a merge '
1818 raise error.Abort(_('cannot partially commit a merge '
1834 '(do not specify files or patterns)'))
1819 '(do not specify files or patterns)'))
1835
1820
1836 status = self.status(match=match, clean=force)
1821 status = self.status(match=match, clean=force)
1837 if force:
1822 if force:
1838 status.modified.extend(status.clean) # mq may commit clean files
1823 status.modified.extend(status.clean) # mq may commit clean files
1839
1824
1840 # check subrepos
1825 # check subrepos
1841 subs, commitsubs, newstate = subrepo.precommit(
1826 subs, commitsubs, newstate = subrepo.precommit(
1842 self.ui, wctx, status, match, force=force)
1827 self.ui, wctx, status, match, force=force)
1843
1828
1844 # make sure all explicit patterns are matched
1829 # make sure all explicit patterns are matched
1845 if not force:
1830 if not force:
1846 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1831 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1847
1832
1848 cctx = context.workingcommitctx(self, status,
1833 cctx = context.workingcommitctx(self, status,
1849 text, user, date, extra)
1834 text, user, date, extra)
1850
1835
1851 # internal config: ui.allowemptycommit
1836 # internal config: ui.allowemptycommit
1852 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1837 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1853 or extra.get('close') or merge or cctx.files()
1838 or extra.get('close') or merge or cctx.files()
1854 or self.ui.configbool('ui', 'allowemptycommit'))
1839 or self.ui.configbool('ui', 'allowemptycommit'))
1855 if not allowemptycommit:
1840 if not allowemptycommit:
1856 return None
1841 return None
1857
1842
1858 if merge and cctx.deleted():
1843 if merge and cctx.deleted():
1859 raise error.Abort(_("cannot commit merge with missing files"))
1844 raise error.Abort(_("cannot commit merge with missing files"))
1860
1845
1861 ms = mergemod.mergestate.read(self)
1846 ms = mergemod.mergestate.read(self)
1862 mergeutil.checkunresolved(ms)
1847 mergeutil.checkunresolved(ms)
1863
1848
1864 if editor:
1849 if editor:
1865 cctx._text = editor(self, cctx, subs)
1850 cctx._text = editor(self, cctx, subs)
1866 edited = (text != cctx._text)
1851 edited = (text != cctx._text)
1867
1852
1868 # Save commit message in case this transaction gets rolled back
1853 # Save commit message in case this transaction gets rolled back
1869 # (e.g. by a pretxncommit hook). Leave the content alone on
1854 # (e.g. by a pretxncommit hook). Leave the content alone on
1870 # the assumption that the user will use the same editor again.
1855 # the assumption that the user will use the same editor again.
1871 msgfn = self.savecommitmessage(cctx._text)
1856 msgfn = self.savecommitmessage(cctx._text)
1872
1857
1873 # commit subs and write new state
1858 # commit subs and write new state
1874 if subs:
1859 if subs:
1875 for s in sorted(commitsubs):
1860 for s in sorted(commitsubs):
1876 sub = wctx.sub(s)
1861 sub = wctx.sub(s)
1877 self.ui.status(_('committing subrepository %s\n') %
1862 self.ui.status(_('committing subrepository %s\n') %
1878 subrepo.subrelpath(sub))
1863 subrepo.subrelpath(sub))
1879 sr = sub.commit(cctx._text, user, date)
1864 sr = sub.commit(cctx._text, user, date)
1880 newstate[s] = (newstate[s][0], sr)
1865 newstate[s] = (newstate[s][0], sr)
1881 subrepo.writestate(self, newstate)
1866 subrepo.writestate(self, newstate)
1882
1867
1883 p1, p2 = self.dirstate.parents()
1868 p1, p2 = self.dirstate.parents()
1884 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1869 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1885 try:
1870 try:
1886 self.hook("precommit", throw=True, parent1=hookp1,
1871 self.hook("precommit", throw=True, parent1=hookp1,
1887 parent2=hookp2)
1872 parent2=hookp2)
1888 tr = self.transaction('commit')
1873 tr = self.transaction('commit')
1889 ret = self.commitctx(cctx, True)
1874 ret = self.commitctx(cctx, True)
1890 except: # re-raises
1875 except: # re-raises
1891 if edited:
1876 if edited:
1892 self.ui.write(
1877 self.ui.write(
1893 _('note: commit message saved in %s\n') % msgfn)
1878 _('note: commit message saved in %s\n') % msgfn)
1894 raise
1879 raise
1895 # update bookmarks, dirstate and mergestate
1880 # update bookmarks, dirstate and mergestate
1896 bookmarks.update(self, [p1, p2], ret)
1881 bookmarks.update(self, [p1, p2], ret)
1897 cctx.markcommitted(ret)
1882 cctx.markcommitted(ret)
1898 ms.reset()
1883 ms.reset()
1899 tr.close()
1884 tr.close()
1900
1885
1901 finally:
1886 finally:
1902 lockmod.release(tr, lock, wlock)
1887 lockmod.release(tr, lock, wlock)
1903
1888
1904 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1889 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1905 # hack for command that use a temporary commit (eg: histedit)
1890 # hack for command that use a temporary commit (eg: histedit)
1906 # temporary commit got stripped before hook release
1891 # temporary commit got stripped before hook release
1907 if self.changelog.hasnode(ret):
1892 if self.changelog.hasnode(ret):
1908 self.hook("commit", node=node, parent1=parent1,
1893 self.hook("commit", node=node, parent1=parent1,
1909 parent2=parent2)
1894 parent2=parent2)
1910 self._afterlock(commithook)
1895 self._afterlock(commithook)
1911 return ret
1896 return ret
1912
1897
1913 @unfilteredmethod
1898 @unfilteredmethod
1914 def commitctx(self, ctx, error=False):
1899 def commitctx(self, ctx, error=False):
1915 """Add a new revision to current repository.
1900 """Add a new revision to current repository.
1916 Revision information is passed via the context argument.
1901 Revision information is passed via the context argument.
1917 """
1902 """
1918
1903
1919 tr = None
1904 tr = None
1920 p1, p2 = ctx.p1(), ctx.p2()
1905 p1, p2 = ctx.p1(), ctx.p2()
1921 user = ctx.user()
1906 user = ctx.user()
1922
1907
1923 lock = self.lock()
1908 lock = self.lock()
1924 try:
1909 try:
1925 tr = self.transaction("commit")
1910 tr = self.transaction("commit")
1926 trp = weakref.proxy(tr)
1911 trp = weakref.proxy(tr)
1927
1912
1928 if ctx.manifestnode():
1913 if ctx.manifestnode():
1929 # reuse an existing manifest revision
1914 # reuse an existing manifest revision
1930 mn = ctx.manifestnode()
1915 mn = ctx.manifestnode()
1931 files = ctx.files()
1916 files = ctx.files()
1932 elif ctx.files():
1917 elif ctx.files():
1933 m1ctx = p1.manifestctx()
1918 m1ctx = p1.manifestctx()
1934 m2ctx = p2.manifestctx()
1919 m2ctx = p2.manifestctx()
1935 mctx = m1ctx.copy()
1920 mctx = m1ctx.copy()
1936
1921
1937 m = mctx.read()
1922 m = mctx.read()
1938 m1 = m1ctx.read()
1923 m1 = m1ctx.read()
1939 m2 = m2ctx.read()
1924 m2 = m2ctx.read()
1940
1925
1941 # check in files
1926 # check in files
1942 added = []
1927 added = []
1943 changed = []
1928 changed = []
1944 removed = list(ctx.removed())
1929 removed = list(ctx.removed())
1945 linkrev = len(self)
1930 linkrev = len(self)
1946 self.ui.note(_("committing files:\n"))
1931 self.ui.note(_("committing files:\n"))
1947 for f in sorted(ctx.modified() + ctx.added()):
1932 for f in sorted(ctx.modified() + ctx.added()):
1948 self.ui.note(f + "\n")
1933 self.ui.note(f + "\n")
1949 try:
1934 try:
1950 fctx = ctx[f]
1935 fctx = ctx[f]
1951 if fctx is None:
1936 if fctx is None:
1952 removed.append(f)
1937 removed.append(f)
1953 else:
1938 else:
1954 added.append(f)
1939 added.append(f)
1955 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1940 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1956 trp, changed)
1941 trp, changed)
1957 m.setflag(f, fctx.flags())
1942 m.setflag(f, fctx.flags())
1958 except OSError as inst:
1943 except OSError as inst:
1959 self.ui.warn(_("trouble committing %s!\n") % f)
1944 self.ui.warn(_("trouble committing %s!\n") % f)
1960 raise
1945 raise
1961 except IOError as inst:
1946 except IOError as inst:
1962 errcode = getattr(inst, 'errno', errno.ENOENT)
1947 errcode = getattr(inst, 'errno', errno.ENOENT)
1963 if error or errcode and errcode != errno.ENOENT:
1948 if error or errcode and errcode != errno.ENOENT:
1964 self.ui.warn(_("trouble committing %s!\n") % f)
1949 self.ui.warn(_("trouble committing %s!\n") % f)
1965 raise
1950 raise
1966
1951
1967 # update manifest
1952 # update manifest
1968 self.ui.note(_("committing manifest\n"))
1953 self.ui.note(_("committing manifest\n"))
1969 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1954 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1970 drop = [f for f in removed if f in m]
1955 drop = [f for f in removed if f in m]
1971 for f in drop:
1956 for f in drop:
1972 del m[f]
1957 del m[f]
1973 mn = mctx.write(trp, linkrev,
1958 mn = mctx.write(trp, linkrev,
1974 p1.manifestnode(), p2.manifestnode(),
1959 p1.manifestnode(), p2.manifestnode(),
1975 added, drop)
1960 added, drop)
1976 files = changed + removed
1961 files = changed + removed
1977 else:
1962 else:
1978 mn = p1.manifestnode()
1963 mn = p1.manifestnode()
1979 files = []
1964 files = []
1980
1965
1981 # update changelog
1966 # update changelog
1982 self.ui.note(_("committing changelog\n"))
1967 self.ui.note(_("committing changelog\n"))
1983 self.changelog.delayupdate(tr)
1968 self.changelog.delayupdate(tr)
1984 n = self.changelog.add(mn, files, ctx.description(),
1969 n = self.changelog.add(mn, files, ctx.description(),
1985 trp, p1.node(), p2.node(),
1970 trp, p1.node(), p2.node(),
1986 user, ctx.date(), ctx.extra().copy())
1971 user, ctx.date(), ctx.extra().copy())
1987 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1972 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1988 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1973 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1989 parent2=xp2)
1974 parent2=xp2)
1990 # set the new commit is proper phase
1975 # set the new commit is proper phase
1991 targetphase = subrepo.newcommitphase(self.ui, ctx)
1976 targetphase = subrepo.newcommitphase(self.ui, ctx)
1992 if targetphase:
1977 if targetphase:
1993 # retract boundary do not alter parent changeset.
1978 # retract boundary do not alter parent changeset.
1994 # if a parent have higher the resulting phase will
1979 # if a parent have higher the resulting phase will
1995 # be compliant anyway
1980 # be compliant anyway
1996 #
1981 #
1997 # if minimal phase was 0 we don't need to retract anything
1982 # if minimal phase was 0 we don't need to retract anything
1998 phases.registernew(self, tr, targetphase, [n])
1983 phases.registernew(self, tr, targetphase, [n])
1999 tr.close()
1984 tr.close()
2000 return n
1985 return n
2001 finally:
1986 finally:
2002 if tr:
1987 if tr:
2003 tr.release()
1988 tr.release()
2004 lock.release()
1989 lock.release()
2005
1990
2006 @unfilteredmethod
1991 @unfilteredmethod
2007 def destroying(self):
1992 def destroying(self):
2008 '''Inform the repository that nodes are about to be destroyed.
1993 '''Inform the repository that nodes are about to be destroyed.
2009 Intended for use by strip and rollback, so there's a common
1994 Intended for use by strip and rollback, so there's a common
2010 place for anything that has to be done before destroying history.
1995 place for anything that has to be done before destroying history.
2011
1996
2012 This is mostly useful for saving state that is in memory and waiting
1997 This is mostly useful for saving state that is in memory and waiting
2013 to be flushed when the current lock is released. Because a call to
1998 to be flushed when the current lock is released. Because a call to
2014 destroyed is imminent, the repo will be invalidated causing those
1999 destroyed is imminent, the repo will be invalidated causing those
2015 changes to stay in memory (waiting for the next unlock), or vanish
2000 changes to stay in memory (waiting for the next unlock), or vanish
2016 completely.
2001 completely.
2017 '''
2002 '''
2018 # When using the same lock to commit and strip, the phasecache is left
2003 # When using the same lock to commit and strip, the phasecache is left
2019 # dirty after committing. Then when we strip, the repo is invalidated,
2004 # dirty after committing. Then when we strip, the repo is invalidated,
2020 # causing those changes to disappear.
2005 # causing those changes to disappear.
2021 if '_phasecache' in vars(self):
2006 if '_phasecache' in vars(self):
2022 self._phasecache.write()
2007 self._phasecache.write()
2023
2008
2024 @unfilteredmethod
2009 @unfilteredmethod
2025 def destroyed(self):
2010 def destroyed(self):
2026 '''Inform the repository that nodes have been destroyed.
2011 '''Inform the repository that nodes have been destroyed.
2027 Intended for use by strip and rollback, so there's a common
2012 Intended for use by strip and rollback, so there's a common
2028 place for anything that has to be done after destroying history.
2013 place for anything that has to be done after destroying history.
2029 '''
2014 '''
2030 # When one tries to:
2015 # When one tries to:
2031 # 1) destroy nodes thus calling this method (e.g. strip)
2016 # 1) destroy nodes thus calling this method (e.g. strip)
2032 # 2) use phasecache somewhere (e.g. commit)
2017 # 2) use phasecache somewhere (e.g. commit)
2033 #
2018 #
2034 # then 2) will fail because the phasecache contains nodes that were
2019 # then 2) will fail because the phasecache contains nodes that were
2035 # removed. We can either remove phasecache from the filecache,
2020 # removed. We can either remove phasecache from the filecache,
2036 # causing it to reload next time it is accessed, or simply filter
2021 # causing it to reload next time it is accessed, or simply filter
2037 # the removed nodes now and write the updated cache.
2022 # the removed nodes now and write the updated cache.
2038 self._phasecache.filterunknown(self)
2023 self._phasecache.filterunknown(self)
2039 self._phasecache.write()
2024 self._phasecache.write()
2040
2025
2041 # refresh all repository caches
2026 # refresh all repository caches
2042 self.updatecaches()
2027 self.updatecaches()
2043
2028
2044 # Ensure the persistent tag cache is updated. Doing it now
2029 # Ensure the persistent tag cache is updated. Doing it now
2045 # means that the tag cache only has to worry about destroyed
2030 # means that the tag cache only has to worry about destroyed
2046 # heads immediately after a strip/rollback. That in turn
2031 # heads immediately after a strip/rollback. That in turn
2047 # guarantees that "cachetip == currenttip" (comparing both rev
2032 # guarantees that "cachetip == currenttip" (comparing both rev
2048 # and node) always means no nodes have been added or destroyed.
2033 # and node) always means no nodes have been added or destroyed.
2049
2034
2050 # XXX this is suboptimal when qrefresh'ing: we strip the current
2035 # XXX this is suboptimal when qrefresh'ing: we strip the current
2051 # head, refresh the tag cache, then immediately add a new head.
2036 # head, refresh the tag cache, then immediately add a new head.
2052 # But I think doing it this way is necessary for the "instant
2037 # But I think doing it this way is necessary for the "instant
2053 # tag cache retrieval" case to work.
2038 # tag cache retrieval" case to work.
2054 self.invalidate()
2039 self.invalidate()
2055
2040
2056 def walk(self, match, node=None):
2041 def walk(self, match, node=None):
2057 '''
2042 '''
2058 walk recursively through the directory tree or a given
2043 walk recursively through the directory tree or a given
2059 changeset, finding all files matched by the match
2044 changeset, finding all files matched by the match
2060 function
2045 function
2061 '''
2046 '''
2062 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2047 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2063 return self[node].walk(match)
2048 return self[node].walk(match)
2064
2049
2065 def status(self, node1='.', node2=None, match=None,
2050 def status(self, node1='.', node2=None, match=None,
2066 ignored=False, clean=False, unknown=False,
2051 ignored=False, clean=False, unknown=False,
2067 listsubrepos=False):
2052 listsubrepos=False):
2068 '''a convenience method that calls node1.status(node2)'''
2053 '''a convenience method that calls node1.status(node2)'''
2069 return self[node1].status(node2, match, ignored, clean, unknown,
2054 return self[node1].status(node2, match, ignored, clean, unknown,
2070 listsubrepos)
2055 listsubrepos)
2071
2056
2072 def addpostdsstatus(self, ps):
2057 def addpostdsstatus(self, ps):
2073 """Add a callback to run within the wlock, at the point at which status
2058 """Add a callback to run within the wlock, at the point at which status
2074 fixups happen.
2059 fixups happen.
2075
2060
2076 On status completion, callback(wctx, status) will be called with the
2061 On status completion, callback(wctx, status) will be called with the
2077 wlock held, unless the dirstate has changed from underneath or the wlock
2062 wlock held, unless the dirstate has changed from underneath or the wlock
2078 couldn't be grabbed.
2063 couldn't be grabbed.
2079
2064
2080 Callbacks should not capture and use a cached copy of the dirstate --
2065 Callbacks should not capture and use a cached copy of the dirstate --
2081 it might change in the meanwhile. Instead, they should access the
2066 it might change in the meanwhile. Instead, they should access the
2082 dirstate via wctx.repo().dirstate.
2067 dirstate via wctx.repo().dirstate.
2083
2068
2084 This list is emptied out after each status run -- extensions should
2069 This list is emptied out after each status run -- extensions should
2085 make sure it adds to this list each time dirstate.status is called.
2070 make sure it adds to this list each time dirstate.status is called.
2086 Extensions should also make sure they don't call this for statuses
2071 Extensions should also make sure they don't call this for statuses
2087 that don't involve the dirstate.
2072 that don't involve the dirstate.
2088 """
2073 """
2089
2074
2090 # The list is located here for uniqueness reasons -- it is actually
2075 # The list is located here for uniqueness reasons -- it is actually
2091 # managed by the workingctx, but that isn't unique per-repo.
2076 # managed by the workingctx, but that isn't unique per-repo.
2092 self._postdsstatus.append(ps)
2077 self._postdsstatus.append(ps)
2093
2078
2094 def postdsstatus(self):
2079 def postdsstatus(self):
2095 """Used by workingctx to get the list of post-dirstate-status hooks."""
2080 """Used by workingctx to get the list of post-dirstate-status hooks."""
2096 return self._postdsstatus
2081 return self._postdsstatus
2097
2082
2098 def clearpostdsstatus(self):
2083 def clearpostdsstatus(self):
2099 """Used by workingctx to clear post-dirstate-status hooks."""
2084 """Used by workingctx to clear post-dirstate-status hooks."""
2100 del self._postdsstatus[:]
2085 del self._postdsstatus[:]
2101
2086
2102 def heads(self, start=None):
2087 def heads(self, start=None):
2103 if start is None:
2088 if start is None:
2104 cl = self.changelog
2089 cl = self.changelog
2105 headrevs = reversed(cl.headrevs())
2090 headrevs = reversed(cl.headrevs())
2106 return [cl.node(rev) for rev in headrevs]
2091 return [cl.node(rev) for rev in headrevs]
2107
2092
2108 heads = self.changelog.heads(start)
2093 heads = self.changelog.heads(start)
2109 # sort the output in rev descending order
2094 # sort the output in rev descending order
2110 return sorted(heads, key=self.changelog.rev, reverse=True)
2095 return sorted(heads, key=self.changelog.rev, reverse=True)
2111
2096
2112 def branchheads(self, branch=None, start=None, closed=False):
2097 def branchheads(self, branch=None, start=None, closed=False):
2113 '''return a (possibly filtered) list of heads for the given branch
2098 '''return a (possibly filtered) list of heads for the given branch
2114
2099
2115 Heads are returned in topological order, from newest to oldest.
2100 Heads are returned in topological order, from newest to oldest.
2116 If branch is None, use the dirstate branch.
2101 If branch is None, use the dirstate branch.
2117 If start is not None, return only heads reachable from start.
2102 If start is not None, return only heads reachable from start.
2118 If closed is True, return heads that are marked as closed as well.
2103 If closed is True, return heads that are marked as closed as well.
2119 '''
2104 '''
2120 if branch is None:
2105 if branch is None:
2121 branch = self[None].branch()
2106 branch = self[None].branch()
2122 branches = self.branchmap()
2107 branches = self.branchmap()
2123 if branch not in branches:
2108 if branch not in branches:
2124 return []
2109 return []
2125 # the cache returns heads ordered lowest to highest
2110 # the cache returns heads ordered lowest to highest
2126 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2111 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2127 if start is not None:
2112 if start is not None:
2128 # filter out the heads that cannot be reached from startrev
2113 # filter out the heads that cannot be reached from startrev
2129 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2114 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2130 bheads = [h for h in bheads if h in fbheads]
2115 bheads = [h for h in bheads if h in fbheads]
2131 return bheads
2116 return bheads
2132
2117
2133 def branches(self, nodes):
2118 def branches(self, nodes):
2134 if not nodes:
2119 if not nodes:
2135 nodes = [self.changelog.tip()]
2120 nodes = [self.changelog.tip()]
2136 b = []
2121 b = []
2137 for n in nodes:
2122 for n in nodes:
2138 t = n
2123 t = n
2139 while True:
2124 while True:
2140 p = self.changelog.parents(n)
2125 p = self.changelog.parents(n)
2141 if p[1] != nullid or p[0] == nullid:
2126 if p[1] != nullid or p[0] == nullid:
2142 b.append((t, n, p[0], p[1]))
2127 b.append((t, n, p[0], p[1]))
2143 break
2128 break
2144 n = p[0]
2129 n = p[0]
2145 return b
2130 return b
2146
2131
2147 def between(self, pairs):
2132 def between(self, pairs):
2148 r = []
2133 r = []
2149
2134
2150 for top, bottom in pairs:
2135 for top, bottom in pairs:
2151 n, l, i = top, [], 0
2136 n, l, i = top, [], 0
2152 f = 1
2137 f = 1
2153
2138
2154 while n != bottom and n != nullid:
2139 while n != bottom and n != nullid:
2155 p = self.changelog.parents(n)[0]
2140 p = self.changelog.parents(n)[0]
2156 if i == f:
2141 if i == f:
2157 l.append(n)
2142 l.append(n)
2158 f = f * 2
2143 f = f * 2
2159 n = p
2144 n = p
2160 i += 1
2145 i += 1
2161
2146
2162 r.append(l)
2147 r.append(l)
2163
2148
2164 return r
2149 return r
2165
2150
2166 def checkpush(self, pushop):
2151 def checkpush(self, pushop):
2167 """Extensions can override this function if additional checks have
2152 """Extensions can override this function if additional checks have
2168 to be performed before pushing, or call it if they override push
2153 to be performed before pushing, or call it if they override push
2169 command.
2154 command.
2170 """
2155 """
2171
2156
2172 @unfilteredpropertycache
2157 @unfilteredpropertycache
2173 def prepushoutgoinghooks(self):
2158 def prepushoutgoinghooks(self):
2174 """Return util.hooks consists of a pushop with repo, remote, outgoing
2159 """Return util.hooks consists of a pushop with repo, remote, outgoing
2175 methods, which are called before pushing changesets.
2160 methods, which are called before pushing changesets.
2176 """
2161 """
2177 return util.hooks()
2162 return util.hooks()
2178
2163
2179 def pushkey(self, namespace, key, old, new):
2164 def pushkey(self, namespace, key, old, new):
2180 try:
2165 try:
2181 tr = self.currenttransaction()
2166 tr = self.currenttransaction()
2182 hookargs = {}
2167 hookargs = {}
2183 if tr is not None:
2168 if tr is not None:
2184 hookargs.update(tr.hookargs)
2169 hookargs.update(tr.hookargs)
2185 hookargs['namespace'] = namespace
2170 hookargs['namespace'] = namespace
2186 hookargs['key'] = key
2171 hookargs['key'] = key
2187 hookargs['old'] = old
2172 hookargs['old'] = old
2188 hookargs['new'] = new
2173 hookargs['new'] = new
2189 self.hook('prepushkey', throw=True, **hookargs)
2174 self.hook('prepushkey', throw=True, **hookargs)
2190 except error.HookAbort as exc:
2175 except error.HookAbort as exc:
2191 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2176 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2192 if exc.hint:
2177 if exc.hint:
2193 self.ui.write_err(_("(%s)\n") % exc.hint)
2178 self.ui.write_err(_("(%s)\n") % exc.hint)
2194 return False
2179 return False
2195 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2180 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2196 ret = pushkey.push(self, namespace, key, old, new)
2181 ret = pushkey.push(self, namespace, key, old, new)
2197 def runhook():
2182 def runhook():
2198 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2183 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2199 ret=ret)
2184 ret=ret)
2200 self._afterlock(runhook)
2185 self._afterlock(runhook)
2201 return ret
2186 return ret
2202
2187
2203 def listkeys(self, namespace):
2188 def listkeys(self, namespace):
2204 self.hook('prelistkeys', throw=True, namespace=namespace)
2189 self.hook('prelistkeys', throw=True, namespace=namespace)
2205 self.ui.debug('listing keys for "%s"\n' % namespace)
2190 self.ui.debug('listing keys for "%s"\n' % namespace)
2206 values = pushkey.list(self, namespace)
2191 values = pushkey.list(self, namespace)
2207 self.hook('listkeys', namespace=namespace, values=values)
2192 self.hook('listkeys', namespace=namespace, values=values)
2208 return values
2193 return values
2209
2194
2210 def debugwireargs(self, one, two, three=None, four=None, five=None):
2195 def debugwireargs(self, one, two, three=None, four=None, five=None):
2211 '''used to test argument passing over the wire'''
2196 '''used to test argument passing over the wire'''
2212 return "%s %s %s %s %s" % (one, two, three, four, five)
2197 return "%s %s %s %s %s" % (one, two, three, four, five)
2213
2198
2214 def savecommitmessage(self, text):
2199 def savecommitmessage(self, text):
2215 fp = self.vfs('last-message.txt', 'wb')
2200 fp = self.vfs('last-message.txt', 'wb')
2216 try:
2201 try:
2217 fp.write(text)
2202 fp.write(text)
2218 finally:
2203 finally:
2219 fp.close()
2204 fp.close()
2220 return self.pathto(fp.name[len(self.root) + 1:])
2205 return self.pathto(fp.name[len(self.root) + 1:])
2221
2206
2222 # used to avoid circular references so destructors work
2207 # used to avoid circular references so destructors work
2223 def aftertrans(files):
2208 def aftertrans(files):
2224 renamefiles = [tuple(t) for t in files]
2209 renamefiles = [tuple(t) for t in files]
2225 def a():
2210 def a():
2226 for vfs, src, dest in renamefiles:
2211 for vfs, src, dest in renamefiles:
2227 # if src and dest refer to a same file, vfs.rename is a no-op,
2212 # if src and dest refer to a same file, vfs.rename is a no-op,
2228 # leaving both src and dest on disk. delete dest to make sure
2213 # leaving both src and dest on disk. delete dest to make sure
2229 # the rename couldn't be such a no-op.
2214 # the rename couldn't be such a no-op.
2230 vfs.tryunlink(dest)
2215 vfs.tryunlink(dest)
2231 try:
2216 try:
2232 vfs.rename(src, dest)
2217 vfs.rename(src, dest)
2233 except OSError: # journal file does not yet exist
2218 except OSError: # journal file does not yet exist
2234 pass
2219 pass
2235 return a
2220 return a
2236
2221
2237 def undoname(fn):
2222 def undoname(fn):
2238 base, name = os.path.split(fn)
2223 base, name = os.path.split(fn)
2239 assert name.startswith('journal')
2224 assert name.startswith('journal')
2240 return os.path.join(base, name.replace('journal', 'undo', 1))
2225 return os.path.join(base, name.replace('journal', 'undo', 1))
2241
2226
2242 def instance(ui, path, create):
2227 def instance(ui, path, create):
2243 return localrepository(ui, util.urllocalpath(path), create)
2228 return localrepository(ui, util.urllocalpath(path), create)
2244
2229
2245 def islocal(path):
2230 def islocal(path):
2246 return True
2231 return True
2247
2232
2248 def newreporequirements(repo):
2233 def newreporequirements(repo):
2249 """Determine the set of requirements for a new local repository.
2234 """Determine the set of requirements for a new local repository.
2250
2235
2251 Extensions can wrap this function to specify custom requirements for
2236 Extensions can wrap this function to specify custom requirements for
2252 new repositories.
2237 new repositories.
2253 """
2238 """
2254 ui = repo.ui
2239 ui = repo.ui
2255 requirements = {'revlogv1'}
2240 requirements = {'revlogv1'}
2256 if ui.configbool('format', 'usestore'):
2241 if ui.configbool('format', 'usestore'):
2257 requirements.add('store')
2242 requirements.add('store')
2258 if ui.configbool('format', 'usefncache'):
2243 if ui.configbool('format', 'usefncache'):
2259 requirements.add('fncache')
2244 requirements.add('fncache')
2260 if ui.configbool('format', 'dotencode'):
2245 if ui.configbool('format', 'dotencode'):
2261 requirements.add('dotencode')
2246 requirements.add('dotencode')
2262
2247
2263 compengine = ui.config('experimental', 'format.compression')
2248 compengine = ui.config('experimental', 'format.compression')
2264 if compengine not in util.compengines:
2249 if compengine not in util.compengines:
2265 raise error.Abort(_('compression engine %s defined by '
2250 raise error.Abort(_('compression engine %s defined by '
2266 'experimental.format.compression not available') %
2251 'experimental.format.compression not available') %
2267 compengine,
2252 compengine,
2268 hint=_('run "hg debuginstall" to list available '
2253 hint=_('run "hg debuginstall" to list available '
2269 'compression engines'))
2254 'compression engines'))
2270
2255
2271 # zlib is the historical default and doesn't need an explicit requirement.
2256 # zlib is the historical default and doesn't need an explicit requirement.
2272 if compengine != 'zlib':
2257 if compengine != 'zlib':
2273 requirements.add('exp-compression-%s' % compengine)
2258 requirements.add('exp-compression-%s' % compengine)
2274
2259
2275 if scmutil.gdinitconfig(ui):
2260 if scmutil.gdinitconfig(ui):
2276 requirements.add('generaldelta')
2261 requirements.add('generaldelta')
2277 if ui.configbool('experimental', 'treemanifest'):
2262 if ui.configbool('experimental', 'treemanifest'):
2278 requirements.add('treemanifest')
2263 requirements.add('treemanifest')
2279 if ui.configbool('experimental', 'manifestv2'):
2264 if ui.configbool('experimental', 'manifestv2'):
2280 requirements.add('manifestv2')
2265 requirements.add('manifestv2')
2281
2266
2282 revlogv2 = ui.config('experimental', 'revlogv2')
2267 revlogv2 = ui.config('experimental', 'revlogv2')
2283 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2268 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2284 requirements.remove('revlogv1')
2269 requirements.remove('revlogv1')
2285 # generaldelta is implied by revlogv2.
2270 # generaldelta is implied by revlogv2.
2286 requirements.discard('generaldelta')
2271 requirements.discard('generaldelta')
2287 requirements.add(REVLOGV2_REQUIREMENT)
2272 requirements.add(REVLOGV2_REQUIREMENT)
2288
2273
2289 return requirements
2274 return requirements
@@ -1,242 +1,256 b''
1 # repoview.py - Filtered view of a localrepo object
1 # repoview.py - Filtered view of a localrepo object
2 #
2 #
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
4 # Logilab SA <contact@logilab.fr>
4 # Logilab SA <contact@logilab.fr>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import copy
11 import copy
12 import weakref
12
13
13 from .node import nullrev
14 from .node import nullrev
14 from . import (
15 from . import (
15 obsolete,
16 obsolete,
16 phases,
17 phases,
17 tags as tagsmod,
18 tags as tagsmod,
18 )
19 )
19
20
20 def hideablerevs(repo):
21 def hideablerevs(repo):
21 """Revision candidates to be hidden
22 """Revision candidates to be hidden
22
23
23 This is a standalone function to allow extensions to wrap it.
24 This is a standalone function to allow extensions to wrap it.
24
25
25 Because we use the set of immutable changesets as a fallback subset in
26 Because we use the set of immutable changesets as a fallback subset in
26 branchmap (see mercurial.branchmap.subsettable), you cannot set "public"
27 branchmap (see mercurial.branchmap.subsettable), you cannot set "public"
27 changesets as "hideable". Doing so would break multiple code assertions and
28 changesets as "hideable". Doing so would break multiple code assertions and
28 lead to crashes."""
29 lead to crashes."""
29 return obsolete.getrevs(repo, 'obsolete')
30 return obsolete.getrevs(repo, 'obsolete')
30
31
31 def pinnedrevs(repo):
32 def pinnedrevs(repo):
32 """revisions blocking hidden changesets from being filtered
33 """revisions blocking hidden changesets from being filtered
33 """
34 """
34
35
35 cl = repo.changelog
36 cl = repo.changelog
36 pinned = set()
37 pinned = set()
37 pinned.update([par.rev() for par in repo[None].parents()])
38 pinned.update([par.rev() for par in repo[None].parents()])
38 pinned.update([cl.rev(bm) for bm in repo._bookmarks.values()])
39 pinned.update([cl.rev(bm) for bm in repo._bookmarks.values()])
39
40
40 tags = {}
41 tags = {}
41 tagsmod.readlocaltags(repo.ui, repo, tags, {})
42 tagsmod.readlocaltags(repo.ui, repo, tags, {})
42 if tags:
43 if tags:
43 rev, nodemap = cl.rev, cl.nodemap
44 rev, nodemap = cl.rev, cl.nodemap
44 pinned.update(rev(t[0]) for t in tags.values() if t[0] in nodemap)
45 pinned.update(rev(t[0]) for t in tags.values() if t[0] in nodemap)
45 return pinned
46 return pinned
46
47
47
48
48 def _revealancestors(pfunc, hidden, revs):
49 def _revealancestors(pfunc, hidden, revs):
49 """reveals contiguous chains of hidden ancestors of 'revs' by removing them
50 """reveals contiguous chains of hidden ancestors of 'revs' by removing them
50 from 'hidden'
51 from 'hidden'
51
52
52 - pfunc(r): a funtion returning parent of 'r',
53 - pfunc(r): a funtion returning parent of 'r',
53 - hidden: the (preliminary) hidden revisions, to be updated
54 - hidden: the (preliminary) hidden revisions, to be updated
54 - revs: iterable of revnum,
55 - revs: iterable of revnum,
55
56
56 (Ancestors are revealed exclusively, i.e. the elements in 'revs' are
57 (Ancestors are revealed exclusively, i.e. the elements in 'revs' are
57 *not* revealed)
58 *not* revealed)
58 """
59 """
59 stack = list(revs)
60 stack = list(revs)
60 while stack:
61 while stack:
61 for p in pfunc(stack.pop()):
62 for p in pfunc(stack.pop()):
62 if p != nullrev and p in hidden:
63 if p != nullrev and p in hidden:
63 hidden.remove(p)
64 hidden.remove(p)
64 stack.append(p)
65 stack.append(p)
65
66
66 def computehidden(repo):
67 def computehidden(repo):
67 """compute the set of hidden revision to filter
68 """compute the set of hidden revision to filter
68
69
69 During most operation hidden should be filtered."""
70 During most operation hidden should be filtered."""
70 assert not repo.changelog.filteredrevs
71 assert not repo.changelog.filteredrevs
71
72
72 hidden = hideablerevs(repo)
73 hidden = hideablerevs(repo)
73 if hidden:
74 if hidden:
74 hidden = set(hidden - pinnedrevs(repo))
75 hidden = set(hidden - pinnedrevs(repo))
75 pfunc = repo.changelog.parentrevs
76 pfunc = repo.changelog.parentrevs
76 mutablephases = (phases.draft, phases.secret)
77 mutablephases = (phases.draft, phases.secret)
77 mutable = repo._phasecache.getrevset(repo, mutablephases)
78 mutable = repo._phasecache.getrevset(repo, mutablephases)
78
79
79 visible = mutable - hidden
80 visible = mutable - hidden
80 _revealancestors(pfunc, hidden, visible)
81 _revealancestors(pfunc, hidden, visible)
81 return frozenset(hidden)
82 return frozenset(hidden)
82
83
83 def computeunserved(repo):
84 def computeunserved(repo):
84 """compute the set of revision that should be filtered when used a server
85 """compute the set of revision that should be filtered when used a server
85
86
86 Secret and hidden changeset should not pretend to be here."""
87 Secret and hidden changeset should not pretend to be here."""
87 assert not repo.changelog.filteredrevs
88 assert not repo.changelog.filteredrevs
88 # fast path in simple case to avoid impact of non optimised code
89 # fast path in simple case to avoid impact of non optimised code
89 hiddens = filterrevs(repo, 'visible')
90 hiddens = filterrevs(repo, 'visible')
90 if phases.hassecret(repo):
91 if phases.hassecret(repo):
91 cl = repo.changelog
92 cl = repo.changelog
92 secret = phases.secret
93 secret = phases.secret
93 getphase = repo._phasecache.phase
94 getphase = repo._phasecache.phase
94 first = min(cl.rev(n) for n in repo._phasecache.phaseroots[secret])
95 first = min(cl.rev(n) for n in repo._phasecache.phaseroots[secret])
95 revs = cl.revs(start=first)
96 revs = cl.revs(start=first)
96 secrets = set(r for r in revs if getphase(repo, r) >= secret)
97 secrets = set(r for r in revs if getphase(repo, r) >= secret)
97 return frozenset(hiddens | secrets)
98 return frozenset(hiddens | secrets)
98 else:
99 else:
99 return hiddens
100 return hiddens
100
101
101 def computemutable(repo):
102 def computemutable(repo):
102 assert not repo.changelog.filteredrevs
103 assert not repo.changelog.filteredrevs
103 # fast check to avoid revset call on huge repo
104 # fast check to avoid revset call on huge repo
104 if any(repo._phasecache.phaseroots[1:]):
105 if any(repo._phasecache.phaseroots[1:]):
105 getphase = repo._phasecache.phase
106 getphase = repo._phasecache.phase
106 maymutable = filterrevs(repo, 'base')
107 maymutable = filterrevs(repo, 'base')
107 return frozenset(r for r in maymutable if getphase(repo, r))
108 return frozenset(r for r in maymutable if getphase(repo, r))
108 return frozenset()
109 return frozenset()
109
110
110 def computeimpactable(repo):
111 def computeimpactable(repo):
111 """Everything impactable by mutable revision
112 """Everything impactable by mutable revision
112
113
113 The immutable filter still have some chance to get invalidated. This will
114 The immutable filter still have some chance to get invalidated. This will
114 happen when:
115 happen when:
115
116
116 - you garbage collect hidden changeset,
117 - you garbage collect hidden changeset,
117 - public phase is moved backward,
118 - public phase is moved backward,
118 - something is changed in the filtering (this could be fixed)
119 - something is changed in the filtering (this could be fixed)
119
120
120 This filter out any mutable changeset and any public changeset that may be
121 This filter out any mutable changeset and any public changeset that may be
121 impacted by something happening to a mutable revision.
122 impacted by something happening to a mutable revision.
122
123
123 This is achieved by filtered everything with a revision number egal or
124 This is achieved by filtered everything with a revision number egal or
124 higher than the first mutable changeset is filtered."""
125 higher than the first mutable changeset is filtered."""
125 assert not repo.changelog.filteredrevs
126 assert not repo.changelog.filteredrevs
126 cl = repo.changelog
127 cl = repo.changelog
127 firstmutable = len(cl)
128 firstmutable = len(cl)
128 for roots in repo._phasecache.phaseroots[1:]:
129 for roots in repo._phasecache.phaseroots[1:]:
129 if roots:
130 if roots:
130 firstmutable = min(firstmutable, min(cl.rev(r) for r in roots))
131 firstmutable = min(firstmutable, min(cl.rev(r) for r in roots))
131 # protect from nullrev root
132 # protect from nullrev root
132 firstmutable = max(0, firstmutable)
133 firstmutable = max(0, firstmutable)
133 return frozenset(xrange(firstmutable, len(cl)))
134 return frozenset(xrange(firstmutable, len(cl)))
134
135
135 # function to compute filtered set
136 # function to compute filtered set
136 #
137 #
137 # When adding a new filter you MUST update the table at:
138 # When adding a new filter you MUST update the table at:
138 # mercurial.branchmap.subsettable
139 # mercurial.branchmap.subsettable
139 # Otherwise your filter will have to recompute all its branches cache
140 # Otherwise your filter will have to recompute all its branches cache
140 # from scratch (very slow).
141 # from scratch (very slow).
141 filtertable = {'visible': computehidden,
142 filtertable = {'visible': computehidden,
142 'served': computeunserved,
143 'served': computeunserved,
143 'immutable': computemutable,
144 'immutable': computemutable,
144 'base': computeimpactable}
145 'base': computeimpactable}
145
146
146 def filterrevs(repo, filtername):
147 def filterrevs(repo, filtername):
147 """returns set of filtered revision for this filter name"""
148 """returns set of filtered revision for this filter name"""
148 if filtername not in repo.filteredrevcache:
149 if filtername not in repo.filteredrevcache:
149 func = filtertable[filtername]
150 func = filtertable[filtername]
150 repo.filteredrevcache[filtername] = func(repo.unfiltered())
151 repo.filteredrevcache[filtername] = func(repo.unfiltered())
151 return repo.filteredrevcache[filtername]
152 return repo.filteredrevcache[filtername]
152
153
153 class repoview(object):
154 class repoview(object):
154 """Provide a read/write view of a repo through a filtered changelog
155 """Provide a read/write view of a repo through a filtered changelog
155
156
156 This object is used to access a filtered version of a repository without
157 This object is used to access a filtered version of a repository without
157 altering the original repository object itself. We can not alter the
158 altering the original repository object itself. We can not alter the
158 original object for two main reasons:
159 original object for two main reasons:
159 - It prevents the use of a repo with multiple filters at the same time. In
160 - It prevents the use of a repo with multiple filters at the same time. In
160 particular when multiple threads are involved.
161 particular when multiple threads are involved.
161 - It makes scope of the filtering harder to control.
162 - It makes scope of the filtering harder to control.
162
163
163 This object behaves very closely to the original repository. All attribute
164 This object behaves very closely to the original repository. All attribute
164 operations are done on the original repository:
165 operations are done on the original repository:
165 - An access to `repoview.someattr` actually returns `repo.someattr`,
166 - An access to `repoview.someattr` actually returns `repo.someattr`,
166 - A write to `repoview.someattr` actually sets value of `repo.someattr`,
167 - A write to `repoview.someattr` actually sets value of `repo.someattr`,
167 - A deletion of `repoview.someattr` actually drops `someattr`
168 - A deletion of `repoview.someattr` actually drops `someattr`
168 from `repo.__dict__`.
169 from `repo.__dict__`.
169
170
170 The only exception is the `changelog` property. It is overridden to return
171 The only exception is the `changelog` property. It is overridden to return
171 a (surface) copy of `repo.changelog` with some revisions filtered. The
172 a (surface) copy of `repo.changelog` with some revisions filtered. The
172 `filtername` attribute of the view control the revisions that need to be
173 `filtername` attribute of the view control the revisions that need to be
173 filtered. (the fact the changelog is copied is an implementation detail).
174 filtered. (the fact the changelog is copied is an implementation detail).
174
175
175 Unlike attributes, this object intercepts all method calls. This means that
176 Unlike attributes, this object intercepts all method calls. This means that
176 all methods are run on the `repoview` object with the filtered `changelog`
177 all methods are run on the `repoview` object with the filtered `changelog`
177 property. For this purpose the simple `repoview` class must be mixed with
178 property. For this purpose the simple `repoview` class must be mixed with
178 the actual class of the repository. This ensures that the resulting
179 the actual class of the repository. This ensures that the resulting
179 `repoview` object have the very same methods than the repo object. This
180 `repoview` object have the very same methods than the repo object. This
180 leads to the property below.
181 leads to the property below.
181
182
182 repoview.method() --> repo.__class__.method(repoview)
183 repoview.method() --> repo.__class__.method(repoview)
183
184
184 The inheritance has to be done dynamically because `repo` can be of any
185 The inheritance has to be done dynamically because `repo` can be of any
185 subclasses of `localrepo`. Eg: `bundlerepo` or `statichttprepo`.
186 subclasses of `localrepo`. Eg: `bundlerepo` or `statichttprepo`.
186 """
187 """
187
188
188 def __init__(self, repo, filtername):
189 def __init__(self, repo, filtername):
189 object.__setattr__(self, r'_unfilteredrepo', repo)
190 object.__setattr__(self, r'_unfilteredrepo', repo)
190 object.__setattr__(self, r'filtername', filtername)
191 object.__setattr__(self, r'filtername', filtername)
191 object.__setattr__(self, r'_clcachekey', None)
192 object.__setattr__(self, r'_clcachekey', None)
192 object.__setattr__(self, r'_clcache', None)
193 object.__setattr__(self, r'_clcache', None)
193
194
194 # not a propertycache on purpose we shall implement a proper cache later
195 # not a propertycache on purpose we shall implement a proper cache later
195 @property
196 @property
196 def changelog(self):
197 def changelog(self):
197 """return a filtered version of the changeset
198 """return a filtered version of the changeset
198
199
199 this changelog must not be used for writing"""
200 this changelog must not be used for writing"""
200 # some cache may be implemented later
201 # some cache may be implemented later
201 unfi = self._unfilteredrepo
202 unfi = self._unfilteredrepo
202 unfichangelog = unfi.changelog
203 unfichangelog = unfi.changelog
203 # bypass call to changelog.method
204 # bypass call to changelog.method
204 unfiindex = unfichangelog.index
205 unfiindex = unfichangelog.index
205 unfilen = len(unfiindex) - 1
206 unfilen = len(unfiindex) - 1
206 unfinode = unfiindex[unfilen - 1][7]
207 unfinode = unfiindex[unfilen - 1][7]
207
208
208 revs = filterrevs(unfi, self.filtername)
209 revs = filterrevs(unfi, self.filtername)
209 cl = self._clcache
210 cl = self._clcache
210 newkey = (unfilen, unfinode, hash(revs), unfichangelog._delayed)
211 newkey = (unfilen, unfinode, hash(revs), unfichangelog._delayed)
211 # if cl.index is not unfiindex, unfi.changelog would be
212 # if cl.index is not unfiindex, unfi.changelog would be
212 # recreated, and our clcache refers to garbage object
213 # recreated, and our clcache refers to garbage object
213 if (cl is not None and
214 if (cl is not None and
214 (cl.index is not unfiindex or newkey != self._clcachekey)):
215 (cl.index is not unfiindex or newkey != self._clcachekey)):
215 cl = None
216 cl = None
216 # could have been made None by the previous if
217 # could have been made None by the previous if
217 if cl is None:
218 if cl is None:
218 cl = copy.copy(unfichangelog)
219 cl = copy.copy(unfichangelog)
219 cl.filteredrevs = revs
220 cl.filteredrevs = revs
220 object.__setattr__(self, r'_clcache', cl)
221 object.__setattr__(self, r'_clcache', cl)
221 object.__setattr__(self, r'_clcachekey', newkey)
222 object.__setattr__(self, r'_clcachekey', newkey)
222 return cl
223 return cl
223
224
224 def unfiltered(self):
225 def unfiltered(self):
225 """Return an unfiltered version of a repo"""
226 """Return an unfiltered version of a repo"""
226 return self._unfilteredrepo
227 return self._unfilteredrepo
227
228
228 def filtered(self, name):
229 def filtered(self, name):
229 """Return a filtered version of a repository"""
230 """Return a filtered version of a repository"""
230 if name == self.filtername:
231 if name == self.filtername:
231 return self
232 return self
232 return self.unfiltered().filtered(name)
233 return self.unfiltered().filtered(name)
233
234
234 # everything access are forwarded to the proxied repo
235 # everything access are forwarded to the proxied repo
235 def __getattr__(self, attr):
236 def __getattr__(self, attr):
236 return getattr(self._unfilteredrepo, attr)
237 return getattr(self._unfilteredrepo, attr)
237
238
238 def __setattr__(self, attr, value):
239 def __setattr__(self, attr, value):
239 return setattr(self._unfilteredrepo, attr, value)
240 return setattr(self._unfilteredrepo, attr, value)
240
241
241 def __delattr__(self, attr):
242 def __delattr__(self, attr):
242 return delattr(self._unfilteredrepo, attr)
243 return delattr(self._unfilteredrepo, attr)
244
245 # Python <3.4 easily leaks types via __mro__. See
246 # https://bugs.python.org/issue17950. We cache dynamically created types
247 # so they won't be leaked on every invocation of repo.filtered().
248 _filteredrepotypes = weakref.WeakKeyDictionary()
249
250 def newtype(base):
251 """Create a new type with the repoview mixin and the given base class"""
252 if base not in _filteredrepotypes:
253 class filteredrepo(repoview, base):
254 pass
255 _filteredrepotypes[base] = filteredrepo
256 return _filteredrepotypes[base]
@@ -1,198 +1,196 b''
1 # statichttprepo.py - simple http repository class for mercurial
1 # statichttprepo.py - simple http repository class for mercurial
2 #
2 #
3 # This provides read-only repo access to repositories exported via static http
3 # This provides read-only repo access to repositories exported via static http
4 #
4 #
5 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11
11
12 import errno
12 import errno
13
13
14 from .i18n import _
14 from .i18n import _
15 from . import (
15 from . import (
16 byterange,
16 byterange,
17 changelog,
17 changelog,
18 error,
18 error,
19 localrepo,
19 localrepo,
20 manifest,
20 manifest,
21 namespaces,
21 namespaces,
22 pathutil,
22 pathutil,
23 scmutil,
23 scmutil,
24 store,
24 store,
25 url,
25 url,
26 util,
26 util,
27 vfs as vfsmod,
27 vfs as vfsmod,
28 )
28 )
29
29
30 urlerr = util.urlerr
30 urlerr = util.urlerr
31 urlreq = util.urlreq
31 urlreq = util.urlreq
32
32
33 class httprangereader(object):
33 class httprangereader(object):
34 def __init__(self, url, opener):
34 def __init__(self, url, opener):
35 # we assume opener has HTTPRangeHandler
35 # we assume opener has HTTPRangeHandler
36 self.url = url
36 self.url = url
37 self.pos = 0
37 self.pos = 0
38 self.opener = opener
38 self.opener = opener
39 self.name = url
39 self.name = url
40
40
41 def __enter__(self):
41 def __enter__(self):
42 return self
42 return self
43
43
44 def __exit__(self, exc_type, exc_value, traceback):
44 def __exit__(self, exc_type, exc_value, traceback):
45 self.close()
45 self.close()
46
46
47 def seek(self, pos):
47 def seek(self, pos):
48 self.pos = pos
48 self.pos = pos
49 def read(self, bytes=None):
49 def read(self, bytes=None):
50 req = urlreq.request(self.url)
50 req = urlreq.request(self.url)
51 end = ''
51 end = ''
52 if bytes:
52 if bytes:
53 end = self.pos + bytes - 1
53 end = self.pos + bytes - 1
54 if self.pos or end:
54 if self.pos or end:
55 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
55 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
56
56
57 try:
57 try:
58 f = self.opener.open(req)
58 f = self.opener.open(req)
59 data = f.read()
59 data = f.read()
60 code = f.code
60 code = f.code
61 except urlerr.httperror as inst:
61 except urlerr.httperror as inst:
62 num = inst.code == 404 and errno.ENOENT or None
62 num = inst.code == 404 and errno.ENOENT or None
63 raise IOError(num, inst)
63 raise IOError(num, inst)
64 except urlerr.urlerror as inst:
64 except urlerr.urlerror as inst:
65 raise IOError(None, inst.reason[1])
65 raise IOError(None, inst.reason[1])
66
66
67 if code == 200:
67 if code == 200:
68 # HTTPRangeHandler does nothing if remote does not support
68 # HTTPRangeHandler does nothing if remote does not support
69 # Range headers and returns the full entity. Let's slice it.
69 # Range headers and returns the full entity. Let's slice it.
70 if bytes:
70 if bytes:
71 data = data[self.pos:self.pos + bytes]
71 data = data[self.pos:self.pos + bytes]
72 else:
72 else:
73 data = data[self.pos:]
73 data = data[self.pos:]
74 elif bytes:
74 elif bytes:
75 data = data[:bytes]
75 data = data[:bytes]
76 self.pos += len(data)
76 self.pos += len(data)
77 return data
77 return data
78 def readlines(self):
78 def readlines(self):
79 return self.read().splitlines(True)
79 return self.read().splitlines(True)
80 def __iter__(self):
80 def __iter__(self):
81 return iter(self.readlines())
81 return iter(self.readlines())
82 def close(self):
82 def close(self):
83 pass
83 pass
84
84
85 def build_opener(ui, authinfo):
85 def build_opener(ui, authinfo):
86 # urllib cannot handle URLs with embedded user or passwd
86 # urllib cannot handle URLs with embedded user or passwd
87 urlopener = url.opener(ui, authinfo)
87 urlopener = url.opener(ui, authinfo)
88 urlopener.add_handler(byterange.HTTPRangeHandler())
88 urlopener.add_handler(byterange.HTTPRangeHandler())
89
89
90 class statichttpvfs(vfsmod.abstractvfs):
90 class statichttpvfs(vfsmod.abstractvfs):
91 def __init__(self, base):
91 def __init__(self, base):
92 self.base = base
92 self.base = base
93
93
94 def __call__(self, path, mode='r', *args, **kw):
94 def __call__(self, path, mode='r', *args, **kw):
95 if mode not in ('r', 'rb'):
95 if mode not in ('r', 'rb'):
96 raise IOError('Permission denied')
96 raise IOError('Permission denied')
97 f = "/".join((self.base, urlreq.quote(path)))
97 f = "/".join((self.base, urlreq.quote(path)))
98 return httprangereader(f, urlopener)
98 return httprangereader(f, urlopener)
99
99
100 def join(self, path):
100 def join(self, path):
101 if path:
101 if path:
102 return pathutil.join(self.base, path)
102 return pathutil.join(self.base, path)
103 else:
103 else:
104 return self.base
104 return self.base
105
105
106 return statichttpvfs
106 return statichttpvfs
107
107
108 class statichttppeer(localrepo.localpeer):
108 class statichttppeer(localrepo.localpeer):
109 def local(self):
109 def local(self):
110 return None
110 return None
111 def canpush(self):
111 def canpush(self):
112 return False
112 return False
113
113
114 class statichttprepository(localrepo.localrepository):
114 class statichttprepository(localrepo.localrepository):
115 supported = localrepo.localrepository._basesupported
115 supported = localrepo.localrepository._basesupported
116
116
117 def __init__(self, ui, path):
117 def __init__(self, ui, path):
118 self._url = path
118 self._url = path
119 self.ui = ui
119 self.ui = ui
120
120
121 self.root = path
121 self.root = path
122 u = util.url(path.rstrip('/') + "/.hg")
122 u = util.url(path.rstrip('/') + "/.hg")
123 self.path, authinfo = u.authinfo()
123 self.path, authinfo = u.authinfo()
124
124
125 vfsclass = build_opener(ui, authinfo)
125 vfsclass = build_opener(ui, authinfo)
126 self.vfs = vfsclass(self.path)
126 self.vfs = vfsclass(self.path)
127 self.cachevfs = vfsclass(self.vfs.join('cache'))
127 self.cachevfs = vfsclass(self.vfs.join('cache'))
128 self._phasedefaults = []
128 self._phasedefaults = []
129
129
130 self.names = namespaces.namespaces()
130 self.names = namespaces.namespaces()
131 self.filtername = None
131 self.filtername = None
132
132
133 try:
133 try:
134 requirements = scmutil.readrequires(self.vfs, self.supported)
134 requirements = scmutil.readrequires(self.vfs, self.supported)
135 except IOError as inst:
135 except IOError as inst:
136 if inst.errno != errno.ENOENT:
136 if inst.errno != errno.ENOENT:
137 raise
137 raise
138 requirements = set()
138 requirements = set()
139
139
140 # check if it is a non-empty old-style repository
140 # check if it is a non-empty old-style repository
141 try:
141 try:
142 fp = self.vfs("00changelog.i")
142 fp = self.vfs("00changelog.i")
143 fp.read(1)
143 fp.read(1)
144 fp.close()
144 fp.close()
145 except IOError as inst:
145 except IOError as inst:
146 if inst.errno != errno.ENOENT:
146 if inst.errno != errno.ENOENT:
147 raise
147 raise
148 # we do not care about empty old-style repositories here
148 # we do not care about empty old-style repositories here
149 msg = _("'%s' does not appear to be an hg repository") % path
149 msg = _("'%s' does not appear to be an hg repository") % path
150 raise error.RepoError(msg)
150 raise error.RepoError(msg)
151
151
152 # setup store
152 # setup store
153 self.store = store.store(requirements, self.path, vfsclass)
153 self.store = store.store(requirements, self.path, vfsclass)
154 self.spath = self.store.path
154 self.spath = self.store.path
155 self.svfs = self.store.opener
155 self.svfs = self.store.opener
156 self.sjoin = self.store.join
156 self.sjoin = self.store.join
157 self._filecache = {}
157 self._filecache = {}
158 self.requirements = requirements
158 self.requirements = requirements
159
159
160 self.manifestlog = manifest.manifestlog(self.svfs, self)
160 self.manifestlog = manifest.manifestlog(self.svfs, self)
161 self.changelog = changelog.changelog(self.svfs)
161 self.changelog = changelog.changelog(self.svfs)
162 self._tags = None
162 self._tags = None
163 self.nodetagscache = None
163 self.nodetagscache = None
164 self._branchcaches = {}
164 self._branchcaches = {}
165 self._revbranchcache = None
165 self._revbranchcache = None
166 self.encodepats = None
166 self.encodepats = None
167 self.decodepats = None
167 self.decodepats = None
168 self._transref = None
168 self._transref = None
169 # Cache of types representing filtered repos.
170 self._filteredrepotypes = {}
171
169
172 def _restrictcapabilities(self, caps):
170 def _restrictcapabilities(self, caps):
173 caps = super(statichttprepository, self)._restrictcapabilities(caps)
171 caps = super(statichttprepository, self)._restrictcapabilities(caps)
174 return caps.difference(["pushkey"])
172 return caps.difference(["pushkey"])
175
173
176 def url(self):
174 def url(self):
177 return self._url
175 return self._url
178
176
179 def local(self):
177 def local(self):
180 return False
178 return False
181
179
182 def peer(self):
180 def peer(self):
183 return statichttppeer(self)
181 return statichttppeer(self)
184
182
185 def wlock(self, wait=True):
183 def wlock(self, wait=True):
186 raise error.LockUnavailable(0, _('lock not available'), 'lock',
184 raise error.LockUnavailable(0, _('lock not available'), 'lock',
187 _('cannot lock static-http repository'))
185 _('cannot lock static-http repository'))
188
186
189 def lock(self, wait=True):
187 def lock(self, wait=True):
190 raise error.Abort(_('cannot lock static-http repository'))
188 raise error.Abort(_('cannot lock static-http repository'))
191
189
192 def _writecaches(self):
190 def _writecaches(self):
193 pass # statichttprepository are read only
191 pass # statichttprepository are read only
194
192
195 def instance(ui, path, create):
193 def instance(ui, path, create):
196 if create:
194 if create:
197 raise error.Abort(_('cannot create new static-http repository'))
195 raise error.Abort(_('cannot create new static-http repository'))
198 return statichttprepository(ui, path[7:])
196 return statichttprepository(ui, path[7:])
General Comments 0
You need to be logged in to leave comments. Login now