##// END OF EJS Templates
tags: cache `repo.changelog` access when checking tags nodes...
Boris Feld -
r40776:300f8564 default
parent child Browse files
Show More
@@ -1,3062 +1,3063 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 os
12 import os
13 import random
13 import random
14 import sys
14 import sys
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 bin,
20 bin,
21 hex,
21 hex,
22 nullid,
22 nullid,
23 nullrev,
23 nullrev,
24 short,
24 short,
25 )
25 )
26 from . import (
26 from . import (
27 bookmarks,
27 bookmarks,
28 branchmap,
28 branchmap,
29 bundle2,
29 bundle2,
30 changegroup,
30 changegroup,
31 changelog,
31 changelog,
32 color,
32 color,
33 context,
33 context,
34 dirstate,
34 dirstate,
35 dirstateguard,
35 dirstateguard,
36 discovery,
36 discovery,
37 encoding,
37 encoding,
38 error,
38 error,
39 exchange,
39 exchange,
40 extensions,
40 extensions,
41 filelog,
41 filelog,
42 hook,
42 hook,
43 lock as lockmod,
43 lock as lockmod,
44 manifest,
44 manifest,
45 match as matchmod,
45 match as matchmod,
46 merge as mergemod,
46 merge as mergemod,
47 mergeutil,
47 mergeutil,
48 namespaces,
48 namespaces,
49 narrowspec,
49 narrowspec,
50 obsolete,
50 obsolete,
51 pathutil,
51 pathutil,
52 phases,
52 phases,
53 pushkey,
53 pushkey,
54 pycompat,
54 pycompat,
55 repository,
55 repository,
56 repoview,
56 repoview,
57 revset,
57 revset,
58 revsetlang,
58 revsetlang,
59 scmutil,
59 scmutil,
60 sparse,
60 sparse,
61 store as storemod,
61 store as storemod,
62 subrepoutil,
62 subrepoutil,
63 tags as tagsmod,
63 tags as tagsmod,
64 transaction,
64 transaction,
65 txnutil,
65 txnutil,
66 util,
66 util,
67 vfs as vfsmod,
67 vfs as vfsmod,
68 )
68 )
69 from .utils import (
69 from .utils import (
70 interfaceutil,
70 interfaceutil,
71 procutil,
71 procutil,
72 stringutil,
72 stringutil,
73 )
73 )
74
74
75 from .revlogutils import (
75 from .revlogutils import (
76 constants as revlogconst,
76 constants as revlogconst,
77 )
77 )
78
78
79 release = lockmod.release
79 release = lockmod.release
80 urlerr = util.urlerr
80 urlerr = util.urlerr
81 urlreq = util.urlreq
81 urlreq = util.urlreq
82
82
83 # set of (path, vfs-location) tuples. vfs-location is:
83 # set of (path, vfs-location) tuples. vfs-location is:
84 # - 'plain for vfs relative paths
84 # - 'plain for vfs relative paths
85 # - '' for svfs relative paths
85 # - '' for svfs relative paths
86 _cachedfiles = set()
86 _cachedfiles = set()
87
87
88 class _basefilecache(scmutil.filecache):
88 class _basefilecache(scmutil.filecache):
89 """All filecache usage on repo are done for logic that should be unfiltered
89 """All filecache usage on repo are done for logic that should be unfiltered
90 """
90 """
91 def __get__(self, repo, type=None):
91 def __get__(self, repo, type=None):
92 if repo is None:
92 if repo is None:
93 return self
93 return self
94 # proxy to unfiltered __dict__ since filtered repo has no entry
94 # proxy to unfiltered __dict__ since filtered repo has no entry
95 unfi = repo.unfiltered()
95 unfi = repo.unfiltered()
96 try:
96 try:
97 return unfi.__dict__[self.sname]
97 return unfi.__dict__[self.sname]
98 except KeyError:
98 except KeyError:
99 pass
99 pass
100 return super(_basefilecache, self).__get__(unfi, type)
100 return super(_basefilecache, self).__get__(unfi, type)
101
101
102 def set(self, repo, value):
102 def set(self, repo, value):
103 return super(_basefilecache, self).set(repo.unfiltered(), value)
103 return super(_basefilecache, self).set(repo.unfiltered(), value)
104
104
105 class repofilecache(_basefilecache):
105 class repofilecache(_basefilecache):
106 """filecache for files in .hg but outside of .hg/store"""
106 """filecache for files in .hg but outside of .hg/store"""
107 def __init__(self, *paths):
107 def __init__(self, *paths):
108 super(repofilecache, self).__init__(*paths)
108 super(repofilecache, self).__init__(*paths)
109 for path in paths:
109 for path in paths:
110 _cachedfiles.add((path, 'plain'))
110 _cachedfiles.add((path, 'plain'))
111
111
112 def join(self, obj, fname):
112 def join(self, obj, fname):
113 return obj.vfs.join(fname)
113 return obj.vfs.join(fname)
114
114
115 class storecache(_basefilecache):
115 class storecache(_basefilecache):
116 """filecache for files in the store"""
116 """filecache for files in the store"""
117 def __init__(self, *paths):
117 def __init__(self, *paths):
118 super(storecache, self).__init__(*paths)
118 super(storecache, self).__init__(*paths)
119 for path in paths:
119 for path in paths:
120 _cachedfiles.add((path, ''))
120 _cachedfiles.add((path, ''))
121
121
122 def join(self, obj, fname):
122 def join(self, obj, fname):
123 return obj.sjoin(fname)
123 return obj.sjoin(fname)
124
124
125 def isfilecached(repo, name):
125 def isfilecached(repo, name):
126 """check if a repo has already cached "name" filecache-ed property
126 """check if a repo has already cached "name" filecache-ed property
127
127
128 This returns (cachedobj-or-None, iscached) tuple.
128 This returns (cachedobj-or-None, iscached) tuple.
129 """
129 """
130 cacheentry = repo.unfiltered()._filecache.get(name, None)
130 cacheentry = repo.unfiltered()._filecache.get(name, None)
131 if not cacheentry:
131 if not cacheentry:
132 return None, False
132 return None, False
133 return cacheentry.obj, True
133 return cacheentry.obj, True
134
134
135 class unfilteredpropertycache(util.propertycache):
135 class unfilteredpropertycache(util.propertycache):
136 """propertycache that apply to unfiltered repo only"""
136 """propertycache that apply to unfiltered repo only"""
137
137
138 def __get__(self, repo, type=None):
138 def __get__(self, repo, type=None):
139 unfi = repo.unfiltered()
139 unfi = repo.unfiltered()
140 if unfi is repo:
140 if unfi is repo:
141 return super(unfilteredpropertycache, self).__get__(unfi)
141 return super(unfilteredpropertycache, self).__get__(unfi)
142 return getattr(unfi, self.name)
142 return getattr(unfi, self.name)
143
143
144 class filteredpropertycache(util.propertycache):
144 class filteredpropertycache(util.propertycache):
145 """propertycache that must take filtering in account"""
145 """propertycache that must take filtering in account"""
146
146
147 def cachevalue(self, obj, value):
147 def cachevalue(self, obj, value):
148 object.__setattr__(obj, self.name, value)
148 object.__setattr__(obj, self.name, value)
149
149
150
150
151 def hasunfilteredcache(repo, name):
151 def hasunfilteredcache(repo, name):
152 """check if a repo has an unfilteredpropertycache value for <name>"""
152 """check if a repo has an unfilteredpropertycache value for <name>"""
153 return name in vars(repo.unfiltered())
153 return name in vars(repo.unfiltered())
154
154
155 def unfilteredmethod(orig):
155 def unfilteredmethod(orig):
156 """decorate method that always need to be run on unfiltered version"""
156 """decorate method that always need to be run on unfiltered version"""
157 def wrapper(repo, *args, **kwargs):
157 def wrapper(repo, *args, **kwargs):
158 return orig(repo.unfiltered(), *args, **kwargs)
158 return orig(repo.unfiltered(), *args, **kwargs)
159 return wrapper
159 return wrapper
160
160
161 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
161 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
162 'unbundle'}
162 'unbundle'}
163 legacycaps = moderncaps.union({'changegroupsubset'})
163 legacycaps = moderncaps.union({'changegroupsubset'})
164
164
165 @interfaceutil.implementer(repository.ipeercommandexecutor)
165 @interfaceutil.implementer(repository.ipeercommandexecutor)
166 class localcommandexecutor(object):
166 class localcommandexecutor(object):
167 def __init__(self, peer):
167 def __init__(self, peer):
168 self._peer = peer
168 self._peer = peer
169 self._sent = False
169 self._sent = False
170 self._closed = False
170 self._closed = False
171
171
172 def __enter__(self):
172 def __enter__(self):
173 return self
173 return self
174
174
175 def __exit__(self, exctype, excvalue, exctb):
175 def __exit__(self, exctype, excvalue, exctb):
176 self.close()
176 self.close()
177
177
178 def callcommand(self, command, args):
178 def callcommand(self, command, args):
179 if self._sent:
179 if self._sent:
180 raise error.ProgrammingError('callcommand() cannot be used after '
180 raise error.ProgrammingError('callcommand() cannot be used after '
181 'sendcommands()')
181 'sendcommands()')
182
182
183 if self._closed:
183 if self._closed:
184 raise error.ProgrammingError('callcommand() cannot be used after '
184 raise error.ProgrammingError('callcommand() cannot be used after '
185 'close()')
185 'close()')
186
186
187 # We don't need to support anything fancy. Just call the named
187 # We don't need to support anything fancy. Just call the named
188 # method on the peer and return a resolved future.
188 # method on the peer and return a resolved future.
189 fn = getattr(self._peer, pycompat.sysstr(command))
189 fn = getattr(self._peer, pycompat.sysstr(command))
190
190
191 f = pycompat.futures.Future()
191 f = pycompat.futures.Future()
192
192
193 try:
193 try:
194 result = fn(**pycompat.strkwargs(args))
194 result = fn(**pycompat.strkwargs(args))
195 except Exception:
195 except Exception:
196 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
196 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
197 else:
197 else:
198 f.set_result(result)
198 f.set_result(result)
199
199
200 return f
200 return f
201
201
202 def sendcommands(self):
202 def sendcommands(self):
203 self._sent = True
203 self._sent = True
204
204
205 def close(self):
205 def close(self):
206 self._closed = True
206 self._closed = True
207
207
208 @interfaceutil.implementer(repository.ipeercommands)
208 @interfaceutil.implementer(repository.ipeercommands)
209 class localpeer(repository.peer):
209 class localpeer(repository.peer):
210 '''peer for a local repo; reflects only the most recent API'''
210 '''peer for a local repo; reflects only the most recent API'''
211
211
212 def __init__(self, repo, caps=None):
212 def __init__(self, repo, caps=None):
213 super(localpeer, self).__init__()
213 super(localpeer, self).__init__()
214
214
215 if caps is None:
215 if caps is None:
216 caps = moderncaps.copy()
216 caps = moderncaps.copy()
217 self._repo = repo.filtered('served')
217 self._repo = repo.filtered('served')
218 self.ui = repo.ui
218 self.ui = repo.ui
219 self._caps = repo._restrictcapabilities(caps)
219 self._caps = repo._restrictcapabilities(caps)
220
220
221 # Begin of _basepeer interface.
221 # Begin of _basepeer interface.
222
222
223 def url(self):
223 def url(self):
224 return self._repo.url()
224 return self._repo.url()
225
225
226 def local(self):
226 def local(self):
227 return self._repo
227 return self._repo
228
228
229 def peer(self):
229 def peer(self):
230 return self
230 return self
231
231
232 def canpush(self):
232 def canpush(self):
233 return True
233 return True
234
234
235 def close(self):
235 def close(self):
236 self._repo.close()
236 self._repo.close()
237
237
238 # End of _basepeer interface.
238 # End of _basepeer interface.
239
239
240 # Begin of _basewirecommands interface.
240 # Begin of _basewirecommands interface.
241
241
242 def branchmap(self):
242 def branchmap(self):
243 return self._repo.branchmap()
243 return self._repo.branchmap()
244
244
245 def capabilities(self):
245 def capabilities(self):
246 return self._caps
246 return self._caps
247
247
248 def clonebundles(self):
248 def clonebundles(self):
249 return self._repo.tryread('clonebundles.manifest')
249 return self._repo.tryread('clonebundles.manifest')
250
250
251 def debugwireargs(self, one, two, three=None, four=None, five=None):
251 def debugwireargs(self, one, two, three=None, four=None, five=None):
252 """Used to test argument passing over the wire"""
252 """Used to test argument passing over the wire"""
253 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
253 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
254 pycompat.bytestr(four),
254 pycompat.bytestr(four),
255 pycompat.bytestr(five))
255 pycompat.bytestr(five))
256
256
257 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
257 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
258 **kwargs):
258 **kwargs):
259 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
259 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
260 common=common, bundlecaps=bundlecaps,
260 common=common, bundlecaps=bundlecaps,
261 **kwargs)[1]
261 **kwargs)[1]
262 cb = util.chunkbuffer(chunks)
262 cb = util.chunkbuffer(chunks)
263
263
264 if exchange.bundle2requested(bundlecaps):
264 if exchange.bundle2requested(bundlecaps):
265 # When requesting a bundle2, getbundle returns a stream to make the
265 # When requesting a bundle2, getbundle returns a stream to make the
266 # wire level function happier. We need to build a proper object
266 # wire level function happier. We need to build a proper object
267 # from it in local peer.
267 # from it in local peer.
268 return bundle2.getunbundler(self.ui, cb)
268 return bundle2.getunbundler(self.ui, cb)
269 else:
269 else:
270 return changegroup.getunbundler('01', cb, None)
270 return changegroup.getunbundler('01', cb, None)
271
271
272 def heads(self):
272 def heads(self):
273 return self._repo.heads()
273 return self._repo.heads()
274
274
275 def known(self, nodes):
275 def known(self, nodes):
276 return self._repo.known(nodes)
276 return self._repo.known(nodes)
277
277
278 def listkeys(self, namespace):
278 def listkeys(self, namespace):
279 return self._repo.listkeys(namespace)
279 return self._repo.listkeys(namespace)
280
280
281 def lookup(self, key):
281 def lookup(self, key):
282 return self._repo.lookup(key)
282 return self._repo.lookup(key)
283
283
284 def pushkey(self, namespace, key, old, new):
284 def pushkey(self, namespace, key, old, new):
285 return self._repo.pushkey(namespace, key, old, new)
285 return self._repo.pushkey(namespace, key, old, new)
286
286
287 def stream_out(self):
287 def stream_out(self):
288 raise error.Abort(_('cannot perform stream clone against local '
288 raise error.Abort(_('cannot perform stream clone against local '
289 'peer'))
289 'peer'))
290
290
291 def unbundle(self, bundle, heads, url):
291 def unbundle(self, bundle, heads, url):
292 """apply a bundle on a repo
292 """apply a bundle on a repo
293
293
294 This function handles the repo locking itself."""
294 This function handles the repo locking itself."""
295 try:
295 try:
296 try:
296 try:
297 bundle = exchange.readbundle(self.ui, bundle, None)
297 bundle = exchange.readbundle(self.ui, bundle, None)
298 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
298 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
299 if util.safehasattr(ret, 'getchunks'):
299 if util.safehasattr(ret, 'getchunks'):
300 # This is a bundle20 object, turn it into an unbundler.
300 # This is a bundle20 object, turn it into an unbundler.
301 # This little dance should be dropped eventually when the
301 # This little dance should be dropped eventually when the
302 # API is finally improved.
302 # API is finally improved.
303 stream = util.chunkbuffer(ret.getchunks())
303 stream = util.chunkbuffer(ret.getchunks())
304 ret = bundle2.getunbundler(self.ui, stream)
304 ret = bundle2.getunbundler(self.ui, stream)
305 return ret
305 return ret
306 except Exception as exc:
306 except Exception as exc:
307 # If the exception contains output salvaged from a bundle2
307 # If the exception contains output salvaged from a bundle2
308 # reply, we need to make sure it is printed before continuing
308 # reply, we need to make sure it is printed before continuing
309 # to fail. So we build a bundle2 with such output and consume
309 # to fail. So we build a bundle2 with such output and consume
310 # it directly.
310 # it directly.
311 #
311 #
312 # This is not very elegant but allows a "simple" solution for
312 # This is not very elegant but allows a "simple" solution for
313 # issue4594
313 # issue4594
314 output = getattr(exc, '_bundle2salvagedoutput', ())
314 output = getattr(exc, '_bundle2salvagedoutput', ())
315 if output:
315 if output:
316 bundler = bundle2.bundle20(self._repo.ui)
316 bundler = bundle2.bundle20(self._repo.ui)
317 for out in output:
317 for out in output:
318 bundler.addpart(out)
318 bundler.addpart(out)
319 stream = util.chunkbuffer(bundler.getchunks())
319 stream = util.chunkbuffer(bundler.getchunks())
320 b = bundle2.getunbundler(self.ui, stream)
320 b = bundle2.getunbundler(self.ui, stream)
321 bundle2.processbundle(self._repo, b)
321 bundle2.processbundle(self._repo, b)
322 raise
322 raise
323 except error.PushRaced as exc:
323 except error.PushRaced as exc:
324 raise error.ResponseError(_('push failed:'),
324 raise error.ResponseError(_('push failed:'),
325 stringutil.forcebytestr(exc))
325 stringutil.forcebytestr(exc))
326
326
327 # End of _basewirecommands interface.
327 # End of _basewirecommands interface.
328
328
329 # Begin of peer interface.
329 # Begin of peer interface.
330
330
331 def commandexecutor(self):
331 def commandexecutor(self):
332 return localcommandexecutor(self)
332 return localcommandexecutor(self)
333
333
334 # End of peer interface.
334 # End of peer interface.
335
335
336 @interfaceutil.implementer(repository.ipeerlegacycommands)
336 @interfaceutil.implementer(repository.ipeerlegacycommands)
337 class locallegacypeer(localpeer):
337 class locallegacypeer(localpeer):
338 '''peer extension which implements legacy methods too; used for tests with
338 '''peer extension which implements legacy methods too; used for tests with
339 restricted capabilities'''
339 restricted capabilities'''
340
340
341 def __init__(self, repo):
341 def __init__(self, repo):
342 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
342 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
343
343
344 # Begin of baselegacywirecommands interface.
344 # Begin of baselegacywirecommands interface.
345
345
346 def between(self, pairs):
346 def between(self, pairs):
347 return self._repo.between(pairs)
347 return self._repo.between(pairs)
348
348
349 def branches(self, nodes):
349 def branches(self, nodes):
350 return self._repo.branches(nodes)
350 return self._repo.branches(nodes)
351
351
352 def changegroup(self, nodes, source):
352 def changegroup(self, nodes, source):
353 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
353 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
354 missingheads=self._repo.heads())
354 missingheads=self._repo.heads())
355 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
355 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
356
356
357 def changegroupsubset(self, bases, heads, source):
357 def changegroupsubset(self, bases, heads, source):
358 outgoing = discovery.outgoing(self._repo, missingroots=bases,
358 outgoing = discovery.outgoing(self._repo, missingroots=bases,
359 missingheads=heads)
359 missingheads=heads)
360 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
360 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
361
361
362 # End of baselegacywirecommands interface.
362 # End of baselegacywirecommands interface.
363
363
364 # Increment the sub-version when the revlog v2 format changes to lock out old
364 # Increment the sub-version when the revlog v2 format changes to lock out old
365 # clients.
365 # clients.
366 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
366 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
367
367
368 # A repository with the sparserevlog feature will have delta chains that
368 # A repository with the sparserevlog feature will have delta chains that
369 # can spread over a larger span. Sparse reading cuts these large spans into
369 # can spread over a larger span. Sparse reading cuts these large spans into
370 # pieces, so that each piece isn't too big.
370 # pieces, so that each piece isn't too big.
371 # Without the sparserevlog capability, reading from the repository could use
371 # Without the sparserevlog capability, reading from the repository could use
372 # huge amounts of memory, because the whole span would be read at once,
372 # huge amounts of memory, because the whole span would be read at once,
373 # including all the intermediate revisions that aren't pertinent for the chain.
373 # including all the intermediate revisions that aren't pertinent for the chain.
374 # This is why once a repository has enabled sparse-read, it becomes required.
374 # This is why once a repository has enabled sparse-read, it becomes required.
375 SPARSEREVLOG_REQUIREMENT = 'sparserevlog'
375 SPARSEREVLOG_REQUIREMENT = 'sparserevlog'
376
376
377 # Functions receiving (ui, features) that extensions can register to impact
377 # Functions receiving (ui, features) that extensions can register to impact
378 # the ability to load repositories with custom requirements. Only
378 # the ability to load repositories with custom requirements. Only
379 # functions defined in loaded extensions are called.
379 # functions defined in loaded extensions are called.
380 #
380 #
381 # The function receives a set of requirement strings that the repository
381 # The function receives a set of requirement strings that the repository
382 # is capable of opening. Functions will typically add elements to the
382 # is capable of opening. Functions will typically add elements to the
383 # set to reflect that the extension knows how to handle that requirements.
383 # set to reflect that the extension knows how to handle that requirements.
384 featuresetupfuncs = set()
384 featuresetupfuncs = set()
385
385
386 def makelocalrepository(baseui, path, intents=None):
386 def makelocalrepository(baseui, path, intents=None):
387 """Create a local repository object.
387 """Create a local repository object.
388
388
389 Given arguments needed to construct a local repository, this function
389 Given arguments needed to construct a local repository, this function
390 performs various early repository loading functionality (such as
390 performs various early repository loading functionality (such as
391 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
391 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
392 the repository can be opened, derives a type suitable for representing
392 the repository can be opened, derives a type suitable for representing
393 that repository, and returns an instance of it.
393 that repository, and returns an instance of it.
394
394
395 The returned object conforms to the ``repository.completelocalrepository``
395 The returned object conforms to the ``repository.completelocalrepository``
396 interface.
396 interface.
397
397
398 The repository type is derived by calling a series of factory functions
398 The repository type is derived by calling a series of factory functions
399 for each aspect/interface of the final repository. These are defined by
399 for each aspect/interface of the final repository. These are defined by
400 ``REPO_INTERFACES``.
400 ``REPO_INTERFACES``.
401
401
402 Each factory function is called to produce a type implementing a specific
402 Each factory function is called to produce a type implementing a specific
403 interface. The cumulative list of returned types will be combined into a
403 interface. The cumulative list of returned types will be combined into a
404 new type and that type will be instantiated to represent the local
404 new type and that type will be instantiated to represent the local
405 repository.
405 repository.
406
406
407 The factory functions each receive various state that may be consulted
407 The factory functions each receive various state that may be consulted
408 as part of deriving a type.
408 as part of deriving a type.
409
409
410 Extensions should wrap these factory functions to customize repository type
410 Extensions should wrap these factory functions to customize repository type
411 creation. Note that an extension's wrapped function may be called even if
411 creation. Note that an extension's wrapped function may be called even if
412 that extension is not loaded for the repo being constructed. Extensions
412 that extension is not loaded for the repo being constructed. Extensions
413 should check if their ``__name__`` appears in the
413 should check if their ``__name__`` appears in the
414 ``extensionmodulenames`` set passed to the factory function and no-op if
414 ``extensionmodulenames`` set passed to the factory function and no-op if
415 not.
415 not.
416 """
416 """
417 ui = baseui.copy()
417 ui = baseui.copy()
418 # Prevent copying repo configuration.
418 # Prevent copying repo configuration.
419 ui.copy = baseui.copy
419 ui.copy = baseui.copy
420
420
421 # Working directory VFS rooted at repository root.
421 # Working directory VFS rooted at repository root.
422 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
422 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
423
423
424 # Main VFS for .hg/ directory.
424 # Main VFS for .hg/ directory.
425 hgpath = wdirvfs.join(b'.hg')
425 hgpath = wdirvfs.join(b'.hg')
426 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
426 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
427
427
428 # The .hg/ path should exist and should be a directory. All other
428 # The .hg/ path should exist and should be a directory. All other
429 # cases are errors.
429 # cases are errors.
430 if not hgvfs.isdir():
430 if not hgvfs.isdir():
431 try:
431 try:
432 hgvfs.stat()
432 hgvfs.stat()
433 except OSError as e:
433 except OSError as e:
434 if e.errno != errno.ENOENT:
434 if e.errno != errno.ENOENT:
435 raise
435 raise
436
436
437 raise error.RepoError(_(b'repository %s not found') % path)
437 raise error.RepoError(_(b'repository %s not found') % path)
438
438
439 # .hg/requires file contains a newline-delimited list of
439 # .hg/requires file contains a newline-delimited list of
440 # features/capabilities the opener (us) must have in order to use
440 # features/capabilities the opener (us) must have in order to use
441 # the repository. This file was introduced in Mercurial 0.9.2,
441 # the repository. This file was introduced in Mercurial 0.9.2,
442 # which means very old repositories may not have one. We assume
442 # which means very old repositories may not have one. We assume
443 # a missing file translates to no requirements.
443 # a missing file translates to no requirements.
444 try:
444 try:
445 requirements = set(hgvfs.read(b'requires').splitlines())
445 requirements = set(hgvfs.read(b'requires').splitlines())
446 except IOError as e:
446 except IOError as e:
447 if e.errno != errno.ENOENT:
447 if e.errno != errno.ENOENT:
448 raise
448 raise
449 requirements = set()
449 requirements = set()
450
450
451 # The .hg/hgrc file may load extensions or contain config options
451 # The .hg/hgrc file may load extensions or contain config options
452 # that influence repository construction. Attempt to load it and
452 # that influence repository construction. Attempt to load it and
453 # process any new extensions that it may have pulled in.
453 # process any new extensions that it may have pulled in.
454 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
454 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
455 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
455 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
456 extensions.loadall(ui)
456 extensions.loadall(ui)
457 extensions.populateui(ui)
457 extensions.populateui(ui)
458
458
459 # Set of module names of extensions loaded for this repository.
459 # Set of module names of extensions loaded for this repository.
460 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
460 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
461
461
462 supportedrequirements = gathersupportedrequirements(ui)
462 supportedrequirements = gathersupportedrequirements(ui)
463
463
464 # We first validate the requirements are known.
464 # We first validate the requirements are known.
465 ensurerequirementsrecognized(requirements, supportedrequirements)
465 ensurerequirementsrecognized(requirements, supportedrequirements)
466
466
467 # Then we validate that the known set is reasonable to use together.
467 # Then we validate that the known set is reasonable to use together.
468 ensurerequirementscompatible(ui, requirements)
468 ensurerequirementscompatible(ui, requirements)
469
469
470 # TODO there are unhandled edge cases related to opening repositories with
470 # TODO there are unhandled edge cases related to opening repositories with
471 # shared storage. If storage is shared, we should also test for requirements
471 # shared storage. If storage is shared, we should also test for requirements
472 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
472 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
473 # that repo, as that repo may load extensions needed to open it. This is a
473 # that repo, as that repo may load extensions needed to open it. This is a
474 # bit complicated because we don't want the other hgrc to overwrite settings
474 # bit complicated because we don't want the other hgrc to overwrite settings
475 # in this hgrc.
475 # in this hgrc.
476 #
476 #
477 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
477 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
478 # file when sharing repos. But if a requirement is added after the share is
478 # file when sharing repos. But if a requirement is added after the share is
479 # performed, thereby introducing a new requirement for the opener, we may
479 # performed, thereby introducing a new requirement for the opener, we may
480 # will not see that and could encounter a run-time error interacting with
480 # will not see that and could encounter a run-time error interacting with
481 # that shared store since it has an unknown-to-us requirement.
481 # that shared store since it has an unknown-to-us requirement.
482
482
483 # At this point, we know we should be capable of opening the repository.
483 # At this point, we know we should be capable of opening the repository.
484 # Now get on with doing that.
484 # Now get on with doing that.
485
485
486 features = set()
486 features = set()
487
487
488 # The "store" part of the repository holds versioned data. How it is
488 # The "store" part of the repository holds versioned data. How it is
489 # accessed is determined by various requirements. The ``shared`` or
489 # accessed is determined by various requirements. The ``shared`` or
490 # ``relshared`` requirements indicate the store lives in the path contained
490 # ``relshared`` requirements indicate the store lives in the path contained
491 # in the ``.hg/sharedpath`` file. This is an absolute path for
491 # in the ``.hg/sharedpath`` file. This is an absolute path for
492 # ``shared`` and relative to ``.hg/`` for ``relshared``.
492 # ``shared`` and relative to ``.hg/`` for ``relshared``.
493 if b'shared' in requirements or b'relshared' in requirements:
493 if b'shared' in requirements or b'relshared' in requirements:
494 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
494 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
495 if b'relshared' in requirements:
495 if b'relshared' in requirements:
496 sharedpath = hgvfs.join(sharedpath)
496 sharedpath = hgvfs.join(sharedpath)
497
497
498 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
498 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
499
499
500 if not sharedvfs.exists():
500 if not sharedvfs.exists():
501 raise error.RepoError(_(b'.hg/sharedpath points to nonexistent '
501 raise error.RepoError(_(b'.hg/sharedpath points to nonexistent '
502 b'directory %s') % sharedvfs.base)
502 b'directory %s') % sharedvfs.base)
503
503
504 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
504 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
505
505
506 storebasepath = sharedvfs.base
506 storebasepath = sharedvfs.base
507 cachepath = sharedvfs.join(b'cache')
507 cachepath = sharedvfs.join(b'cache')
508 else:
508 else:
509 storebasepath = hgvfs.base
509 storebasepath = hgvfs.base
510 cachepath = hgvfs.join(b'cache')
510 cachepath = hgvfs.join(b'cache')
511
511
512 # The store has changed over time and the exact layout is dictated by
512 # The store has changed over time and the exact layout is dictated by
513 # requirements. The store interface abstracts differences across all
513 # requirements. The store interface abstracts differences across all
514 # of them.
514 # of them.
515 store = makestore(requirements, storebasepath,
515 store = makestore(requirements, storebasepath,
516 lambda base: vfsmod.vfs(base, cacheaudited=True))
516 lambda base: vfsmod.vfs(base, cacheaudited=True))
517 hgvfs.createmode = store.createmode
517 hgvfs.createmode = store.createmode
518
518
519 storevfs = store.vfs
519 storevfs = store.vfs
520 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
520 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
521
521
522 # The cache vfs is used to manage cache files.
522 # The cache vfs is used to manage cache files.
523 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
523 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
524 cachevfs.createmode = store.createmode
524 cachevfs.createmode = store.createmode
525
525
526 # Now resolve the type for the repository object. We do this by repeatedly
526 # Now resolve the type for the repository object. We do this by repeatedly
527 # calling a factory function to produces types for specific aspects of the
527 # calling a factory function to produces types for specific aspects of the
528 # repo's operation. The aggregate returned types are used as base classes
528 # repo's operation. The aggregate returned types are used as base classes
529 # for a dynamically-derived type, which will represent our new repository.
529 # for a dynamically-derived type, which will represent our new repository.
530
530
531 bases = []
531 bases = []
532 extrastate = {}
532 extrastate = {}
533
533
534 for iface, fn in REPO_INTERFACES:
534 for iface, fn in REPO_INTERFACES:
535 # We pass all potentially useful state to give extensions tons of
535 # We pass all potentially useful state to give extensions tons of
536 # flexibility.
536 # flexibility.
537 typ = fn()(ui=ui,
537 typ = fn()(ui=ui,
538 intents=intents,
538 intents=intents,
539 requirements=requirements,
539 requirements=requirements,
540 features=features,
540 features=features,
541 wdirvfs=wdirvfs,
541 wdirvfs=wdirvfs,
542 hgvfs=hgvfs,
542 hgvfs=hgvfs,
543 store=store,
543 store=store,
544 storevfs=storevfs,
544 storevfs=storevfs,
545 storeoptions=storevfs.options,
545 storeoptions=storevfs.options,
546 cachevfs=cachevfs,
546 cachevfs=cachevfs,
547 extensionmodulenames=extensionmodulenames,
547 extensionmodulenames=extensionmodulenames,
548 extrastate=extrastate,
548 extrastate=extrastate,
549 baseclasses=bases)
549 baseclasses=bases)
550
550
551 if not isinstance(typ, type):
551 if not isinstance(typ, type):
552 raise error.ProgrammingError('unable to construct type for %s' %
552 raise error.ProgrammingError('unable to construct type for %s' %
553 iface)
553 iface)
554
554
555 bases.append(typ)
555 bases.append(typ)
556
556
557 # type() allows you to use characters in type names that wouldn't be
557 # type() allows you to use characters in type names that wouldn't be
558 # recognized as Python symbols in source code. We abuse that to add
558 # recognized as Python symbols in source code. We abuse that to add
559 # rich information about our constructed repo.
559 # rich information about our constructed repo.
560 name = pycompat.sysstr(b'derivedrepo:%s<%s>' % (
560 name = pycompat.sysstr(b'derivedrepo:%s<%s>' % (
561 wdirvfs.base,
561 wdirvfs.base,
562 b','.join(sorted(requirements))))
562 b','.join(sorted(requirements))))
563
563
564 cls = type(name, tuple(bases), {})
564 cls = type(name, tuple(bases), {})
565
565
566 return cls(
566 return cls(
567 baseui=baseui,
567 baseui=baseui,
568 ui=ui,
568 ui=ui,
569 origroot=path,
569 origroot=path,
570 wdirvfs=wdirvfs,
570 wdirvfs=wdirvfs,
571 hgvfs=hgvfs,
571 hgvfs=hgvfs,
572 requirements=requirements,
572 requirements=requirements,
573 supportedrequirements=supportedrequirements,
573 supportedrequirements=supportedrequirements,
574 sharedpath=storebasepath,
574 sharedpath=storebasepath,
575 store=store,
575 store=store,
576 cachevfs=cachevfs,
576 cachevfs=cachevfs,
577 features=features,
577 features=features,
578 intents=intents)
578 intents=intents)
579
579
580 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
580 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
581 """Load hgrc files/content into a ui instance.
581 """Load hgrc files/content into a ui instance.
582
582
583 This is called during repository opening to load any additional
583 This is called during repository opening to load any additional
584 config files or settings relevant to the current repository.
584 config files or settings relevant to the current repository.
585
585
586 Returns a bool indicating whether any additional configs were loaded.
586 Returns a bool indicating whether any additional configs were loaded.
587
587
588 Extensions should monkeypatch this function to modify how per-repo
588 Extensions should monkeypatch this function to modify how per-repo
589 configs are loaded. For example, an extension may wish to pull in
589 configs are loaded. For example, an extension may wish to pull in
590 configs from alternate files or sources.
590 configs from alternate files or sources.
591 """
591 """
592 try:
592 try:
593 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
593 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
594 return True
594 return True
595 except IOError:
595 except IOError:
596 return False
596 return False
597
597
598 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
598 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
599 """Perform additional actions after .hg/hgrc is loaded.
599 """Perform additional actions after .hg/hgrc is loaded.
600
600
601 This function is called during repository loading immediately after
601 This function is called during repository loading immediately after
602 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
602 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
603
603
604 The function can be used to validate configs, automatically add
604 The function can be used to validate configs, automatically add
605 options (including extensions) based on requirements, etc.
605 options (including extensions) based on requirements, etc.
606 """
606 """
607
607
608 # Map of requirements to list of extensions to load automatically when
608 # Map of requirements to list of extensions to load automatically when
609 # requirement is present.
609 # requirement is present.
610 autoextensions = {
610 autoextensions = {
611 b'largefiles': [b'largefiles'],
611 b'largefiles': [b'largefiles'],
612 b'lfs': [b'lfs'],
612 b'lfs': [b'lfs'],
613 }
613 }
614
614
615 for requirement, names in sorted(autoextensions.items()):
615 for requirement, names in sorted(autoextensions.items()):
616 if requirement not in requirements:
616 if requirement not in requirements:
617 continue
617 continue
618
618
619 for name in names:
619 for name in names:
620 if not ui.hasconfig(b'extensions', name):
620 if not ui.hasconfig(b'extensions', name):
621 ui.setconfig(b'extensions', name, b'', source='autoload')
621 ui.setconfig(b'extensions', name, b'', source='autoload')
622
622
623 def gathersupportedrequirements(ui):
623 def gathersupportedrequirements(ui):
624 """Determine the complete set of recognized requirements."""
624 """Determine the complete set of recognized requirements."""
625 # Start with all requirements supported by this file.
625 # Start with all requirements supported by this file.
626 supported = set(localrepository._basesupported)
626 supported = set(localrepository._basesupported)
627
627
628 # Execute ``featuresetupfuncs`` entries if they belong to an extension
628 # Execute ``featuresetupfuncs`` entries if they belong to an extension
629 # relevant to this ui instance.
629 # relevant to this ui instance.
630 modules = {m.__name__ for n, m in extensions.extensions(ui)}
630 modules = {m.__name__ for n, m in extensions.extensions(ui)}
631
631
632 for fn in featuresetupfuncs:
632 for fn in featuresetupfuncs:
633 if fn.__module__ in modules:
633 if fn.__module__ in modules:
634 fn(ui, supported)
634 fn(ui, supported)
635
635
636 # Add derived requirements from registered compression engines.
636 # Add derived requirements from registered compression engines.
637 for name in util.compengines:
637 for name in util.compengines:
638 engine = util.compengines[name]
638 engine = util.compengines[name]
639 if engine.revlogheader():
639 if engine.revlogheader():
640 supported.add(b'exp-compression-%s' % name)
640 supported.add(b'exp-compression-%s' % name)
641
641
642 return supported
642 return supported
643
643
644 def ensurerequirementsrecognized(requirements, supported):
644 def ensurerequirementsrecognized(requirements, supported):
645 """Validate that a set of local requirements is recognized.
645 """Validate that a set of local requirements is recognized.
646
646
647 Receives a set of requirements. Raises an ``error.RepoError`` if there
647 Receives a set of requirements. Raises an ``error.RepoError`` if there
648 exists any requirement in that set that currently loaded code doesn't
648 exists any requirement in that set that currently loaded code doesn't
649 recognize.
649 recognize.
650
650
651 Returns a set of supported requirements.
651 Returns a set of supported requirements.
652 """
652 """
653 missing = set()
653 missing = set()
654
654
655 for requirement in requirements:
655 for requirement in requirements:
656 if requirement in supported:
656 if requirement in supported:
657 continue
657 continue
658
658
659 if not requirement or not requirement[0:1].isalnum():
659 if not requirement or not requirement[0:1].isalnum():
660 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
660 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
661
661
662 missing.add(requirement)
662 missing.add(requirement)
663
663
664 if missing:
664 if missing:
665 raise error.RequirementError(
665 raise error.RequirementError(
666 _(b'repository requires features unknown to this Mercurial: %s') %
666 _(b'repository requires features unknown to this Mercurial: %s') %
667 b' '.join(sorted(missing)),
667 b' '.join(sorted(missing)),
668 hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement '
668 hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement '
669 b'for more information'))
669 b'for more information'))
670
670
671 def ensurerequirementscompatible(ui, requirements):
671 def ensurerequirementscompatible(ui, requirements):
672 """Validates that a set of recognized requirements is mutually compatible.
672 """Validates that a set of recognized requirements is mutually compatible.
673
673
674 Some requirements may not be compatible with others or require
674 Some requirements may not be compatible with others or require
675 config options that aren't enabled. This function is called during
675 config options that aren't enabled. This function is called during
676 repository opening to ensure that the set of requirements needed
676 repository opening to ensure that the set of requirements needed
677 to open a repository is sane and compatible with config options.
677 to open a repository is sane and compatible with config options.
678
678
679 Extensions can monkeypatch this function to perform additional
679 Extensions can monkeypatch this function to perform additional
680 checking.
680 checking.
681
681
682 ``error.RepoError`` should be raised on failure.
682 ``error.RepoError`` should be raised on failure.
683 """
683 """
684 if b'exp-sparse' in requirements and not sparse.enabled:
684 if b'exp-sparse' in requirements and not sparse.enabled:
685 raise error.RepoError(_(b'repository is using sparse feature but '
685 raise error.RepoError(_(b'repository is using sparse feature but '
686 b'sparse is not enabled; enable the '
686 b'sparse is not enabled; enable the '
687 b'"sparse" extensions to access'))
687 b'"sparse" extensions to access'))
688
688
689 def makestore(requirements, path, vfstype):
689 def makestore(requirements, path, vfstype):
690 """Construct a storage object for a repository."""
690 """Construct a storage object for a repository."""
691 if b'store' in requirements:
691 if b'store' in requirements:
692 if b'fncache' in requirements:
692 if b'fncache' in requirements:
693 return storemod.fncachestore(path, vfstype,
693 return storemod.fncachestore(path, vfstype,
694 b'dotencode' in requirements)
694 b'dotencode' in requirements)
695
695
696 return storemod.encodedstore(path, vfstype)
696 return storemod.encodedstore(path, vfstype)
697
697
698 return storemod.basicstore(path, vfstype)
698 return storemod.basicstore(path, vfstype)
699
699
700 def resolvestorevfsoptions(ui, requirements, features):
700 def resolvestorevfsoptions(ui, requirements, features):
701 """Resolve the options to pass to the store vfs opener.
701 """Resolve the options to pass to the store vfs opener.
702
702
703 The returned dict is used to influence behavior of the storage layer.
703 The returned dict is used to influence behavior of the storage layer.
704 """
704 """
705 options = {}
705 options = {}
706
706
707 if b'treemanifest' in requirements:
707 if b'treemanifest' in requirements:
708 options[b'treemanifest'] = True
708 options[b'treemanifest'] = True
709
709
710 # experimental config: format.manifestcachesize
710 # experimental config: format.manifestcachesize
711 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
711 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
712 if manifestcachesize is not None:
712 if manifestcachesize is not None:
713 options[b'manifestcachesize'] = manifestcachesize
713 options[b'manifestcachesize'] = manifestcachesize
714
714
715 # In the absence of another requirement superseding a revlog-related
715 # In the absence of another requirement superseding a revlog-related
716 # requirement, we have to assume the repo is using revlog version 0.
716 # requirement, we have to assume the repo is using revlog version 0.
717 # This revlog format is super old and we don't bother trying to parse
717 # This revlog format is super old and we don't bother trying to parse
718 # opener options for it because those options wouldn't do anything
718 # opener options for it because those options wouldn't do anything
719 # meaningful on such old repos.
719 # meaningful on such old repos.
720 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
720 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
721 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
721 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
722
722
723 return options
723 return options
724
724
725 def resolverevlogstorevfsoptions(ui, requirements, features):
725 def resolverevlogstorevfsoptions(ui, requirements, features):
726 """Resolve opener options specific to revlogs."""
726 """Resolve opener options specific to revlogs."""
727
727
728 options = {}
728 options = {}
729 options[b'flagprocessors'] = {}
729 options[b'flagprocessors'] = {}
730
730
731 if b'revlogv1' in requirements:
731 if b'revlogv1' in requirements:
732 options[b'revlogv1'] = True
732 options[b'revlogv1'] = True
733 if REVLOGV2_REQUIREMENT in requirements:
733 if REVLOGV2_REQUIREMENT in requirements:
734 options[b'revlogv2'] = True
734 options[b'revlogv2'] = True
735
735
736 if b'generaldelta' in requirements:
736 if b'generaldelta' in requirements:
737 options[b'generaldelta'] = True
737 options[b'generaldelta'] = True
738
738
739 # experimental config: format.chunkcachesize
739 # experimental config: format.chunkcachesize
740 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
740 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
741 if chunkcachesize is not None:
741 if chunkcachesize is not None:
742 options[b'chunkcachesize'] = chunkcachesize
742 options[b'chunkcachesize'] = chunkcachesize
743
743
744 deltabothparents = ui.configbool(b'storage',
744 deltabothparents = ui.configbool(b'storage',
745 b'revlog.optimize-delta-parent-choice')
745 b'revlog.optimize-delta-parent-choice')
746 options[b'deltabothparents'] = deltabothparents
746 options[b'deltabothparents'] = deltabothparents
747
747
748 options[b'lazydeltabase'] = not scmutil.gddeltaconfig(ui)
748 options[b'lazydeltabase'] = not scmutil.gddeltaconfig(ui)
749
749
750 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
750 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
751 if 0 <= chainspan:
751 if 0 <= chainspan:
752 options[b'maxdeltachainspan'] = chainspan
752 options[b'maxdeltachainspan'] = chainspan
753
753
754 mmapindexthreshold = ui.configbytes(b'experimental',
754 mmapindexthreshold = ui.configbytes(b'experimental',
755 b'mmapindexthreshold')
755 b'mmapindexthreshold')
756 if mmapindexthreshold is not None:
756 if mmapindexthreshold is not None:
757 options[b'mmapindexthreshold'] = mmapindexthreshold
757 options[b'mmapindexthreshold'] = mmapindexthreshold
758
758
759 withsparseread = ui.configbool(b'experimental', b'sparse-read')
759 withsparseread = ui.configbool(b'experimental', b'sparse-read')
760 srdensitythres = float(ui.config(b'experimental',
760 srdensitythres = float(ui.config(b'experimental',
761 b'sparse-read.density-threshold'))
761 b'sparse-read.density-threshold'))
762 srmingapsize = ui.configbytes(b'experimental',
762 srmingapsize = ui.configbytes(b'experimental',
763 b'sparse-read.min-gap-size')
763 b'sparse-read.min-gap-size')
764 options[b'with-sparse-read'] = withsparseread
764 options[b'with-sparse-read'] = withsparseread
765 options[b'sparse-read-density-threshold'] = srdensitythres
765 options[b'sparse-read-density-threshold'] = srdensitythres
766 options[b'sparse-read-min-gap-size'] = srmingapsize
766 options[b'sparse-read-min-gap-size'] = srmingapsize
767
767
768 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
768 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
769 options[b'sparse-revlog'] = sparserevlog
769 options[b'sparse-revlog'] = sparserevlog
770 if sparserevlog:
770 if sparserevlog:
771 options[b'generaldelta'] = True
771 options[b'generaldelta'] = True
772
772
773 maxchainlen = None
773 maxchainlen = None
774 if sparserevlog:
774 if sparserevlog:
775 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
775 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
776 # experimental config: format.maxchainlen
776 # experimental config: format.maxchainlen
777 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
777 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
778 if maxchainlen is not None:
778 if maxchainlen is not None:
779 options[b'maxchainlen'] = maxchainlen
779 options[b'maxchainlen'] = maxchainlen
780
780
781 for r in requirements:
781 for r in requirements:
782 if r.startswith(b'exp-compression-'):
782 if r.startswith(b'exp-compression-'):
783 options[b'compengine'] = r[len(b'exp-compression-'):]
783 options[b'compengine'] = r[len(b'exp-compression-'):]
784
784
785 if repository.NARROW_REQUIREMENT in requirements:
785 if repository.NARROW_REQUIREMENT in requirements:
786 options[b'enableellipsis'] = True
786 options[b'enableellipsis'] = True
787
787
788 return options
788 return options
789
789
790 def makemain(**kwargs):
790 def makemain(**kwargs):
791 """Produce a type conforming to ``ilocalrepositorymain``."""
791 """Produce a type conforming to ``ilocalrepositorymain``."""
792 return localrepository
792 return localrepository
793
793
794 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
794 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
795 class revlogfilestorage(object):
795 class revlogfilestorage(object):
796 """File storage when using revlogs."""
796 """File storage when using revlogs."""
797
797
798 def file(self, path):
798 def file(self, path):
799 if path[0] == b'/':
799 if path[0] == b'/':
800 path = path[1:]
800 path = path[1:]
801
801
802 return filelog.filelog(self.svfs, path)
802 return filelog.filelog(self.svfs, path)
803
803
804 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
804 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
805 class revlognarrowfilestorage(object):
805 class revlognarrowfilestorage(object):
806 """File storage when using revlogs and narrow files."""
806 """File storage when using revlogs and narrow files."""
807
807
808 def file(self, path):
808 def file(self, path):
809 if path[0] == b'/':
809 if path[0] == b'/':
810 path = path[1:]
810 path = path[1:]
811
811
812 return filelog.narrowfilelog(self.svfs, path, self.narrowmatch())
812 return filelog.narrowfilelog(self.svfs, path, self.narrowmatch())
813
813
814 def makefilestorage(requirements, features, **kwargs):
814 def makefilestorage(requirements, features, **kwargs):
815 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
815 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
816 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
816 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
817 features.add(repository.REPO_FEATURE_STREAM_CLONE)
817 features.add(repository.REPO_FEATURE_STREAM_CLONE)
818
818
819 if repository.NARROW_REQUIREMENT in requirements:
819 if repository.NARROW_REQUIREMENT in requirements:
820 return revlognarrowfilestorage
820 return revlognarrowfilestorage
821 else:
821 else:
822 return revlogfilestorage
822 return revlogfilestorage
823
823
824 # List of repository interfaces and factory functions for them. Each
824 # List of repository interfaces and factory functions for them. Each
825 # will be called in order during ``makelocalrepository()`` to iteratively
825 # will be called in order during ``makelocalrepository()`` to iteratively
826 # derive the final type for a local repository instance. We capture the
826 # derive the final type for a local repository instance. We capture the
827 # function as a lambda so we don't hold a reference and the module-level
827 # function as a lambda so we don't hold a reference and the module-level
828 # functions can be wrapped.
828 # functions can be wrapped.
829 REPO_INTERFACES = [
829 REPO_INTERFACES = [
830 (repository.ilocalrepositorymain, lambda: makemain),
830 (repository.ilocalrepositorymain, lambda: makemain),
831 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
831 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
832 ]
832 ]
833
833
834 @interfaceutil.implementer(repository.ilocalrepositorymain)
834 @interfaceutil.implementer(repository.ilocalrepositorymain)
835 class localrepository(object):
835 class localrepository(object):
836 """Main class for representing local repositories.
836 """Main class for representing local repositories.
837
837
838 All local repositories are instances of this class.
838 All local repositories are instances of this class.
839
839
840 Constructed on its own, instances of this class are not usable as
840 Constructed on its own, instances of this class are not usable as
841 repository objects. To obtain a usable repository object, call
841 repository objects. To obtain a usable repository object, call
842 ``hg.repository()``, ``localrepo.instance()``, or
842 ``hg.repository()``, ``localrepo.instance()``, or
843 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
843 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
844 ``instance()`` adds support for creating new repositories.
844 ``instance()`` adds support for creating new repositories.
845 ``hg.repository()`` adds more extension integration, including calling
845 ``hg.repository()`` adds more extension integration, including calling
846 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
846 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
847 used.
847 used.
848 """
848 """
849
849
850 # obsolete experimental requirements:
850 # obsolete experimental requirements:
851 # - manifestv2: An experimental new manifest format that allowed
851 # - manifestv2: An experimental new manifest format that allowed
852 # for stem compression of long paths. Experiment ended up not
852 # for stem compression of long paths. Experiment ended up not
853 # being successful (repository sizes went up due to worse delta
853 # being successful (repository sizes went up due to worse delta
854 # chains), and the code was deleted in 4.6.
854 # chains), and the code was deleted in 4.6.
855 supportedformats = {
855 supportedformats = {
856 'revlogv1',
856 'revlogv1',
857 'generaldelta',
857 'generaldelta',
858 'treemanifest',
858 'treemanifest',
859 REVLOGV2_REQUIREMENT,
859 REVLOGV2_REQUIREMENT,
860 SPARSEREVLOG_REQUIREMENT,
860 SPARSEREVLOG_REQUIREMENT,
861 }
861 }
862 _basesupported = supportedformats | {
862 _basesupported = supportedformats | {
863 'store',
863 'store',
864 'fncache',
864 'fncache',
865 'shared',
865 'shared',
866 'relshared',
866 'relshared',
867 'dotencode',
867 'dotencode',
868 'exp-sparse',
868 'exp-sparse',
869 'internal-phase'
869 'internal-phase'
870 }
870 }
871
871
872 # list of prefix for file which can be written without 'wlock'
872 # list of prefix for file which can be written without 'wlock'
873 # Extensions should extend this list when needed
873 # Extensions should extend this list when needed
874 _wlockfreeprefix = {
874 _wlockfreeprefix = {
875 # We migh consider requiring 'wlock' for the next
875 # We migh consider requiring 'wlock' for the next
876 # two, but pretty much all the existing code assume
876 # two, but pretty much all the existing code assume
877 # wlock is not needed so we keep them excluded for
877 # wlock is not needed so we keep them excluded for
878 # now.
878 # now.
879 'hgrc',
879 'hgrc',
880 'requires',
880 'requires',
881 # XXX cache is a complicatged business someone
881 # XXX cache is a complicatged business someone
882 # should investigate this in depth at some point
882 # should investigate this in depth at some point
883 'cache/',
883 'cache/',
884 # XXX shouldn't be dirstate covered by the wlock?
884 # XXX shouldn't be dirstate covered by the wlock?
885 'dirstate',
885 'dirstate',
886 # XXX bisect was still a bit too messy at the time
886 # XXX bisect was still a bit too messy at the time
887 # this changeset was introduced. Someone should fix
887 # this changeset was introduced. Someone should fix
888 # the remainig bit and drop this line
888 # the remainig bit and drop this line
889 'bisect.state',
889 'bisect.state',
890 }
890 }
891
891
892 def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements,
892 def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements,
893 supportedrequirements, sharedpath, store, cachevfs,
893 supportedrequirements, sharedpath, store, cachevfs,
894 features, intents=None):
894 features, intents=None):
895 """Create a new local repository instance.
895 """Create a new local repository instance.
896
896
897 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
897 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
898 or ``localrepo.makelocalrepository()`` for obtaining a new repository
898 or ``localrepo.makelocalrepository()`` for obtaining a new repository
899 object.
899 object.
900
900
901 Arguments:
901 Arguments:
902
902
903 baseui
903 baseui
904 ``ui.ui`` instance that ``ui`` argument was based off of.
904 ``ui.ui`` instance that ``ui`` argument was based off of.
905
905
906 ui
906 ui
907 ``ui.ui`` instance for use by the repository.
907 ``ui.ui`` instance for use by the repository.
908
908
909 origroot
909 origroot
910 ``bytes`` path to working directory root of this repository.
910 ``bytes`` path to working directory root of this repository.
911
911
912 wdirvfs
912 wdirvfs
913 ``vfs.vfs`` rooted at the working directory.
913 ``vfs.vfs`` rooted at the working directory.
914
914
915 hgvfs
915 hgvfs
916 ``vfs.vfs`` rooted at .hg/
916 ``vfs.vfs`` rooted at .hg/
917
917
918 requirements
918 requirements
919 ``set`` of bytestrings representing repository opening requirements.
919 ``set`` of bytestrings representing repository opening requirements.
920
920
921 supportedrequirements
921 supportedrequirements
922 ``set`` of bytestrings representing repository requirements that we
922 ``set`` of bytestrings representing repository requirements that we
923 know how to open. May be a supetset of ``requirements``.
923 know how to open. May be a supetset of ``requirements``.
924
924
925 sharedpath
925 sharedpath
926 ``bytes`` Defining path to storage base directory. Points to a
926 ``bytes`` Defining path to storage base directory. Points to a
927 ``.hg/`` directory somewhere.
927 ``.hg/`` directory somewhere.
928
928
929 store
929 store
930 ``store.basicstore`` (or derived) instance providing access to
930 ``store.basicstore`` (or derived) instance providing access to
931 versioned storage.
931 versioned storage.
932
932
933 cachevfs
933 cachevfs
934 ``vfs.vfs`` used for cache files.
934 ``vfs.vfs`` used for cache files.
935
935
936 features
936 features
937 ``set`` of bytestrings defining features/capabilities of this
937 ``set`` of bytestrings defining features/capabilities of this
938 instance.
938 instance.
939
939
940 intents
940 intents
941 ``set`` of system strings indicating what this repo will be used
941 ``set`` of system strings indicating what this repo will be used
942 for.
942 for.
943 """
943 """
944 self.baseui = baseui
944 self.baseui = baseui
945 self.ui = ui
945 self.ui = ui
946 self.origroot = origroot
946 self.origroot = origroot
947 # vfs rooted at working directory.
947 # vfs rooted at working directory.
948 self.wvfs = wdirvfs
948 self.wvfs = wdirvfs
949 self.root = wdirvfs.base
949 self.root = wdirvfs.base
950 # vfs rooted at .hg/. Used to access most non-store paths.
950 # vfs rooted at .hg/. Used to access most non-store paths.
951 self.vfs = hgvfs
951 self.vfs = hgvfs
952 self.path = hgvfs.base
952 self.path = hgvfs.base
953 self.requirements = requirements
953 self.requirements = requirements
954 self.supported = supportedrequirements
954 self.supported = supportedrequirements
955 self.sharedpath = sharedpath
955 self.sharedpath = sharedpath
956 self.store = store
956 self.store = store
957 self.cachevfs = cachevfs
957 self.cachevfs = cachevfs
958 self.features = features
958 self.features = features
959
959
960 self.filtername = None
960 self.filtername = None
961
961
962 if (self.ui.configbool('devel', 'all-warnings') or
962 if (self.ui.configbool('devel', 'all-warnings') or
963 self.ui.configbool('devel', 'check-locks')):
963 self.ui.configbool('devel', 'check-locks')):
964 self.vfs.audit = self._getvfsward(self.vfs.audit)
964 self.vfs.audit = self._getvfsward(self.vfs.audit)
965 # A list of callback to shape the phase if no data were found.
965 # A list of callback to shape the phase if no data were found.
966 # Callback are in the form: func(repo, roots) --> processed root.
966 # Callback are in the form: func(repo, roots) --> processed root.
967 # This list it to be filled by extension during repo setup
967 # This list it to be filled by extension during repo setup
968 self._phasedefaults = []
968 self._phasedefaults = []
969
969
970 color.setup(self.ui)
970 color.setup(self.ui)
971
971
972 self.spath = self.store.path
972 self.spath = self.store.path
973 self.svfs = self.store.vfs
973 self.svfs = self.store.vfs
974 self.sjoin = self.store.join
974 self.sjoin = self.store.join
975 if (self.ui.configbool('devel', 'all-warnings') or
975 if (self.ui.configbool('devel', 'all-warnings') or
976 self.ui.configbool('devel', 'check-locks')):
976 self.ui.configbool('devel', 'check-locks')):
977 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
977 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
978 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
978 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
979 else: # standard vfs
979 else: # standard vfs
980 self.svfs.audit = self._getsvfsward(self.svfs.audit)
980 self.svfs.audit = self._getsvfsward(self.svfs.audit)
981
981
982 self._dirstatevalidatewarned = False
982 self._dirstatevalidatewarned = False
983
983
984 self._branchcaches = {}
984 self._branchcaches = {}
985 self._revbranchcache = None
985 self._revbranchcache = None
986 self._filterpats = {}
986 self._filterpats = {}
987 self._datafilters = {}
987 self._datafilters = {}
988 self._transref = self._lockref = self._wlockref = None
988 self._transref = self._lockref = self._wlockref = None
989
989
990 # A cache for various files under .hg/ that tracks file changes,
990 # A cache for various files under .hg/ that tracks file changes,
991 # (used by the filecache decorator)
991 # (used by the filecache decorator)
992 #
992 #
993 # Maps a property name to its util.filecacheentry
993 # Maps a property name to its util.filecacheentry
994 self._filecache = {}
994 self._filecache = {}
995
995
996 # hold sets of revision to be filtered
996 # hold sets of revision to be filtered
997 # should be cleared when something might have changed the filter value:
997 # should be cleared when something might have changed the filter value:
998 # - new changesets,
998 # - new changesets,
999 # - phase change,
999 # - phase change,
1000 # - new obsolescence marker,
1000 # - new obsolescence marker,
1001 # - working directory parent change,
1001 # - working directory parent change,
1002 # - bookmark changes
1002 # - bookmark changes
1003 self.filteredrevcache = {}
1003 self.filteredrevcache = {}
1004
1004
1005 # post-dirstate-status hooks
1005 # post-dirstate-status hooks
1006 self._postdsstatus = []
1006 self._postdsstatus = []
1007
1007
1008 # generic mapping between names and nodes
1008 # generic mapping between names and nodes
1009 self.names = namespaces.namespaces()
1009 self.names = namespaces.namespaces()
1010
1010
1011 # Key to signature value.
1011 # Key to signature value.
1012 self._sparsesignaturecache = {}
1012 self._sparsesignaturecache = {}
1013 # Signature to cached matcher instance.
1013 # Signature to cached matcher instance.
1014 self._sparsematchercache = {}
1014 self._sparsematchercache = {}
1015
1015
1016 def _getvfsward(self, origfunc):
1016 def _getvfsward(self, origfunc):
1017 """build a ward for self.vfs"""
1017 """build a ward for self.vfs"""
1018 rref = weakref.ref(self)
1018 rref = weakref.ref(self)
1019 def checkvfs(path, mode=None):
1019 def checkvfs(path, mode=None):
1020 ret = origfunc(path, mode=mode)
1020 ret = origfunc(path, mode=mode)
1021 repo = rref()
1021 repo = rref()
1022 if (repo is None
1022 if (repo is None
1023 or not util.safehasattr(repo, '_wlockref')
1023 or not util.safehasattr(repo, '_wlockref')
1024 or not util.safehasattr(repo, '_lockref')):
1024 or not util.safehasattr(repo, '_lockref')):
1025 return
1025 return
1026 if mode in (None, 'r', 'rb'):
1026 if mode in (None, 'r', 'rb'):
1027 return
1027 return
1028 if path.startswith(repo.path):
1028 if path.startswith(repo.path):
1029 # truncate name relative to the repository (.hg)
1029 # truncate name relative to the repository (.hg)
1030 path = path[len(repo.path) + 1:]
1030 path = path[len(repo.path) + 1:]
1031 if path.startswith('cache/'):
1031 if path.startswith('cache/'):
1032 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
1032 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
1033 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
1033 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
1034 if path.startswith('journal.'):
1034 if path.startswith('journal.'):
1035 # journal is covered by 'lock'
1035 # journal is covered by 'lock'
1036 if repo._currentlock(repo._lockref) is None:
1036 if repo._currentlock(repo._lockref) is None:
1037 repo.ui.develwarn('write with no lock: "%s"' % path,
1037 repo.ui.develwarn('write with no lock: "%s"' % path,
1038 stacklevel=2, config='check-locks')
1038 stacklevel=2, config='check-locks')
1039 elif repo._currentlock(repo._wlockref) is None:
1039 elif repo._currentlock(repo._wlockref) is None:
1040 # rest of vfs files are covered by 'wlock'
1040 # rest of vfs files are covered by 'wlock'
1041 #
1041 #
1042 # exclude special files
1042 # exclude special files
1043 for prefix in self._wlockfreeprefix:
1043 for prefix in self._wlockfreeprefix:
1044 if path.startswith(prefix):
1044 if path.startswith(prefix):
1045 return
1045 return
1046 repo.ui.develwarn('write with no wlock: "%s"' % path,
1046 repo.ui.develwarn('write with no wlock: "%s"' % path,
1047 stacklevel=2, config='check-locks')
1047 stacklevel=2, config='check-locks')
1048 return ret
1048 return ret
1049 return checkvfs
1049 return checkvfs
1050
1050
1051 def _getsvfsward(self, origfunc):
1051 def _getsvfsward(self, origfunc):
1052 """build a ward for self.svfs"""
1052 """build a ward for self.svfs"""
1053 rref = weakref.ref(self)
1053 rref = weakref.ref(self)
1054 def checksvfs(path, mode=None):
1054 def checksvfs(path, mode=None):
1055 ret = origfunc(path, mode=mode)
1055 ret = origfunc(path, mode=mode)
1056 repo = rref()
1056 repo = rref()
1057 if repo is None or not util.safehasattr(repo, '_lockref'):
1057 if repo is None or not util.safehasattr(repo, '_lockref'):
1058 return
1058 return
1059 if mode in (None, 'r', 'rb'):
1059 if mode in (None, 'r', 'rb'):
1060 return
1060 return
1061 if path.startswith(repo.sharedpath):
1061 if path.startswith(repo.sharedpath):
1062 # truncate name relative to the repository (.hg)
1062 # truncate name relative to the repository (.hg)
1063 path = path[len(repo.sharedpath) + 1:]
1063 path = path[len(repo.sharedpath) + 1:]
1064 if repo._currentlock(repo._lockref) is None:
1064 if repo._currentlock(repo._lockref) is None:
1065 repo.ui.develwarn('write with no lock: "%s"' % path,
1065 repo.ui.develwarn('write with no lock: "%s"' % path,
1066 stacklevel=3)
1066 stacklevel=3)
1067 return ret
1067 return ret
1068 return checksvfs
1068 return checksvfs
1069
1069
1070 def close(self):
1070 def close(self):
1071 self._writecaches()
1071 self._writecaches()
1072
1072
1073 def _writecaches(self):
1073 def _writecaches(self):
1074 if self._revbranchcache:
1074 if self._revbranchcache:
1075 self._revbranchcache.write()
1075 self._revbranchcache.write()
1076
1076
1077 def _restrictcapabilities(self, caps):
1077 def _restrictcapabilities(self, caps):
1078 if self.ui.configbool('experimental', 'bundle2-advertise'):
1078 if self.ui.configbool('experimental', 'bundle2-advertise'):
1079 caps = set(caps)
1079 caps = set(caps)
1080 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
1080 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
1081 role='client'))
1081 role='client'))
1082 caps.add('bundle2=' + urlreq.quote(capsblob))
1082 caps.add('bundle2=' + urlreq.quote(capsblob))
1083 return caps
1083 return caps
1084
1084
1085 def _writerequirements(self):
1085 def _writerequirements(self):
1086 scmutil.writerequires(self.vfs, self.requirements)
1086 scmutil.writerequires(self.vfs, self.requirements)
1087
1087
1088 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1088 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1089 # self -> auditor -> self._checknested -> self
1089 # self -> auditor -> self._checknested -> self
1090
1090
1091 @property
1091 @property
1092 def auditor(self):
1092 def auditor(self):
1093 # This is only used by context.workingctx.match in order to
1093 # This is only used by context.workingctx.match in order to
1094 # detect files in subrepos.
1094 # detect files in subrepos.
1095 return pathutil.pathauditor(self.root, callback=self._checknested)
1095 return pathutil.pathauditor(self.root, callback=self._checknested)
1096
1096
1097 @property
1097 @property
1098 def nofsauditor(self):
1098 def nofsauditor(self):
1099 # This is only used by context.basectx.match in order to detect
1099 # This is only used by context.basectx.match in order to detect
1100 # files in subrepos.
1100 # files in subrepos.
1101 return pathutil.pathauditor(self.root, callback=self._checknested,
1101 return pathutil.pathauditor(self.root, callback=self._checknested,
1102 realfs=False, cached=True)
1102 realfs=False, cached=True)
1103
1103
1104 def _checknested(self, path):
1104 def _checknested(self, path):
1105 """Determine if path is a legal nested repository."""
1105 """Determine if path is a legal nested repository."""
1106 if not path.startswith(self.root):
1106 if not path.startswith(self.root):
1107 return False
1107 return False
1108 subpath = path[len(self.root) + 1:]
1108 subpath = path[len(self.root) + 1:]
1109 normsubpath = util.pconvert(subpath)
1109 normsubpath = util.pconvert(subpath)
1110
1110
1111 # XXX: Checking against the current working copy is wrong in
1111 # XXX: Checking against the current working copy is wrong in
1112 # the sense that it can reject things like
1112 # the sense that it can reject things like
1113 #
1113 #
1114 # $ hg cat -r 10 sub/x.txt
1114 # $ hg cat -r 10 sub/x.txt
1115 #
1115 #
1116 # if sub/ is no longer a subrepository in the working copy
1116 # if sub/ is no longer a subrepository in the working copy
1117 # parent revision.
1117 # parent revision.
1118 #
1118 #
1119 # However, it can of course also allow things that would have
1119 # However, it can of course also allow things that would have
1120 # been rejected before, such as the above cat command if sub/
1120 # been rejected before, such as the above cat command if sub/
1121 # is a subrepository now, but was a normal directory before.
1121 # is a subrepository now, but was a normal directory before.
1122 # The old path auditor would have rejected by mistake since it
1122 # The old path auditor would have rejected by mistake since it
1123 # panics when it sees sub/.hg/.
1123 # panics when it sees sub/.hg/.
1124 #
1124 #
1125 # All in all, checking against the working copy seems sensible
1125 # All in all, checking against the working copy seems sensible
1126 # since we want to prevent access to nested repositories on
1126 # since we want to prevent access to nested repositories on
1127 # the filesystem *now*.
1127 # the filesystem *now*.
1128 ctx = self[None]
1128 ctx = self[None]
1129 parts = util.splitpath(subpath)
1129 parts = util.splitpath(subpath)
1130 while parts:
1130 while parts:
1131 prefix = '/'.join(parts)
1131 prefix = '/'.join(parts)
1132 if prefix in ctx.substate:
1132 if prefix in ctx.substate:
1133 if prefix == normsubpath:
1133 if prefix == normsubpath:
1134 return True
1134 return True
1135 else:
1135 else:
1136 sub = ctx.sub(prefix)
1136 sub = ctx.sub(prefix)
1137 return sub.checknested(subpath[len(prefix) + 1:])
1137 return sub.checknested(subpath[len(prefix) + 1:])
1138 else:
1138 else:
1139 parts.pop()
1139 parts.pop()
1140 return False
1140 return False
1141
1141
1142 def peer(self):
1142 def peer(self):
1143 return localpeer(self) # not cached to avoid reference cycle
1143 return localpeer(self) # not cached to avoid reference cycle
1144
1144
1145 def unfiltered(self):
1145 def unfiltered(self):
1146 """Return unfiltered version of the repository
1146 """Return unfiltered version of the repository
1147
1147
1148 Intended to be overwritten by filtered repo."""
1148 Intended to be overwritten by filtered repo."""
1149 return self
1149 return self
1150
1150
1151 def filtered(self, name, visibilityexceptions=None):
1151 def filtered(self, name, visibilityexceptions=None):
1152 """Return a filtered version of a repository"""
1152 """Return a filtered version of a repository"""
1153 cls = repoview.newtype(self.unfiltered().__class__)
1153 cls = repoview.newtype(self.unfiltered().__class__)
1154 return cls(self, name, visibilityexceptions)
1154 return cls(self, name, visibilityexceptions)
1155
1155
1156 @repofilecache('bookmarks', 'bookmarks.current')
1156 @repofilecache('bookmarks', 'bookmarks.current')
1157 def _bookmarks(self):
1157 def _bookmarks(self):
1158 return bookmarks.bmstore(self)
1158 return bookmarks.bmstore(self)
1159
1159
1160 @property
1160 @property
1161 def _activebookmark(self):
1161 def _activebookmark(self):
1162 return self._bookmarks.active
1162 return self._bookmarks.active
1163
1163
1164 # _phasesets depend on changelog. what we need is to call
1164 # _phasesets depend on changelog. what we need is to call
1165 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1165 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1166 # can't be easily expressed in filecache mechanism.
1166 # can't be easily expressed in filecache mechanism.
1167 @storecache('phaseroots', '00changelog.i')
1167 @storecache('phaseroots', '00changelog.i')
1168 def _phasecache(self):
1168 def _phasecache(self):
1169 return phases.phasecache(self, self._phasedefaults)
1169 return phases.phasecache(self, self._phasedefaults)
1170
1170
1171 @storecache('obsstore')
1171 @storecache('obsstore')
1172 def obsstore(self):
1172 def obsstore(self):
1173 return obsolete.makestore(self.ui, self)
1173 return obsolete.makestore(self.ui, self)
1174
1174
1175 @storecache('00changelog.i')
1175 @storecache('00changelog.i')
1176 def changelog(self):
1176 def changelog(self):
1177 return changelog.changelog(self.svfs,
1177 return changelog.changelog(self.svfs,
1178 trypending=txnutil.mayhavepending(self.root))
1178 trypending=txnutil.mayhavepending(self.root))
1179
1179
1180 @storecache('00manifest.i')
1180 @storecache('00manifest.i')
1181 def manifestlog(self):
1181 def manifestlog(self):
1182 rootstore = manifest.manifestrevlog(self.svfs)
1182 rootstore = manifest.manifestrevlog(self.svfs)
1183 return manifest.manifestlog(self.svfs, self, rootstore)
1183 return manifest.manifestlog(self.svfs, self, rootstore)
1184
1184
1185 @repofilecache('dirstate')
1185 @repofilecache('dirstate')
1186 def dirstate(self):
1186 def dirstate(self):
1187 return self._makedirstate()
1187 return self._makedirstate()
1188
1188
1189 def _makedirstate(self):
1189 def _makedirstate(self):
1190 """Extension point for wrapping the dirstate per-repo."""
1190 """Extension point for wrapping the dirstate per-repo."""
1191 sparsematchfn = lambda: sparse.matcher(self)
1191 sparsematchfn = lambda: sparse.matcher(self)
1192
1192
1193 return dirstate.dirstate(self.vfs, self.ui, self.root,
1193 return dirstate.dirstate(self.vfs, self.ui, self.root,
1194 self._dirstatevalidate, sparsematchfn)
1194 self._dirstatevalidate, sparsematchfn)
1195
1195
1196 def _dirstatevalidate(self, node):
1196 def _dirstatevalidate(self, node):
1197 try:
1197 try:
1198 self.changelog.rev(node)
1198 self.changelog.rev(node)
1199 return node
1199 return node
1200 except error.LookupError:
1200 except error.LookupError:
1201 if not self._dirstatevalidatewarned:
1201 if not self._dirstatevalidatewarned:
1202 self._dirstatevalidatewarned = True
1202 self._dirstatevalidatewarned = True
1203 self.ui.warn(_("warning: ignoring unknown"
1203 self.ui.warn(_("warning: ignoring unknown"
1204 " working parent %s!\n") % short(node))
1204 " working parent %s!\n") % short(node))
1205 return nullid
1205 return nullid
1206
1206
1207 @storecache(narrowspec.FILENAME)
1207 @storecache(narrowspec.FILENAME)
1208 def narrowpats(self):
1208 def narrowpats(self):
1209 """matcher patterns for this repository's narrowspec
1209 """matcher patterns for this repository's narrowspec
1210
1210
1211 A tuple of (includes, excludes).
1211 A tuple of (includes, excludes).
1212 """
1212 """
1213 return narrowspec.load(self)
1213 return narrowspec.load(self)
1214
1214
1215 @storecache(narrowspec.FILENAME)
1215 @storecache(narrowspec.FILENAME)
1216 def _narrowmatch(self):
1216 def _narrowmatch(self):
1217 if repository.NARROW_REQUIREMENT not in self.requirements:
1217 if repository.NARROW_REQUIREMENT not in self.requirements:
1218 return matchmod.always(self.root, '')
1218 return matchmod.always(self.root, '')
1219 include, exclude = self.narrowpats
1219 include, exclude = self.narrowpats
1220 return narrowspec.match(self.root, include=include, exclude=exclude)
1220 return narrowspec.match(self.root, include=include, exclude=exclude)
1221
1221
1222 def narrowmatch(self, match=None, includeexact=False):
1222 def narrowmatch(self, match=None, includeexact=False):
1223 """matcher corresponding the the repo's narrowspec
1223 """matcher corresponding the the repo's narrowspec
1224
1224
1225 If `match` is given, then that will be intersected with the narrow
1225 If `match` is given, then that will be intersected with the narrow
1226 matcher.
1226 matcher.
1227
1227
1228 If `includeexact` is True, then any exact matches from `match` will
1228 If `includeexact` is True, then any exact matches from `match` will
1229 be included even if they're outside the narrowspec.
1229 be included even if they're outside the narrowspec.
1230 """
1230 """
1231 if match:
1231 if match:
1232 if includeexact and not self._narrowmatch.always():
1232 if includeexact and not self._narrowmatch.always():
1233 # do not exclude explicitly-specified paths so that they can
1233 # do not exclude explicitly-specified paths so that they can
1234 # be warned later on
1234 # be warned later on
1235 em = matchmod.exact(match._root, match._cwd, match.files())
1235 em = matchmod.exact(match._root, match._cwd, match.files())
1236 nm = matchmod.unionmatcher([self._narrowmatch, em])
1236 nm = matchmod.unionmatcher([self._narrowmatch, em])
1237 return matchmod.intersectmatchers(match, nm)
1237 return matchmod.intersectmatchers(match, nm)
1238 return matchmod.intersectmatchers(match, self._narrowmatch)
1238 return matchmod.intersectmatchers(match, self._narrowmatch)
1239 return self._narrowmatch
1239 return self._narrowmatch
1240
1240
1241 def setnarrowpats(self, newincludes, newexcludes):
1241 def setnarrowpats(self, newincludes, newexcludes):
1242 narrowspec.save(self, newincludes, newexcludes)
1242 narrowspec.save(self, newincludes, newexcludes)
1243 self.invalidate(clearfilecache=True)
1243 self.invalidate(clearfilecache=True)
1244
1244
1245 def __getitem__(self, changeid):
1245 def __getitem__(self, changeid):
1246 if changeid is None:
1246 if changeid is None:
1247 return context.workingctx(self)
1247 return context.workingctx(self)
1248 if isinstance(changeid, context.basectx):
1248 if isinstance(changeid, context.basectx):
1249 return changeid
1249 return changeid
1250 if isinstance(changeid, slice):
1250 if isinstance(changeid, slice):
1251 # wdirrev isn't contiguous so the slice shouldn't include it
1251 # wdirrev isn't contiguous so the slice shouldn't include it
1252 return [self[i]
1252 return [self[i]
1253 for i in pycompat.xrange(*changeid.indices(len(self)))
1253 for i in pycompat.xrange(*changeid.indices(len(self)))
1254 if i not in self.changelog.filteredrevs]
1254 if i not in self.changelog.filteredrevs]
1255 try:
1255 try:
1256 if isinstance(changeid, int):
1256 if isinstance(changeid, int):
1257 node = self.changelog.node(changeid)
1257 node = self.changelog.node(changeid)
1258 rev = changeid
1258 rev = changeid
1259 elif changeid == 'null':
1259 elif changeid == 'null':
1260 node = nullid
1260 node = nullid
1261 rev = nullrev
1261 rev = nullrev
1262 elif changeid == 'tip':
1262 elif changeid == 'tip':
1263 node = self.changelog.tip()
1263 node = self.changelog.tip()
1264 rev = self.changelog.rev(node)
1264 rev = self.changelog.rev(node)
1265 elif changeid == '.':
1265 elif changeid == '.':
1266 # this is a hack to delay/avoid loading obsmarkers
1266 # this is a hack to delay/avoid loading obsmarkers
1267 # when we know that '.' won't be hidden
1267 # when we know that '.' won't be hidden
1268 node = self.dirstate.p1()
1268 node = self.dirstate.p1()
1269 rev = self.unfiltered().changelog.rev(node)
1269 rev = self.unfiltered().changelog.rev(node)
1270 elif len(changeid) == 20:
1270 elif len(changeid) == 20:
1271 try:
1271 try:
1272 node = changeid
1272 node = changeid
1273 rev = self.changelog.rev(changeid)
1273 rev = self.changelog.rev(changeid)
1274 except error.FilteredLookupError:
1274 except error.FilteredLookupError:
1275 changeid = hex(changeid) # for the error message
1275 changeid = hex(changeid) # for the error message
1276 raise
1276 raise
1277 except LookupError:
1277 except LookupError:
1278 # check if it might have come from damaged dirstate
1278 # check if it might have come from damaged dirstate
1279 #
1279 #
1280 # XXX we could avoid the unfiltered if we had a recognizable
1280 # XXX we could avoid the unfiltered if we had a recognizable
1281 # exception for filtered changeset access
1281 # exception for filtered changeset access
1282 if (self.local()
1282 if (self.local()
1283 and changeid in self.unfiltered().dirstate.parents()):
1283 and changeid in self.unfiltered().dirstate.parents()):
1284 msg = _("working directory has unknown parent '%s'!")
1284 msg = _("working directory has unknown parent '%s'!")
1285 raise error.Abort(msg % short(changeid))
1285 raise error.Abort(msg % short(changeid))
1286 changeid = hex(changeid) # for the error message
1286 changeid = hex(changeid) # for the error message
1287 raise
1287 raise
1288
1288
1289 elif len(changeid) == 40:
1289 elif len(changeid) == 40:
1290 node = bin(changeid)
1290 node = bin(changeid)
1291 rev = self.changelog.rev(node)
1291 rev = self.changelog.rev(node)
1292 else:
1292 else:
1293 raise error.ProgrammingError(
1293 raise error.ProgrammingError(
1294 "unsupported changeid '%s' of type %s" %
1294 "unsupported changeid '%s' of type %s" %
1295 (changeid, type(changeid)))
1295 (changeid, type(changeid)))
1296
1296
1297 return context.changectx(self, rev, node)
1297 return context.changectx(self, rev, node)
1298
1298
1299 except (error.FilteredIndexError, error.FilteredLookupError):
1299 except (error.FilteredIndexError, error.FilteredLookupError):
1300 raise error.FilteredRepoLookupError(_("filtered revision '%s'")
1300 raise error.FilteredRepoLookupError(_("filtered revision '%s'")
1301 % pycompat.bytestr(changeid))
1301 % pycompat.bytestr(changeid))
1302 except (IndexError, LookupError):
1302 except (IndexError, LookupError):
1303 raise error.RepoLookupError(
1303 raise error.RepoLookupError(
1304 _("unknown revision '%s'") % pycompat.bytestr(changeid))
1304 _("unknown revision '%s'") % pycompat.bytestr(changeid))
1305 except error.WdirUnsupported:
1305 except error.WdirUnsupported:
1306 return context.workingctx(self)
1306 return context.workingctx(self)
1307
1307
1308 def __contains__(self, changeid):
1308 def __contains__(self, changeid):
1309 """True if the given changeid exists
1309 """True if the given changeid exists
1310
1310
1311 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1311 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1312 specified.
1312 specified.
1313 """
1313 """
1314 try:
1314 try:
1315 self[changeid]
1315 self[changeid]
1316 return True
1316 return True
1317 except error.RepoLookupError:
1317 except error.RepoLookupError:
1318 return False
1318 return False
1319
1319
1320 def __nonzero__(self):
1320 def __nonzero__(self):
1321 return True
1321 return True
1322
1322
1323 __bool__ = __nonzero__
1323 __bool__ = __nonzero__
1324
1324
1325 def __len__(self):
1325 def __len__(self):
1326 # no need to pay the cost of repoview.changelog
1326 # no need to pay the cost of repoview.changelog
1327 unfi = self.unfiltered()
1327 unfi = self.unfiltered()
1328 return len(unfi.changelog)
1328 return len(unfi.changelog)
1329
1329
1330 def __iter__(self):
1330 def __iter__(self):
1331 return iter(self.changelog)
1331 return iter(self.changelog)
1332
1332
1333 def revs(self, expr, *args):
1333 def revs(self, expr, *args):
1334 '''Find revisions matching a revset.
1334 '''Find revisions matching a revset.
1335
1335
1336 The revset is specified as a string ``expr`` that may contain
1336 The revset is specified as a string ``expr`` that may contain
1337 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1337 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1338
1338
1339 Revset aliases from the configuration are not expanded. To expand
1339 Revset aliases from the configuration are not expanded. To expand
1340 user aliases, consider calling ``scmutil.revrange()`` or
1340 user aliases, consider calling ``scmutil.revrange()`` or
1341 ``repo.anyrevs([expr], user=True)``.
1341 ``repo.anyrevs([expr], user=True)``.
1342
1342
1343 Returns a revset.abstractsmartset, which is a list-like interface
1343 Returns a revset.abstractsmartset, which is a list-like interface
1344 that contains integer revisions.
1344 that contains integer revisions.
1345 '''
1345 '''
1346 expr = revsetlang.formatspec(expr, *args)
1346 expr = revsetlang.formatspec(expr, *args)
1347 m = revset.match(None, expr)
1347 m = revset.match(None, expr)
1348 return m(self)
1348 return m(self)
1349
1349
1350 def set(self, expr, *args):
1350 def set(self, expr, *args):
1351 '''Find revisions matching a revset and emit changectx instances.
1351 '''Find revisions matching a revset and emit changectx instances.
1352
1352
1353 This is a convenience wrapper around ``revs()`` that iterates the
1353 This is a convenience wrapper around ``revs()`` that iterates the
1354 result and is a generator of changectx instances.
1354 result and is a generator of changectx instances.
1355
1355
1356 Revset aliases from the configuration are not expanded. To expand
1356 Revset aliases from the configuration are not expanded. To expand
1357 user aliases, consider calling ``scmutil.revrange()``.
1357 user aliases, consider calling ``scmutil.revrange()``.
1358 '''
1358 '''
1359 for r in self.revs(expr, *args):
1359 for r in self.revs(expr, *args):
1360 yield self[r]
1360 yield self[r]
1361
1361
1362 def anyrevs(self, specs, user=False, localalias=None):
1362 def anyrevs(self, specs, user=False, localalias=None):
1363 '''Find revisions matching one of the given revsets.
1363 '''Find revisions matching one of the given revsets.
1364
1364
1365 Revset aliases from the configuration are not expanded by default. To
1365 Revset aliases from the configuration are not expanded by default. To
1366 expand user aliases, specify ``user=True``. To provide some local
1366 expand user aliases, specify ``user=True``. To provide some local
1367 definitions overriding user aliases, set ``localalias`` to
1367 definitions overriding user aliases, set ``localalias`` to
1368 ``{name: definitionstring}``.
1368 ``{name: definitionstring}``.
1369 '''
1369 '''
1370 if user:
1370 if user:
1371 m = revset.matchany(self.ui, specs,
1371 m = revset.matchany(self.ui, specs,
1372 lookup=revset.lookupfn(self),
1372 lookup=revset.lookupfn(self),
1373 localalias=localalias)
1373 localalias=localalias)
1374 else:
1374 else:
1375 m = revset.matchany(None, specs, localalias=localalias)
1375 m = revset.matchany(None, specs, localalias=localalias)
1376 return m(self)
1376 return m(self)
1377
1377
1378 def url(self):
1378 def url(self):
1379 return 'file:' + self.root
1379 return 'file:' + self.root
1380
1380
1381 def hook(self, name, throw=False, **args):
1381 def hook(self, name, throw=False, **args):
1382 """Call a hook, passing this repo instance.
1382 """Call a hook, passing this repo instance.
1383
1383
1384 This a convenience method to aid invoking hooks. Extensions likely
1384 This a convenience method to aid invoking hooks. Extensions likely
1385 won't call this unless they have registered a custom hook or are
1385 won't call this unless they have registered a custom hook or are
1386 replacing code that is expected to call a hook.
1386 replacing code that is expected to call a hook.
1387 """
1387 """
1388 return hook.hook(self.ui, self, name, throw, **args)
1388 return hook.hook(self.ui, self, name, throw, **args)
1389
1389
1390 @filteredpropertycache
1390 @filteredpropertycache
1391 def _tagscache(self):
1391 def _tagscache(self):
1392 '''Returns a tagscache object that contains various tags related
1392 '''Returns a tagscache object that contains various tags related
1393 caches.'''
1393 caches.'''
1394
1394
1395 # This simplifies its cache management by having one decorated
1395 # This simplifies its cache management by having one decorated
1396 # function (this one) and the rest simply fetch things from it.
1396 # function (this one) and the rest simply fetch things from it.
1397 class tagscache(object):
1397 class tagscache(object):
1398 def __init__(self):
1398 def __init__(self):
1399 # These two define the set of tags for this repository. tags
1399 # These two define the set of tags for this repository. tags
1400 # maps tag name to node; tagtypes maps tag name to 'global' or
1400 # maps tag name to node; tagtypes maps tag name to 'global' or
1401 # 'local'. (Global tags are defined by .hgtags across all
1401 # 'local'. (Global tags are defined by .hgtags across all
1402 # heads, and local tags are defined in .hg/localtags.)
1402 # heads, and local tags are defined in .hg/localtags.)
1403 # They constitute the in-memory cache of tags.
1403 # They constitute the in-memory cache of tags.
1404 self.tags = self.tagtypes = None
1404 self.tags = self.tagtypes = None
1405
1405
1406 self.nodetagscache = self.tagslist = None
1406 self.nodetagscache = self.tagslist = None
1407
1407
1408 cache = tagscache()
1408 cache = tagscache()
1409 cache.tags, cache.tagtypes = self._findtags()
1409 cache.tags, cache.tagtypes = self._findtags()
1410
1410
1411 return cache
1411 return cache
1412
1412
1413 def tags(self):
1413 def tags(self):
1414 '''return a mapping of tag to node'''
1414 '''return a mapping of tag to node'''
1415 t = {}
1415 t = {}
1416 if self.changelog.filteredrevs:
1416 if self.changelog.filteredrevs:
1417 tags, tt = self._findtags()
1417 tags, tt = self._findtags()
1418 else:
1418 else:
1419 tags = self._tagscache.tags
1419 tags = self._tagscache.tags
1420 rev = self.changelog.rev
1420 for k, v in tags.iteritems():
1421 for k, v in tags.iteritems():
1421 try:
1422 try:
1422 # ignore tags to unknown nodes
1423 # ignore tags to unknown nodes
1423 self.changelog.rev(v)
1424 rev(v)
1424 t[k] = v
1425 t[k] = v
1425 except (error.LookupError, ValueError):
1426 except (error.LookupError, ValueError):
1426 pass
1427 pass
1427 return t
1428 return t
1428
1429
1429 def _findtags(self):
1430 def _findtags(self):
1430 '''Do the hard work of finding tags. Return a pair of dicts
1431 '''Do the hard work of finding tags. Return a pair of dicts
1431 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1432 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1432 maps tag name to a string like \'global\' or \'local\'.
1433 maps tag name to a string like \'global\' or \'local\'.
1433 Subclasses or extensions are free to add their own tags, but
1434 Subclasses or extensions are free to add their own tags, but
1434 should be aware that the returned dicts will be retained for the
1435 should be aware that the returned dicts will be retained for the
1435 duration of the localrepo object.'''
1436 duration of the localrepo object.'''
1436
1437
1437 # XXX what tagtype should subclasses/extensions use? Currently
1438 # XXX what tagtype should subclasses/extensions use? Currently
1438 # mq and bookmarks add tags, but do not set the tagtype at all.
1439 # mq and bookmarks add tags, but do not set the tagtype at all.
1439 # Should each extension invent its own tag type? Should there
1440 # Should each extension invent its own tag type? Should there
1440 # be one tagtype for all such "virtual" tags? Or is the status
1441 # be one tagtype for all such "virtual" tags? Or is the status
1441 # quo fine?
1442 # quo fine?
1442
1443
1443
1444
1444 # map tag name to (node, hist)
1445 # map tag name to (node, hist)
1445 alltags = tagsmod.findglobaltags(self.ui, self)
1446 alltags = tagsmod.findglobaltags(self.ui, self)
1446 # map tag name to tag type
1447 # map tag name to tag type
1447 tagtypes = dict((tag, 'global') for tag in alltags)
1448 tagtypes = dict((tag, 'global') for tag in alltags)
1448
1449
1449 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1450 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1450
1451
1451 # Build the return dicts. Have to re-encode tag names because
1452 # Build the return dicts. Have to re-encode tag names because
1452 # the tags module always uses UTF-8 (in order not to lose info
1453 # the tags module always uses UTF-8 (in order not to lose info
1453 # writing to the cache), but the rest of Mercurial wants them in
1454 # writing to the cache), but the rest of Mercurial wants them in
1454 # local encoding.
1455 # local encoding.
1455 tags = {}
1456 tags = {}
1456 for (name, (node, hist)) in alltags.iteritems():
1457 for (name, (node, hist)) in alltags.iteritems():
1457 if node != nullid:
1458 if node != nullid:
1458 tags[encoding.tolocal(name)] = node
1459 tags[encoding.tolocal(name)] = node
1459 tags['tip'] = self.changelog.tip()
1460 tags['tip'] = self.changelog.tip()
1460 tagtypes = dict([(encoding.tolocal(name), value)
1461 tagtypes = dict([(encoding.tolocal(name), value)
1461 for (name, value) in tagtypes.iteritems()])
1462 for (name, value) in tagtypes.iteritems()])
1462 return (tags, tagtypes)
1463 return (tags, tagtypes)
1463
1464
1464 def tagtype(self, tagname):
1465 def tagtype(self, tagname):
1465 '''
1466 '''
1466 return the type of the given tag. result can be:
1467 return the type of the given tag. result can be:
1467
1468
1468 'local' : a local tag
1469 'local' : a local tag
1469 'global' : a global tag
1470 'global' : a global tag
1470 None : tag does not exist
1471 None : tag does not exist
1471 '''
1472 '''
1472
1473
1473 return self._tagscache.tagtypes.get(tagname)
1474 return self._tagscache.tagtypes.get(tagname)
1474
1475
1475 def tagslist(self):
1476 def tagslist(self):
1476 '''return a list of tags ordered by revision'''
1477 '''return a list of tags ordered by revision'''
1477 if not self._tagscache.tagslist:
1478 if not self._tagscache.tagslist:
1478 l = []
1479 l = []
1479 for t, n in self.tags().iteritems():
1480 for t, n in self.tags().iteritems():
1480 l.append((self.changelog.rev(n), t, n))
1481 l.append((self.changelog.rev(n), t, n))
1481 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1482 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1482
1483
1483 return self._tagscache.tagslist
1484 return self._tagscache.tagslist
1484
1485
1485 def nodetags(self, node):
1486 def nodetags(self, node):
1486 '''return the tags associated with a node'''
1487 '''return the tags associated with a node'''
1487 if not self._tagscache.nodetagscache:
1488 if not self._tagscache.nodetagscache:
1488 nodetagscache = {}
1489 nodetagscache = {}
1489 for t, n in self._tagscache.tags.iteritems():
1490 for t, n in self._tagscache.tags.iteritems():
1490 nodetagscache.setdefault(n, []).append(t)
1491 nodetagscache.setdefault(n, []).append(t)
1491 for tags in nodetagscache.itervalues():
1492 for tags in nodetagscache.itervalues():
1492 tags.sort()
1493 tags.sort()
1493 self._tagscache.nodetagscache = nodetagscache
1494 self._tagscache.nodetagscache = nodetagscache
1494 return self._tagscache.nodetagscache.get(node, [])
1495 return self._tagscache.nodetagscache.get(node, [])
1495
1496
1496 def nodebookmarks(self, node):
1497 def nodebookmarks(self, node):
1497 """return the list of bookmarks pointing to the specified node"""
1498 """return the list of bookmarks pointing to the specified node"""
1498 return self._bookmarks.names(node)
1499 return self._bookmarks.names(node)
1499
1500
1500 def branchmap(self):
1501 def branchmap(self):
1501 '''returns a dictionary {branch: [branchheads]} with branchheads
1502 '''returns a dictionary {branch: [branchheads]} with branchheads
1502 ordered by increasing revision number'''
1503 ordered by increasing revision number'''
1503 branchmap.updatecache(self)
1504 branchmap.updatecache(self)
1504 return self._branchcaches[self.filtername]
1505 return self._branchcaches[self.filtername]
1505
1506
1506 @unfilteredmethod
1507 @unfilteredmethod
1507 def revbranchcache(self):
1508 def revbranchcache(self):
1508 if not self._revbranchcache:
1509 if not self._revbranchcache:
1509 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1510 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1510 return self._revbranchcache
1511 return self._revbranchcache
1511
1512
1512 def branchtip(self, branch, ignoremissing=False):
1513 def branchtip(self, branch, ignoremissing=False):
1513 '''return the tip node for a given branch
1514 '''return the tip node for a given branch
1514
1515
1515 If ignoremissing is True, then this method will not raise an error.
1516 If ignoremissing is True, then this method will not raise an error.
1516 This is helpful for callers that only expect None for a missing branch
1517 This is helpful for callers that only expect None for a missing branch
1517 (e.g. namespace).
1518 (e.g. namespace).
1518
1519
1519 '''
1520 '''
1520 try:
1521 try:
1521 return self.branchmap().branchtip(branch)
1522 return self.branchmap().branchtip(branch)
1522 except KeyError:
1523 except KeyError:
1523 if not ignoremissing:
1524 if not ignoremissing:
1524 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1525 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1525 else:
1526 else:
1526 pass
1527 pass
1527
1528
1528 def lookup(self, key):
1529 def lookup(self, key):
1529 return scmutil.revsymbol(self, key).node()
1530 return scmutil.revsymbol(self, key).node()
1530
1531
1531 def lookupbranch(self, key):
1532 def lookupbranch(self, key):
1532 if key in self.branchmap():
1533 if key in self.branchmap():
1533 return key
1534 return key
1534
1535
1535 return scmutil.revsymbol(self, key).branch()
1536 return scmutil.revsymbol(self, key).branch()
1536
1537
1537 def known(self, nodes):
1538 def known(self, nodes):
1538 cl = self.changelog
1539 cl = self.changelog
1539 nm = cl.nodemap
1540 nm = cl.nodemap
1540 filtered = cl.filteredrevs
1541 filtered = cl.filteredrevs
1541 result = []
1542 result = []
1542 for n in nodes:
1543 for n in nodes:
1543 r = nm.get(n)
1544 r = nm.get(n)
1544 resp = not (r is None or r in filtered)
1545 resp = not (r is None or r in filtered)
1545 result.append(resp)
1546 result.append(resp)
1546 return result
1547 return result
1547
1548
1548 def local(self):
1549 def local(self):
1549 return self
1550 return self
1550
1551
1551 def publishing(self):
1552 def publishing(self):
1552 # it's safe (and desirable) to trust the publish flag unconditionally
1553 # it's safe (and desirable) to trust the publish flag unconditionally
1553 # so that we don't finalize changes shared between users via ssh or nfs
1554 # so that we don't finalize changes shared between users via ssh or nfs
1554 return self.ui.configbool('phases', 'publish', untrusted=True)
1555 return self.ui.configbool('phases', 'publish', untrusted=True)
1555
1556
1556 def cancopy(self):
1557 def cancopy(self):
1557 # so statichttprepo's override of local() works
1558 # so statichttprepo's override of local() works
1558 if not self.local():
1559 if not self.local():
1559 return False
1560 return False
1560 if not self.publishing():
1561 if not self.publishing():
1561 return True
1562 return True
1562 # if publishing we can't copy if there is filtered content
1563 # if publishing we can't copy if there is filtered content
1563 return not self.filtered('visible').changelog.filteredrevs
1564 return not self.filtered('visible').changelog.filteredrevs
1564
1565
1565 def shared(self):
1566 def shared(self):
1566 '''the type of shared repository (None if not shared)'''
1567 '''the type of shared repository (None if not shared)'''
1567 if self.sharedpath != self.path:
1568 if self.sharedpath != self.path:
1568 return 'store'
1569 return 'store'
1569 return None
1570 return None
1570
1571
1571 def wjoin(self, f, *insidef):
1572 def wjoin(self, f, *insidef):
1572 return self.vfs.reljoin(self.root, f, *insidef)
1573 return self.vfs.reljoin(self.root, f, *insidef)
1573
1574
1574 def setparents(self, p1, p2=nullid):
1575 def setparents(self, p1, p2=nullid):
1575 with self.dirstate.parentchange():
1576 with self.dirstate.parentchange():
1576 copies = self.dirstate.setparents(p1, p2)
1577 copies = self.dirstate.setparents(p1, p2)
1577 pctx = self[p1]
1578 pctx = self[p1]
1578 if copies:
1579 if copies:
1579 # Adjust copy records, the dirstate cannot do it, it
1580 # Adjust copy records, the dirstate cannot do it, it
1580 # requires access to parents manifests. Preserve them
1581 # requires access to parents manifests. Preserve them
1581 # only for entries added to first parent.
1582 # only for entries added to first parent.
1582 for f in copies:
1583 for f in copies:
1583 if f not in pctx and copies[f] in pctx:
1584 if f not in pctx and copies[f] in pctx:
1584 self.dirstate.copy(copies[f], f)
1585 self.dirstate.copy(copies[f], f)
1585 if p2 == nullid:
1586 if p2 == nullid:
1586 for f, s in sorted(self.dirstate.copies().items()):
1587 for f, s in sorted(self.dirstate.copies().items()):
1587 if f not in pctx and s not in pctx:
1588 if f not in pctx and s not in pctx:
1588 self.dirstate.copy(None, f)
1589 self.dirstate.copy(None, f)
1589
1590
1590 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1591 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1591 """changeid must be a changeset revision, if specified.
1592 """changeid must be a changeset revision, if specified.
1592 fileid can be a file revision or node."""
1593 fileid can be a file revision or node."""
1593 return context.filectx(self, path, changeid, fileid,
1594 return context.filectx(self, path, changeid, fileid,
1594 changectx=changectx)
1595 changectx=changectx)
1595
1596
1596 def getcwd(self):
1597 def getcwd(self):
1597 return self.dirstate.getcwd()
1598 return self.dirstate.getcwd()
1598
1599
1599 def pathto(self, f, cwd=None):
1600 def pathto(self, f, cwd=None):
1600 return self.dirstate.pathto(f, cwd)
1601 return self.dirstate.pathto(f, cwd)
1601
1602
1602 def _loadfilter(self, filter):
1603 def _loadfilter(self, filter):
1603 if filter not in self._filterpats:
1604 if filter not in self._filterpats:
1604 l = []
1605 l = []
1605 for pat, cmd in self.ui.configitems(filter):
1606 for pat, cmd in self.ui.configitems(filter):
1606 if cmd == '!':
1607 if cmd == '!':
1607 continue
1608 continue
1608 mf = matchmod.match(self.root, '', [pat])
1609 mf = matchmod.match(self.root, '', [pat])
1609 fn = None
1610 fn = None
1610 params = cmd
1611 params = cmd
1611 for name, filterfn in self._datafilters.iteritems():
1612 for name, filterfn in self._datafilters.iteritems():
1612 if cmd.startswith(name):
1613 if cmd.startswith(name):
1613 fn = filterfn
1614 fn = filterfn
1614 params = cmd[len(name):].lstrip()
1615 params = cmd[len(name):].lstrip()
1615 break
1616 break
1616 if not fn:
1617 if not fn:
1617 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1618 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1618 # Wrap old filters not supporting keyword arguments
1619 # Wrap old filters not supporting keyword arguments
1619 if not pycompat.getargspec(fn)[2]:
1620 if not pycompat.getargspec(fn)[2]:
1620 oldfn = fn
1621 oldfn = fn
1621 fn = lambda s, c, **kwargs: oldfn(s, c)
1622 fn = lambda s, c, **kwargs: oldfn(s, c)
1622 l.append((mf, fn, params))
1623 l.append((mf, fn, params))
1623 self._filterpats[filter] = l
1624 self._filterpats[filter] = l
1624 return self._filterpats[filter]
1625 return self._filterpats[filter]
1625
1626
1626 def _filter(self, filterpats, filename, data):
1627 def _filter(self, filterpats, filename, data):
1627 for mf, fn, cmd in filterpats:
1628 for mf, fn, cmd in filterpats:
1628 if mf(filename):
1629 if mf(filename):
1629 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1630 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1630 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1631 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1631 break
1632 break
1632
1633
1633 return data
1634 return data
1634
1635
1635 @unfilteredpropertycache
1636 @unfilteredpropertycache
1636 def _encodefilterpats(self):
1637 def _encodefilterpats(self):
1637 return self._loadfilter('encode')
1638 return self._loadfilter('encode')
1638
1639
1639 @unfilteredpropertycache
1640 @unfilteredpropertycache
1640 def _decodefilterpats(self):
1641 def _decodefilterpats(self):
1641 return self._loadfilter('decode')
1642 return self._loadfilter('decode')
1642
1643
1643 def adddatafilter(self, name, filter):
1644 def adddatafilter(self, name, filter):
1644 self._datafilters[name] = filter
1645 self._datafilters[name] = filter
1645
1646
1646 def wread(self, filename):
1647 def wread(self, filename):
1647 if self.wvfs.islink(filename):
1648 if self.wvfs.islink(filename):
1648 data = self.wvfs.readlink(filename)
1649 data = self.wvfs.readlink(filename)
1649 else:
1650 else:
1650 data = self.wvfs.read(filename)
1651 data = self.wvfs.read(filename)
1651 return self._filter(self._encodefilterpats, filename, data)
1652 return self._filter(self._encodefilterpats, filename, data)
1652
1653
1653 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1654 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1654 """write ``data`` into ``filename`` in the working directory
1655 """write ``data`` into ``filename`` in the working directory
1655
1656
1656 This returns length of written (maybe decoded) data.
1657 This returns length of written (maybe decoded) data.
1657 """
1658 """
1658 data = self._filter(self._decodefilterpats, filename, data)
1659 data = self._filter(self._decodefilterpats, filename, data)
1659 if 'l' in flags:
1660 if 'l' in flags:
1660 self.wvfs.symlink(data, filename)
1661 self.wvfs.symlink(data, filename)
1661 else:
1662 else:
1662 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1663 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1663 **kwargs)
1664 **kwargs)
1664 if 'x' in flags:
1665 if 'x' in flags:
1665 self.wvfs.setflags(filename, False, True)
1666 self.wvfs.setflags(filename, False, True)
1666 else:
1667 else:
1667 self.wvfs.setflags(filename, False, False)
1668 self.wvfs.setflags(filename, False, False)
1668 return len(data)
1669 return len(data)
1669
1670
1670 def wwritedata(self, filename, data):
1671 def wwritedata(self, filename, data):
1671 return self._filter(self._decodefilterpats, filename, data)
1672 return self._filter(self._decodefilterpats, filename, data)
1672
1673
1673 def currenttransaction(self):
1674 def currenttransaction(self):
1674 """return the current transaction or None if non exists"""
1675 """return the current transaction or None if non exists"""
1675 if self._transref:
1676 if self._transref:
1676 tr = self._transref()
1677 tr = self._transref()
1677 else:
1678 else:
1678 tr = None
1679 tr = None
1679
1680
1680 if tr and tr.running():
1681 if tr and tr.running():
1681 return tr
1682 return tr
1682 return None
1683 return None
1683
1684
1684 def transaction(self, desc, report=None):
1685 def transaction(self, desc, report=None):
1685 if (self.ui.configbool('devel', 'all-warnings')
1686 if (self.ui.configbool('devel', 'all-warnings')
1686 or self.ui.configbool('devel', 'check-locks')):
1687 or self.ui.configbool('devel', 'check-locks')):
1687 if self._currentlock(self._lockref) is None:
1688 if self._currentlock(self._lockref) is None:
1688 raise error.ProgrammingError('transaction requires locking')
1689 raise error.ProgrammingError('transaction requires locking')
1689 tr = self.currenttransaction()
1690 tr = self.currenttransaction()
1690 if tr is not None:
1691 if tr is not None:
1691 return tr.nest(name=desc)
1692 return tr.nest(name=desc)
1692
1693
1693 # abort here if the journal already exists
1694 # abort here if the journal already exists
1694 if self.svfs.exists("journal"):
1695 if self.svfs.exists("journal"):
1695 raise error.RepoError(
1696 raise error.RepoError(
1696 _("abandoned transaction found"),
1697 _("abandoned transaction found"),
1697 hint=_("run 'hg recover' to clean up transaction"))
1698 hint=_("run 'hg recover' to clean up transaction"))
1698
1699
1699 idbase = "%.40f#%f" % (random.random(), time.time())
1700 idbase = "%.40f#%f" % (random.random(), time.time())
1700 ha = hex(hashlib.sha1(idbase).digest())
1701 ha = hex(hashlib.sha1(idbase).digest())
1701 txnid = 'TXN:' + ha
1702 txnid = 'TXN:' + ha
1702 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1703 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1703
1704
1704 self._writejournal(desc)
1705 self._writejournal(desc)
1705 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1706 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1706 if report:
1707 if report:
1707 rp = report
1708 rp = report
1708 else:
1709 else:
1709 rp = self.ui.warn
1710 rp = self.ui.warn
1710 vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/
1711 vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/
1711 # we must avoid cyclic reference between repo and transaction.
1712 # we must avoid cyclic reference between repo and transaction.
1712 reporef = weakref.ref(self)
1713 reporef = weakref.ref(self)
1713 # Code to track tag movement
1714 # Code to track tag movement
1714 #
1715 #
1715 # Since tags are all handled as file content, it is actually quite hard
1716 # Since tags are all handled as file content, it is actually quite hard
1716 # to track these movement from a code perspective. So we fallback to a
1717 # to track these movement from a code perspective. So we fallback to a
1717 # tracking at the repository level. One could envision to track changes
1718 # tracking at the repository level. One could envision to track changes
1718 # to the '.hgtags' file through changegroup apply but that fails to
1719 # to the '.hgtags' file through changegroup apply but that fails to
1719 # cope with case where transaction expose new heads without changegroup
1720 # cope with case where transaction expose new heads without changegroup
1720 # being involved (eg: phase movement).
1721 # being involved (eg: phase movement).
1721 #
1722 #
1722 # For now, We gate the feature behind a flag since this likely comes
1723 # For now, We gate the feature behind a flag since this likely comes
1723 # with performance impacts. The current code run more often than needed
1724 # with performance impacts. The current code run more often than needed
1724 # and do not use caches as much as it could. The current focus is on
1725 # and do not use caches as much as it could. The current focus is on
1725 # the behavior of the feature so we disable it by default. The flag
1726 # the behavior of the feature so we disable it by default. The flag
1726 # will be removed when we are happy with the performance impact.
1727 # will be removed when we are happy with the performance impact.
1727 #
1728 #
1728 # Once this feature is no longer experimental move the following
1729 # Once this feature is no longer experimental move the following
1729 # documentation to the appropriate help section:
1730 # documentation to the appropriate help section:
1730 #
1731 #
1731 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1732 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1732 # tags (new or changed or deleted tags). In addition the details of
1733 # tags (new or changed or deleted tags). In addition the details of
1733 # these changes are made available in a file at:
1734 # these changes are made available in a file at:
1734 # ``REPOROOT/.hg/changes/tags.changes``.
1735 # ``REPOROOT/.hg/changes/tags.changes``.
1735 # Make sure you check for HG_TAG_MOVED before reading that file as it
1736 # Make sure you check for HG_TAG_MOVED before reading that file as it
1736 # might exist from a previous transaction even if no tag were touched
1737 # might exist from a previous transaction even if no tag were touched
1737 # in this one. Changes are recorded in a line base format::
1738 # in this one. Changes are recorded in a line base format::
1738 #
1739 #
1739 # <action> <hex-node> <tag-name>\n
1740 # <action> <hex-node> <tag-name>\n
1740 #
1741 #
1741 # Actions are defined as follow:
1742 # Actions are defined as follow:
1742 # "-R": tag is removed,
1743 # "-R": tag is removed,
1743 # "+A": tag is added,
1744 # "+A": tag is added,
1744 # "-M": tag is moved (old value),
1745 # "-M": tag is moved (old value),
1745 # "+M": tag is moved (new value),
1746 # "+M": tag is moved (new value),
1746 tracktags = lambda x: None
1747 tracktags = lambda x: None
1747 # experimental config: experimental.hook-track-tags
1748 # experimental config: experimental.hook-track-tags
1748 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1749 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1749 if desc != 'strip' and shouldtracktags:
1750 if desc != 'strip' and shouldtracktags:
1750 oldheads = self.changelog.headrevs()
1751 oldheads = self.changelog.headrevs()
1751 def tracktags(tr2):
1752 def tracktags(tr2):
1752 repo = reporef()
1753 repo = reporef()
1753 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1754 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1754 newheads = repo.changelog.headrevs()
1755 newheads = repo.changelog.headrevs()
1755 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1756 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1756 # notes: we compare lists here.
1757 # notes: we compare lists here.
1757 # As we do it only once buiding set would not be cheaper
1758 # As we do it only once buiding set would not be cheaper
1758 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1759 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1759 if changes:
1760 if changes:
1760 tr2.hookargs['tag_moved'] = '1'
1761 tr2.hookargs['tag_moved'] = '1'
1761 with repo.vfs('changes/tags.changes', 'w',
1762 with repo.vfs('changes/tags.changes', 'w',
1762 atomictemp=True) as changesfile:
1763 atomictemp=True) as changesfile:
1763 # note: we do not register the file to the transaction
1764 # note: we do not register the file to the transaction
1764 # because we needs it to still exist on the transaction
1765 # because we needs it to still exist on the transaction
1765 # is close (for txnclose hooks)
1766 # is close (for txnclose hooks)
1766 tagsmod.writediff(changesfile, changes)
1767 tagsmod.writediff(changesfile, changes)
1767 def validate(tr2):
1768 def validate(tr2):
1768 """will run pre-closing hooks"""
1769 """will run pre-closing hooks"""
1769 # XXX the transaction API is a bit lacking here so we take a hacky
1770 # XXX the transaction API is a bit lacking here so we take a hacky
1770 # path for now
1771 # path for now
1771 #
1772 #
1772 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1773 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1773 # dict is copied before these run. In addition we needs the data
1774 # dict is copied before these run. In addition we needs the data
1774 # available to in memory hooks too.
1775 # available to in memory hooks too.
1775 #
1776 #
1776 # Moreover, we also need to make sure this runs before txnclose
1777 # Moreover, we also need to make sure this runs before txnclose
1777 # hooks and there is no "pending" mechanism that would execute
1778 # hooks and there is no "pending" mechanism that would execute
1778 # logic only if hooks are about to run.
1779 # logic only if hooks are about to run.
1779 #
1780 #
1780 # Fixing this limitation of the transaction is also needed to track
1781 # Fixing this limitation of the transaction is also needed to track
1781 # other families of changes (bookmarks, phases, obsolescence).
1782 # other families of changes (bookmarks, phases, obsolescence).
1782 #
1783 #
1783 # This will have to be fixed before we remove the experimental
1784 # This will have to be fixed before we remove the experimental
1784 # gating.
1785 # gating.
1785 tracktags(tr2)
1786 tracktags(tr2)
1786 repo = reporef()
1787 repo = reporef()
1787 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1788 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1788 scmutil.enforcesinglehead(repo, tr2, desc)
1789 scmutil.enforcesinglehead(repo, tr2, desc)
1789 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1790 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1790 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1791 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1791 args = tr.hookargs.copy()
1792 args = tr.hookargs.copy()
1792 args.update(bookmarks.preparehookargs(name, old, new))
1793 args.update(bookmarks.preparehookargs(name, old, new))
1793 repo.hook('pretxnclose-bookmark', throw=True,
1794 repo.hook('pretxnclose-bookmark', throw=True,
1794 txnname=desc,
1795 txnname=desc,
1795 **pycompat.strkwargs(args))
1796 **pycompat.strkwargs(args))
1796 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1797 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1797 cl = repo.unfiltered().changelog
1798 cl = repo.unfiltered().changelog
1798 for rev, (old, new) in tr.changes['phases'].items():
1799 for rev, (old, new) in tr.changes['phases'].items():
1799 args = tr.hookargs.copy()
1800 args = tr.hookargs.copy()
1800 node = hex(cl.node(rev))
1801 node = hex(cl.node(rev))
1801 args.update(phases.preparehookargs(node, old, new))
1802 args.update(phases.preparehookargs(node, old, new))
1802 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1803 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1803 **pycompat.strkwargs(args))
1804 **pycompat.strkwargs(args))
1804
1805
1805 repo.hook('pretxnclose', throw=True,
1806 repo.hook('pretxnclose', throw=True,
1806 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1807 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1807 def releasefn(tr, success):
1808 def releasefn(tr, success):
1808 repo = reporef()
1809 repo = reporef()
1809 if success:
1810 if success:
1810 # this should be explicitly invoked here, because
1811 # this should be explicitly invoked here, because
1811 # in-memory changes aren't written out at closing
1812 # in-memory changes aren't written out at closing
1812 # transaction, if tr.addfilegenerator (via
1813 # transaction, if tr.addfilegenerator (via
1813 # dirstate.write or so) isn't invoked while
1814 # dirstate.write or so) isn't invoked while
1814 # transaction running
1815 # transaction running
1815 repo.dirstate.write(None)
1816 repo.dirstate.write(None)
1816 else:
1817 else:
1817 # discard all changes (including ones already written
1818 # discard all changes (including ones already written
1818 # out) in this transaction
1819 # out) in this transaction
1819 narrowspec.restorebackup(self, 'journal.narrowspec')
1820 narrowspec.restorebackup(self, 'journal.narrowspec')
1820 repo.dirstate.restorebackup(None, 'journal.dirstate')
1821 repo.dirstate.restorebackup(None, 'journal.dirstate')
1821
1822
1822 repo.invalidate(clearfilecache=True)
1823 repo.invalidate(clearfilecache=True)
1823
1824
1824 tr = transaction.transaction(rp, self.svfs, vfsmap,
1825 tr = transaction.transaction(rp, self.svfs, vfsmap,
1825 "journal",
1826 "journal",
1826 "undo",
1827 "undo",
1827 aftertrans(renames),
1828 aftertrans(renames),
1828 self.store.createmode,
1829 self.store.createmode,
1829 validator=validate,
1830 validator=validate,
1830 releasefn=releasefn,
1831 releasefn=releasefn,
1831 checkambigfiles=_cachedfiles,
1832 checkambigfiles=_cachedfiles,
1832 name=desc)
1833 name=desc)
1833 tr.changes['origrepolen'] = len(self)
1834 tr.changes['origrepolen'] = len(self)
1834 tr.changes['obsmarkers'] = set()
1835 tr.changes['obsmarkers'] = set()
1835 tr.changes['phases'] = {}
1836 tr.changes['phases'] = {}
1836 tr.changes['bookmarks'] = {}
1837 tr.changes['bookmarks'] = {}
1837
1838
1838 tr.hookargs['txnid'] = txnid
1839 tr.hookargs['txnid'] = txnid
1839 # note: writing the fncache only during finalize mean that the file is
1840 # note: writing the fncache only during finalize mean that the file is
1840 # outdated when running hooks. As fncache is used for streaming clone,
1841 # outdated when running hooks. As fncache is used for streaming clone,
1841 # this is not expected to break anything that happen during the hooks.
1842 # this is not expected to break anything that happen during the hooks.
1842 tr.addfinalize('flush-fncache', self.store.write)
1843 tr.addfinalize('flush-fncache', self.store.write)
1843 def txnclosehook(tr2):
1844 def txnclosehook(tr2):
1844 """To be run if transaction is successful, will schedule a hook run
1845 """To be run if transaction is successful, will schedule a hook run
1845 """
1846 """
1846 # Don't reference tr2 in hook() so we don't hold a reference.
1847 # Don't reference tr2 in hook() so we don't hold a reference.
1847 # This reduces memory consumption when there are multiple
1848 # This reduces memory consumption when there are multiple
1848 # transactions per lock. This can likely go away if issue5045
1849 # transactions per lock. This can likely go away if issue5045
1849 # fixes the function accumulation.
1850 # fixes the function accumulation.
1850 hookargs = tr2.hookargs
1851 hookargs = tr2.hookargs
1851
1852
1852 def hookfunc():
1853 def hookfunc():
1853 repo = reporef()
1854 repo = reporef()
1854 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1855 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1855 bmchanges = sorted(tr.changes['bookmarks'].items())
1856 bmchanges = sorted(tr.changes['bookmarks'].items())
1856 for name, (old, new) in bmchanges:
1857 for name, (old, new) in bmchanges:
1857 args = tr.hookargs.copy()
1858 args = tr.hookargs.copy()
1858 args.update(bookmarks.preparehookargs(name, old, new))
1859 args.update(bookmarks.preparehookargs(name, old, new))
1859 repo.hook('txnclose-bookmark', throw=False,
1860 repo.hook('txnclose-bookmark', throw=False,
1860 txnname=desc, **pycompat.strkwargs(args))
1861 txnname=desc, **pycompat.strkwargs(args))
1861
1862
1862 if hook.hashook(repo.ui, 'txnclose-phase'):
1863 if hook.hashook(repo.ui, 'txnclose-phase'):
1863 cl = repo.unfiltered().changelog
1864 cl = repo.unfiltered().changelog
1864 phasemv = sorted(tr.changes['phases'].items())
1865 phasemv = sorted(tr.changes['phases'].items())
1865 for rev, (old, new) in phasemv:
1866 for rev, (old, new) in phasemv:
1866 args = tr.hookargs.copy()
1867 args = tr.hookargs.copy()
1867 node = hex(cl.node(rev))
1868 node = hex(cl.node(rev))
1868 args.update(phases.preparehookargs(node, old, new))
1869 args.update(phases.preparehookargs(node, old, new))
1869 repo.hook('txnclose-phase', throw=False, txnname=desc,
1870 repo.hook('txnclose-phase', throw=False, txnname=desc,
1870 **pycompat.strkwargs(args))
1871 **pycompat.strkwargs(args))
1871
1872
1872 repo.hook('txnclose', throw=False, txnname=desc,
1873 repo.hook('txnclose', throw=False, txnname=desc,
1873 **pycompat.strkwargs(hookargs))
1874 **pycompat.strkwargs(hookargs))
1874 reporef()._afterlock(hookfunc)
1875 reporef()._afterlock(hookfunc)
1875 tr.addfinalize('txnclose-hook', txnclosehook)
1876 tr.addfinalize('txnclose-hook', txnclosehook)
1876 # Include a leading "-" to make it happen before the transaction summary
1877 # Include a leading "-" to make it happen before the transaction summary
1877 # reports registered via scmutil.registersummarycallback() whose names
1878 # reports registered via scmutil.registersummarycallback() whose names
1878 # are 00-txnreport etc. That way, the caches will be warm when the
1879 # are 00-txnreport etc. That way, the caches will be warm when the
1879 # callbacks run.
1880 # callbacks run.
1880 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1881 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1881 def txnaborthook(tr2):
1882 def txnaborthook(tr2):
1882 """To be run if transaction is aborted
1883 """To be run if transaction is aborted
1883 """
1884 """
1884 reporef().hook('txnabort', throw=False, txnname=desc,
1885 reporef().hook('txnabort', throw=False, txnname=desc,
1885 **pycompat.strkwargs(tr2.hookargs))
1886 **pycompat.strkwargs(tr2.hookargs))
1886 tr.addabort('txnabort-hook', txnaborthook)
1887 tr.addabort('txnabort-hook', txnaborthook)
1887 # avoid eager cache invalidation. in-memory data should be identical
1888 # avoid eager cache invalidation. in-memory data should be identical
1888 # to stored data if transaction has no error.
1889 # to stored data if transaction has no error.
1889 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1890 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1890 self._transref = weakref.ref(tr)
1891 self._transref = weakref.ref(tr)
1891 scmutil.registersummarycallback(self, tr, desc)
1892 scmutil.registersummarycallback(self, tr, desc)
1892 return tr
1893 return tr
1893
1894
1894 def _journalfiles(self):
1895 def _journalfiles(self):
1895 return ((self.svfs, 'journal'),
1896 return ((self.svfs, 'journal'),
1896 (self.vfs, 'journal.dirstate'),
1897 (self.vfs, 'journal.dirstate'),
1897 (self.vfs, 'journal.branch'),
1898 (self.vfs, 'journal.branch'),
1898 (self.vfs, 'journal.desc'),
1899 (self.vfs, 'journal.desc'),
1899 (self.vfs, 'journal.bookmarks'),
1900 (self.vfs, 'journal.bookmarks'),
1900 (self.svfs, 'journal.phaseroots'))
1901 (self.svfs, 'journal.phaseroots'))
1901
1902
1902 def undofiles(self):
1903 def undofiles(self):
1903 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1904 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1904
1905
1905 @unfilteredmethod
1906 @unfilteredmethod
1906 def _writejournal(self, desc):
1907 def _writejournal(self, desc):
1907 self.dirstate.savebackup(None, 'journal.dirstate')
1908 self.dirstate.savebackup(None, 'journal.dirstate')
1908 narrowspec.savebackup(self, 'journal.narrowspec')
1909 narrowspec.savebackup(self, 'journal.narrowspec')
1909 self.vfs.write("journal.branch",
1910 self.vfs.write("journal.branch",
1910 encoding.fromlocal(self.dirstate.branch()))
1911 encoding.fromlocal(self.dirstate.branch()))
1911 self.vfs.write("journal.desc",
1912 self.vfs.write("journal.desc",
1912 "%d\n%s\n" % (len(self), desc))
1913 "%d\n%s\n" % (len(self), desc))
1913 self.vfs.write("journal.bookmarks",
1914 self.vfs.write("journal.bookmarks",
1914 self.vfs.tryread("bookmarks"))
1915 self.vfs.tryread("bookmarks"))
1915 self.svfs.write("journal.phaseroots",
1916 self.svfs.write("journal.phaseroots",
1916 self.svfs.tryread("phaseroots"))
1917 self.svfs.tryread("phaseroots"))
1917
1918
1918 def recover(self):
1919 def recover(self):
1919 with self.lock():
1920 with self.lock():
1920 if self.svfs.exists("journal"):
1921 if self.svfs.exists("journal"):
1921 self.ui.status(_("rolling back interrupted transaction\n"))
1922 self.ui.status(_("rolling back interrupted transaction\n"))
1922 vfsmap = {'': self.svfs,
1923 vfsmap = {'': self.svfs,
1923 'plain': self.vfs,}
1924 'plain': self.vfs,}
1924 transaction.rollback(self.svfs, vfsmap, "journal",
1925 transaction.rollback(self.svfs, vfsmap, "journal",
1925 self.ui.warn,
1926 self.ui.warn,
1926 checkambigfiles=_cachedfiles)
1927 checkambigfiles=_cachedfiles)
1927 self.invalidate()
1928 self.invalidate()
1928 return True
1929 return True
1929 else:
1930 else:
1930 self.ui.warn(_("no interrupted transaction available\n"))
1931 self.ui.warn(_("no interrupted transaction available\n"))
1931 return False
1932 return False
1932
1933
1933 def rollback(self, dryrun=False, force=False):
1934 def rollback(self, dryrun=False, force=False):
1934 wlock = lock = dsguard = None
1935 wlock = lock = dsguard = None
1935 try:
1936 try:
1936 wlock = self.wlock()
1937 wlock = self.wlock()
1937 lock = self.lock()
1938 lock = self.lock()
1938 if self.svfs.exists("undo"):
1939 if self.svfs.exists("undo"):
1939 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1940 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1940
1941
1941 return self._rollback(dryrun, force, dsguard)
1942 return self._rollback(dryrun, force, dsguard)
1942 else:
1943 else:
1943 self.ui.warn(_("no rollback information available\n"))
1944 self.ui.warn(_("no rollback information available\n"))
1944 return 1
1945 return 1
1945 finally:
1946 finally:
1946 release(dsguard, lock, wlock)
1947 release(dsguard, lock, wlock)
1947
1948
1948 @unfilteredmethod # Until we get smarter cache management
1949 @unfilteredmethod # Until we get smarter cache management
1949 def _rollback(self, dryrun, force, dsguard):
1950 def _rollback(self, dryrun, force, dsguard):
1950 ui = self.ui
1951 ui = self.ui
1951 try:
1952 try:
1952 args = self.vfs.read('undo.desc').splitlines()
1953 args = self.vfs.read('undo.desc').splitlines()
1953 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1954 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1954 if len(args) >= 3:
1955 if len(args) >= 3:
1955 detail = args[2]
1956 detail = args[2]
1956 oldtip = oldlen - 1
1957 oldtip = oldlen - 1
1957
1958
1958 if detail and ui.verbose:
1959 if detail and ui.verbose:
1959 msg = (_('repository tip rolled back to revision %d'
1960 msg = (_('repository tip rolled back to revision %d'
1960 ' (undo %s: %s)\n')
1961 ' (undo %s: %s)\n')
1961 % (oldtip, desc, detail))
1962 % (oldtip, desc, detail))
1962 else:
1963 else:
1963 msg = (_('repository tip rolled back to revision %d'
1964 msg = (_('repository tip rolled back to revision %d'
1964 ' (undo %s)\n')
1965 ' (undo %s)\n')
1965 % (oldtip, desc))
1966 % (oldtip, desc))
1966 except IOError:
1967 except IOError:
1967 msg = _('rolling back unknown transaction\n')
1968 msg = _('rolling back unknown transaction\n')
1968 desc = None
1969 desc = None
1969
1970
1970 if not force and self['.'] != self['tip'] and desc == 'commit':
1971 if not force and self['.'] != self['tip'] and desc == 'commit':
1971 raise error.Abort(
1972 raise error.Abort(
1972 _('rollback of last commit while not checked out '
1973 _('rollback of last commit while not checked out '
1973 'may lose data'), hint=_('use -f to force'))
1974 'may lose data'), hint=_('use -f to force'))
1974
1975
1975 ui.status(msg)
1976 ui.status(msg)
1976 if dryrun:
1977 if dryrun:
1977 return 0
1978 return 0
1978
1979
1979 parents = self.dirstate.parents()
1980 parents = self.dirstate.parents()
1980 self.destroying()
1981 self.destroying()
1981 vfsmap = {'plain': self.vfs, '': self.svfs}
1982 vfsmap = {'plain': self.vfs, '': self.svfs}
1982 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1983 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1983 checkambigfiles=_cachedfiles)
1984 checkambigfiles=_cachedfiles)
1984 if self.vfs.exists('undo.bookmarks'):
1985 if self.vfs.exists('undo.bookmarks'):
1985 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1986 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1986 if self.svfs.exists('undo.phaseroots'):
1987 if self.svfs.exists('undo.phaseroots'):
1987 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1988 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1988 self.invalidate()
1989 self.invalidate()
1989
1990
1990 parentgone = (parents[0] not in self.changelog.nodemap or
1991 parentgone = (parents[0] not in self.changelog.nodemap or
1991 parents[1] not in self.changelog.nodemap)
1992 parents[1] not in self.changelog.nodemap)
1992 if parentgone:
1993 if parentgone:
1993 # prevent dirstateguard from overwriting already restored one
1994 # prevent dirstateguard from overwriting already restored one
1994 dsguard.close()
1995 dsguard.close()
1995
1996
1996 narrowspec.restorebackup(self, 'undo.narrowspec')
1997 narrowspec.restorebackup(self, 'undo.narrowspec')
1997 self.dirstate.restorebackup(None, 'undo.dirstate')
1998 self.dirstate.restorebackup(None, 'undo.dirstate')
1998 try:
1999 try:
1999 branch = self.vfs.read('undo.branch')
2000 branch = self.vfs.read('undo.branch')
2000 self.dirstate.setbranch(encoding.tolocal(branch))
2001 self.dirstate.setbranch(encoding.tolocal(branch))
2001 except IOError:
2002 except IOError:
2002 ui.warn(_('named branch could not be reset: '
2003 ui.warn(_('named branch could not be reset: '
2003 'current branch is still \'%s\'\n')
2004 'current branch is still \'%s\'\n')
2004 % self.dirstate.branch())
2005 % self.dirstate.branch())
2005
2006
2006 parents = tuple([p.rev() for p in self[None].parents()])
2007 parents = tuple([p.rev() for p in self[None].parents()])
2007 if len(parents) > 1:
2008 if len(parents) > 1:
2008 ui.status(_('working directory now based on '
2009 ui.status(_('working directory now based on '
2009 'revisions %d and %d\n') % parents)
2010 'revisions %d and %d\n') % parents)
2010 else:
2011 else:
2011 ui.status(_('working directory now based on '
2012 ui.status(_('working directory now based on '
2012 'revision %d\n') % parents)
2013 'revision %d\n') % parents)
2013 mergemod.mergestate.clean(self, self['.'].node())
2014 mergemod.mergestate.clean(self, self['.'].node())
2014
2015
2015 # TODO: if we know which new heads may result from this rollback, pass
2016 # TODO: if we know which new heads may result from this rollback, pass
2016 # them to destroy(), which will prevent the branchhead cache from being
2017 # them to destroy(), which will prevent the branchhead cache from being
2017 # invalidated.
2018 # invalidated.
2018 self.destroyed()
2019 self.destroyed()
2019 return 0
2020 return 0
2020
2021
2021 def _buildcacheupdater(self, newtransaction):
2022 def _buildcacheupdater(self, newtransaction):
2022 """called during transaction to build the callback updating cache
2023 """called during transaction to build the callback updating cache
2023
2024
2024 Lives on the repository to help extension who might want to augment
2025 Lives on the repository to help extension who might want to augment
2025 this logic. For this purpose, the created transaction is passed to the
2026 this logic. For this purpose, the created transaction is passed to the
2026 method.
2027 method.
2027 """
2028 """
2028 # we must avoid cyclic reference between repo and transaction.
2029 # we must avoid cyclic reference between repo and transaction.
2029 reporef = weakref.ref(self)
2030 reporef = weakref.ref(self)
2030 def updater(tr):
2031 def updater(tr):
2031 repo = reporef()
2032 repo = reporef()
2032 repo.updatecaches(tr)
2033 repo.updatecaches(tr)
2033 return updater
2034 return updater
2034
2035
2035 @unfilteredmethod
2036 @unfilteredmethod
2036 def updatecaches(self, tr=None, full=False):
2037 def updatecaches(self, tr=None, full=False):
2037 """warm appropriate caches
2038 """warm appropriate caches
2038
2039
2039 If this function is called after a transaction closed. The transaction
2040 If this function is called after a transaction closed. The transaction
2040 will be available in the 'tr' argument. This can be used to selectively
2041 will be available in the 'tr' argument. This can be used to selectively
2041 update caches relevant to the changes in that transaction.
2042 update caches relevant to the changes in that transaction.
2042
2043
2043 If 'full' is set, make sure all caches the function knows about have
2044 If 'full' is set, make sure all caches the function knows about have
2044 up-to-date data. Even the ones usually loaded more lazily.
2045 up-to-date data. Even the ones usually loaded more lazily.
2045 """
2046 """
2046 if tr is not None and tr.hookargs.get('source') == 'strip':
2047 if tr is not None and tr.hookargs.get('source') == 'strip':
2047 # During strip, many caches are invalid but
2048 # During strip, many caches are invalid but
2048 # later call to `destroyed` will refresh them.
2049 # later call to `destroyed` will refresh them.
2049 return
2050 return
2050
2051
2051 if tr is None or tr.changes['origrepolen'] < len(self):
2052 if tr is None or tr.changes['origrepolen'] < len(self):
2052 # updating the unfiltered branchmap should refresh all the others,
2053 # updating the unfiltered branchmap should refresh all the others,
2053 self.ui.debug('updating the branch cache\n')
2054 self.ui.debug('updating the branch cache\n')
2054 branchmap.updatecache(self.filtered('served'))
2055 branchmap.updatecache(self.filtered('served'))
2055
2056
2056 if full:
2057 if full:
2057 rbc = self.revbranchcache()
2058 rbc = self.revbranchcache()
2058 for r in self.changelog:
2059 for r in self.changelog:
2059 rbc.branchinfo(r)
2060 rbc.branchinfo(r)
2060 rbc.write()
2061 rbc.write()
2061
2062
2062 # ensure the working copy parents are in the manifestfulltextcache
2063 # ensure the working copy parents are in the manifestfulltextcache
2063 for ctx in self['.'].parents():
2064 for ctx in self['.'].parents():
2064 ctx.manifest() # accessing the manifest is enough
2065 ctx.manifest() # accessing the manifest is enough
2065
2066
2066 def invalidatecaches(self):
2067 def invalidatecaches(self):
2067
2068
2068 if r'_tagscache' in vars(self):
2069 if r'_tagscache' in vars(self):
2069 # can't use delattr on proxy
2070 # can't use delattr on proxy
2070 del self.__dict__[r'_tagscache']
2071 del self.__dict__[r'_tagscache']
2071
2072
2072 self.unfiltered()._branchcaches.clear()
2073 self.unfiltered()._branchcaches.clear()
2073 self.invalidatevolatilesets()
2074 self.invalidatevolatilesets()
2074 self._sparsesignaturecache.clear()
2075 self._sparsesignaturecache.clear()
2075
2076
2076 def invalidatevolatilesets(self):
2077 def invalidatevolatilesets(self):
2077 self.filteredrevcache.clear()
2078 self.filteredrevcache.clear()
2078 obsolete.clearobscaches(self)
2079 obsolete.clearobscaches(self)
2079
2080
2080 def invalidatedirstate(self):
2081 def invalidatedirstate(self):
2081 '''Invalidates the dirstate, causing the next call to dirstate
2082 '''Invalidates the dirstate, causing the next call to dirstate
2082 to check if it was modified since the last time it was read,
2083 to check if it was modified since the last time it was read,
2083 rereading it if it has.
2084 rereading it if it has.
2084
2085
2085 This is different to dirstate.invalidate() that it doesn't always
2086 This is different to dirstate.invalidate() that it doesn't always
2086 rereads the dirstate. Use dirstate.invalidate() if you want to
2087 rereads the dirstate. Use dirstate.invalidate() if you want to
2087 explicitly read the dirstate again (i.e. restoring it to a previous
2088 explicitly read the dirstate again (i.e. restoring it to a previous
2088 known good state).'''
2089 known good state).'''
2089 if hasunfilteredcache(self, r'dirstate'):
2090 if hasunfilteredcache(self, r'dirstate'):
2090 for k in self.dirstate._filecache:
2091 for k in self.dirstate._filecache:
2091 try:
2092 try:
2092 delattr(self.dirstate, k)
2093 delattr(self.dirstate, k)
2093 except AttributeError:
2094 except AttributeError:
2094 pass
2095 pass
2095 delattr(self.unfiltered(), r'dirstate')
2096 delattr(self.unfiltered(), r'dirstate')
2096
2097
2097 def invalidate(self, clearfilecache=False):
2098 def invalidate(self, clearfilecache=False):
2098 '''Invalidates both store and non-store parts other than dirstate
2099 '''Invalidates both store and non-store parts other than dirstate
2099
2100
2100 If a transaction is running, invalidation of store is omitted,
2101 If a transaction is running, invalidation of store is omitted,
2101 because discarding in-memory changes might cause inconsistency
2102 because discarding in-memory changes might cause inconsistency
2102 (e.g. incomplete fncache causes unintentional failure, but
2103 (e.g. incomplete fncache causes unintentional failure, but
2103 redundant one doesn't).
2104 redundant one doesn't).
2104 '''
2105 '''
2105 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2106 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2106 for k in list(self._filecache.keys()):
2107 for k in list(self._filecache.keys()):
2107 # dirstate is invalidated separately in invalidatedirstate()
2108 # dirstate is invalidated separately in invalidatedirstate()
2108 if k == 'dirstate':
2109 if k == 'dirstate':
2109 continue
2110 continue
2110 if (k == 'changelog' and
2111 if (k == 'changelog' and
2111 self.currenttransaction() and
2112 self.currenttransaction() and
2112 self.changelog._delayed):
2113 self.changelog._delayed):
2113 # The changelog object may store unwritten revisions. We don't
2114 # The changelog object may store unwritten revisions. We don't
2114 # want to lose them.
2115 # want to lose them.
2115 # TODO: Solve the problem instead of working around it.
2116 # TODO: Solve the problem instead of working around it.
2116 continue
2117 continue
2117
2118
2118 if clearfilecache:
2119 if clearfilecache:
2119 del self._filecache[k]
2120 del self._filecache[k]
2120 try:
2121 try:
2121 delattr(unfiltered, k)
2122 delattr(unfiltered, k)
2122 except AttributeError:
2123 except AttributeError:
2123 pass
2124 pass
2124 self.invalidatecaches()
2125 self.invalidatecaches()
2125 if not self.currenttransaction():
2126 if not self.currenttransaction():
2126 # TODO: Changing contents of store outside transaction
2127 # TODO: Changing contents of store outside transaction
2127 # causes inconsistency. We should make in-memory store
2128 # causes inconsistency. We should make in-memory store
2128 # changes detectable, and abort if changed.
2129 # changes detectable, and abort if changed.
2129 self.store.invalidatecaches()
2130 self.store.invalidatecaches()
2130
2131
2131 def invalidateall(self):
2132 def invalidateall(self):
2132 '''Fully invalidates both store and non-store parts, causing the
2133 '''Fully invalidates both store and non-store parts, causing the
2133 subsequent operation to reread any outside changes.'''
2134 subsequent operation to reread any outside changes.'''
2134 # extension should hook this to invalidate its caches
2135 # extension should hook this to invalidate its caches
2135 self.invalidate()
2136 self.invalidate()
2136 self.invalidatedirstate()
2137 self.invalidatedirstate()
2137
2138
2138 @unfilteredmethod
2139 @unfilteredmethod
2139 def _refreshfilecachestats(self, tr):
2140 def _refreshfilecachestats(self, tr):
2140 """Reload stats of cached files so that they are flagged as valid"""
2141 """Reload stats of cached files so that they are flagged as valid"""
2141 for k, ce in self._filecache.items():
2142 for k, ce in self._filecache.items():
2142 k = pycompat.sysstr(k)
2143 k = pycompat.sysstr(k)
2143 if k == r'dirstate' or k not in self.__dict__:
2144 if k == r'dirstate' or k not in self.__dict__:
2144 continue
2145 continue
2145 ce.refresh()
2146 ce.refresh()
2146
2147
2147 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
2148 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
2148 inheritchecker=None, parentenvvar=None):
2149 inheritchecker=None, parentenvvar=None):
2149 parentlock = None
2150 parentlock = None
2150 # the contents of parentenvvar are used by the underlying lock to
2151 # the contents of parentenvvar are used by the underlying lock to
2151 # determine whether it can be inherited
2152 # determine whether it can be inherited
2152 if parentenvvar is not None:
2153 if parentenvvar is not None:
2153 parentlock = encoding.environ.get(parentenvvar)
2154 parentlock = encoding.environ.get(parentenvvar)
2154
2155
2155 timeout = 0
2156 timeout = 0
2156 warntimeout = 0
2157 warntimeout = 0
2157 if wait:
2158 if wait:
2158 timeout = self.ui.configint("ui", "timeout")
2159 timeout = self.ui.configint("ui", "timeout")
2159 warntimeout = self.ui.configint("ui", "timeout.warn")
2160 warntimeout = self.ui.configint("ui", "timeout.warn")
2160 # internal config: ui.signal-safe-lock
2161 # internal config: ui.signal-safe-lock
2161 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
2162 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
2162
2163
2163 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
2164 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
2164 releasefn=releasefn,
2165 releasefn=releasefn,
2165 acquirefn=acquirefn, desc=desc,
2166 acquirefn=acquirefn, desc=desc,
2166 inheritchecker=inheritchecker,
2167 inheritchecker=inheritchecker,
2167 parentlock=parentlock,
2168 parentlock=parentlock,
2168 signalsafe=signalsafe)
2169 signalsafe=signalsafe)
2169 return l
2170 return l
2170
2171
2171 def _afterlock(self, callback):
2172 def _afterlock(self, callback):
2172 """add a callback to be run when the repository is fully unlocked
2173 """add a callback to be run when the repository is fully unlocked
2173
2174
2174 The callback will be executed when the outermost lock is released
2175 The callback will be executed when the outermost lock is released
2175 (with wlock being higher level than 'lock')."""
2176 (with wlock being higher level than 'lock')."""
2176 for ref in (self._wlockref, self._lockref):
2177 for ref in (self._wlockref, self._lockref):
2177 l = ref and ref()
2178 l = ref and ref()
2178 if l and l.held:
2179 if l and l.held:
2179 l.postrelease.append(callback)
2180 l.postrelease.append(callback)
2180 break
2181 break
2181 else: # no lock have been found.
2182 else: # no lock have been found.
2182 callback()
2183 callback()
2183
2184
2184 def lock(self, wait=True):
2185 def lock(self, wait=True):
2185 '''Lock the repository store (.hg/store) and return a weak reference
2186 '''Lock the repository store (.hg/store) and return a weak reference
2186 to the lock. Use this before modifying the store (e.g. committing or
2187 to the lock. Use this before modifying the store (e.g. committing or
2187 stripping). If you are opening a transaction, get a lock as well.)
2188 stripping). If you are opening a transaction, get a lock as well.)
2188
2189
2189 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2190 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2190 'wlock' first to avoid a dead-lock hazard.'''
2191 'wlock' first to avoid a dead-lock hazard.'''
2191 l = self._currentlock(self._lockref)
2192 l = self._currentlock(self._lockref)
2192 if l is not None:
2193 if l is not None:
2193 l.lock()
2194 l.lock()
2194 return l
2195 return l
2195
2196
2196 l = self._lock(self.svfs, "lock", wait, None,
2197 l = self._lock(self.svfs, "lock", wait, None,
2197 self.invalidate, _('repository %s') % self.origroot)
2198 self.invalidate, _('repository %s') % self.origroot)
2198 self._lockref = weakref.ref(l)
2199 self._lockref = weakref.ref(l)
2199 return l
2200 return l
2200
2201
2201 def _wlockchecktransaction(self):
2202 def _wlockchecktransaction(self):
2202 if self.currenttransaction() is not None:
2203 if self.currenttransaction() is not None:
2203 raise error.LockInheritanceContractViolation(
2204 raise error.LockInheritanceContractViolation(
2204 'wlock cannot be inherited in the middle of a transaction')
2205 'wlock cannot be inherited in the middle of a transaction')
2205
2206
2206 def wlock(self, wait=True):
2207 def wlock(self, wait=True):
2207 '''Lock the non-store parts of the repository (everything under
2208 '''Lock the non-store parts of the repository (everything under
2208 .hg except .hg/store) and return a weak reference to the lock.
2209 .hg except .hg/store) and return a weak reference to the lock.
2209
2210
2210 Use this before modifying files in .hg.
2211 Use this before modifying files in .hg.
2211
2212
2212 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2213 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2213 'wlock' first to avoid a dead-lock hazard.'''
2214 'wlock' first to avoid a dead-lock hazard.'''
2214 l = self._wlockref and self._wlockref()
2215 l = self._wlockref and self._wlockref()
2215 if l is not None and l.held:
2216 if l is not None and l.held:
2216 l.lock()
2217 l.lock()
2217 return l
2218 return l
2218
2219
2219 # We do not need to check for non-waiting lock acquisition. Such
2220 # We do not need to check for non-waiting lock acquisition. Such
2220 # acquisition would not cause dead-lock as they would just fail.
2221 # acquisition would not cause dead-lock as they would just fail.
2221 if wait and (self.ui.configbool('devel', 'all-warnings')
2222 if wait and (self.ui.configbool('devel', 'all-warnings')
2222 or self.ui.configbool('devel', 'check-locks')):
2223 or self.ui.configbool('devel', 'check-locks')):
2223 if self._currentlock(self._lockref) is not None:
2224 if self._currentlock(self._lockref) is not None:
2224 self.ui.develwarn('"wlock" acquired after "lock"')
2225 self.ui.develwarn('"wlock" acquired after "lock"')
2225
2226
2226 def unlock():
2227 def unlock():
2227 if self.dirstate.pendingparentchange():
2228 if self.dirstate.pendingparentchange():
2228 self.dirstate.invalidate()
2229 self.dirstate.invalidate()
2229 else:
2230 else:
2230 self.dirstate.write(None)
2231 self.dirstate.write(None)
2231
2232
2232 self._filecache['dirstate'].refresh()
2233 self._filecache['dirstate'].refresh()
2233
2234
2234 l = self._lock(self.vfs, "wlock", wait, unlock,
2235 l = self._lock(self.vfs, "wlock", wait, unlock,
2235 self.invalidatedirstate, _('working directory of %s') %
2236 self.invalidatedirstate, _('working directory of %s') %
2236 self.origroot,
2237 self.origroot,
2237 inheritchecker=self._wlockchecktransaction,
2238 inheritchecker=self._wlockchecktransaction,
2238 parentenvvar='HG_WLOCK_LOCKER')
2239 parentenvvar='HG_WLOCK_LOCKER')
2239 self._wlockref = weakref.ref(l)
2240 self._wlockref = weakref.ref(l)
2240 return l
2241 return l
2241
2242
2242 def _currentlock(self, lockref):
2243 def _currentlock(self, lockref):
2243 """Returns the lock if it's held, or None if it's not."""
2244 """Returns the lock if it's held, or None if it's not."""
2244 if lockref is None:
2245 if lockref is None:
2245 return None
2246 return None
2246 l = lockref()
2247 l = lockref()
2247 if l is None or not l.held:
2248 if l is None or not l.held:
2248 return None
2249 return None
2249 return l
2250 return l
2250
2251
2251 def currentwlock(self):
2252 def currentwlock(self):
2252 """Returns the wlock if it's held, or None if it's not."""
2253 """Returns the wlock if it's held, or None if it's not."""
2253 return self._currentlock(self._wlockref)
2254 return self._currentlock(self._wlockref)
2254
2255
2255 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
2256 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
2256 """
2257 """
2257 commit an individual file as part of a larger transaction
2258 commit an individual file as part of a larger transaction
2258 """
2259 """
2259
2260
2260 fname = fctx.path()
2261 fname = fctx.path()
2261 fparent1 = manifest1.get(fname, nullid)
2262 fparent1 = manifest1.get(fname, nullid)
2262 fparent2 = manifest2.get(fname, nullid)
2263 fparent2 = manifest2.get(fname, nullid)
2263 if isinstance(fctx, context.filectx):
2264 if isinstance(fctx, context.filectx):
2264 node = fctx.filenode()
2265 node = fctx.filenode()
2265 if node in [fparent1, fparent2]:
2266 if node in [fparent1, fparent2]:
2266 self.ui.debug('reusing %s filelog entry\n' % fname)
2267 self.ui.debug('reusing %s filelog entry\n' % fname)
2267 if manifest1.flags(fname) != fctx.flags():
2268 if manifest1.flags(fname) != fctx.flags():
2268 changelist.append(fname)
2269 changelist.append(fname)
2269 return node
2270 return node
2270
2271
2271 flog = self.file(fname)
2272 flog = self.file(fname)
2272 meta = {}
2273 meta = {}
2273 copy = fctx.renamed()
2274 copy = fctx.renamed()
2274 if copy and copy[0] != fname:
2275 if copy and copy[0] != fname:
2275 # Mark the new revision of this file as a copy of another
2276 # Mark the new revision of this file as a copy of another
2276 # file. This copy data will effectively act as a parent
2277 # file. This copy data will effectively act as a parent
2277 # of this new revision. If this is a merge, the first
2278 # of this new revision. If this is a merge, the first
2278 # parent will be the nullid (meaning "look up the copy data")
2279 # parent will be the nullid (meaning "look up the copy data")
2279 # and the second one will be the other parent. For example:
2280 # and the second one will be the other parent. For example:
2280 #
2281 #
2281 # 0 --- 1 --- 3 rev1 changes file foo
2282 # 0 --- 1 --- 3 rev1 changes file foo
2282 # \ / rev2 renames foo to bar and changes it
2283 # \ / rev2 renames foo to bar and changes it
2283 # \- 2 -/ rev3 should have bar with all changes and
2284 # \- 2 -/ rev3 should have bar with all changes and
2284 # should record that bar descends from
2285 # should record that bar descends from
2285 # bar in rev2 and foo in rev1
2286 # bar in rev2 and foo in rev1
2286 #
2287 #
2287 # this allows this merge to succeed:
2288 # this allows this merge to succeed:
2288 #
2289 #
2289 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2290 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2290 # \ / merging rev3 and rev4 should use bar@rev2
2291 # \ / merging rev3 and rev4 should use bar@rev2
2291 # \- 2 --- 4 as the merge base
2292 # \- 2 --- 4 as the merge base
2292 #
2293 #
2293
2294
2294 cfname = copy[0]
2295 cfname = copy[0]
2295 crev = manifest1.get(cfname)
2296 crev = manifest1.get(cfname)
2296 newfparent = fparent2
2297 newfparent = fparent2
2297
2298
2298 if manifest2: # branch merge
2299 if manifest2: # branch merge
2299 if fparent2 == nullid or crev is None: # copied on remote side
2300 if fparent2 == nullid or crev is None: # copied on remote side
2300 if cfname in manifest2:
2301 if cfname in manifest2:
2301 crev = manifest2[cfname]
2302 crev = manifest2[cfname]
2302 newfparent = fparent1
2303 newfparent = fparent1
2303
2304
2304 # Here, we used to search backwards through history to try to find
2305 # Here, we used to search backwards through history to try to find
2305 # where the file copy came from if the source of a copy was not in
2306 # where the file copy came from if the source of a copy was not in
2306 # the parent directory. However, this doesn't actually make sense to
2307 # the parent directory. However, this doesn't actually make sense to
2307 # do (what does a copy from something not in your working copy even
2308 # do (what does a copy from something not in your working copy even
2308 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2309 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2309 # the user that copy information was dropped, so if they didn't
2310 # the user that copy information was dropped, so if they didn't
2310 # expect this outcome it can be fixed, but this is the correct
2311 # expect this outcome it can be fixed, but this is the correct
2311 # behavior in this circumstance.
2312 # behavior in this circumstance.
2312
2313
2313 if crev:
2314 if crev:
2314 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
2315 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
2315 meta["copy"] = cfname
2316 meta["copy"] = cfname
2316 meta["copyrev"] = hex(crev)
2317 meta["copyrev"] = hex(crev)
2317 fparent1, fparent2 = nullid, newfparent
2318 fparent1, fparent2 = nullid, newfparent
2318 else:
2319 else:
2319 self.ui.warn(_("warning: can't find ancestor for '%s' "
2320 self.ui.warn(_("warning: can't find ancestor for '%s' "
2320 "copied from '%s'!\n") % (fname, cfname))
2321 "copied from '%s'!\n") % (fname, cfname))
2321
2322
2322 elif fparent1 == nullid:
2323 elif fparent1 == nullid:
2323 fparent1, fparent2 = fparent2, nullid
2324 fparent1, fparent2 = fparent2, nullid
2324 elif fparent2 != nullid:
2325 elif fparent2 != nullid:
2325 # is one parent an ancestor of the other?
2326 # is one parent an ancestor of the other?
2326 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2327 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2327 if fparent1 in fparentancestors:
2328 if fparent1 in fparentancestors:
2328 fparent1, fparent2 = fparent2, nullid
2329 fparent1, fparent2 = fparent2, nullid
2329 elif fparent2 in fparentancestors:
2330 elif fparent2 in fparentancestors:
2330 fparent2 = nullid
2331 fparent2 = nullid
2331
2332
2332 # is the file changed?
2333 # is the file changed?
2333 text = fctx.data()
2334 text = fctx.data()
2334 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2335 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2335 changelist.append(fname)
2336 changelist.append(fname)
2336 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2337 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2337 # are just the flags changed during merge?
2338 # are just the flags changed during merge?
2338 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2339 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2339 changelist.append(fname)
2340 changelist.append(fname)
2340
2341
2341 return fparent1
2342 return fparent1
2342
2343
2343 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
2344 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
2344 """check for commit arguments that aren't committable"""
2345 """check for commit arguments that aren't committable"""
2345 if match.isexact() or match.prefix():
2346 if match.isexact() or match.prefix():
2346 matched = set(status.modified + status.added + status.removed)
2347 matched = set(status.modified + status.added + status.removed)
2347
2348
2348 for f in match.files():
2349 for f in match.files():
2349 f = self.dirstate.normalize(f)
2350 f = self.dirstate.normalize(f)
2350 if f == '.' or f in matched or f in wctx.substate:
2351 if f == '.' or f in matched or f in wctx.substate:
2351 continue
2352 continue
2352 if f in status.deleted:
2353 if f in status.deleted:
2353 fail(f, _('file not found!'))
2354 fail(f, _('file not found!'))
2354 if f in vdirs: # visited directory
2355 if f in vdirs: # visited directory
2355 d = f + '/'
2356 d = f + '/'
2356 for mf in matched:
2357 for mf in matched:
2357 if mf.startswith(d):
2358 if mf.startswith(d):
2358 break
2359 break
2359 else:
2360 else:
2360 fail(f, _("no match under directory!"))
2361 fail(f, _("no match under directory!"))
2361 elif f not in self.dirstate:
2362 elif f not in self.dirstate:
2362 fail(f, _("file not tracked!"))
2363 fail(f, _("file not tracked!"))
2363
2364
2364 @unfilteredmethod
2365 @unfilteredmethod
2365 def commit(self, text="", user=None, date=None, match=None, force=False,
2366 def commit(self, text="", user=None, date=None, match=None, force=False,
2366 editor=False, extra=None):
2367 editor=False, extra=None):
2367 """Add a new revision to current repository.
2368 """Add a new revision to current repository.
2368
2369
2369 Revision information is gathered from the working directory,
2370 Revision information is gathered from the working directory,
2370 match can be used to filter the committed files. If editor is
2371 match can be used to filter the committed files. If editor is
2371 supplied, it is called to get a commit message.
2372 supplied, it is called to get a commit message.
2372 """
2373 """
2373 if extra is None:
2374 if extra is None:
2374 extra = {}
2375 extra = {}
2375
2376
2376 def fail(f, msg):
2377 def fail(f, msg):
2377 raise error.Abort('%s: %s' % (f, msg))
2378 raise error.Abort('%s: %s' % (f, msg))
2378
2379
2379 if not match:
2380 if not match:
2380 match = matchmod.always(self.root, '')
2381 match = matchmod.always(self.root, '')
2381
2382
2382 if not force:
2383 if not force:
2383 vdirs = []
2384 vdirs = []
2384 match.explicitdir = vdirs.append
2385 match.explicitdir = vdirs.append
2385 match.bad = fail
2386 match.bad = fail
2386
2387
2387 wlock = lock = tr = None
2388 wlock = lock = tr = None
2388 try:
2389 try:
2389 wlock = self.wlock()
2390 wlock = self.wlock()
2390 lock = self.lock() # for recent changelog (see issue4368)
2391 lock = self.lock() # for recent changelog (see issue4368)
2391
2392
2392 wctx = self[None]
2393 wctx = self[None]
2393 merge = len(wctx.parents()) > 1
2394 merge = len(wctx.parents()) > 1
2394
2395
2395 if not force and merge and not match.always():
2396 if not force and merge and not match.always():
2396 raise error.Abort(_('cannot partially commit a merge '
2397 raise error.Abort(_('cannot partially commit a merge '
2397 '(do not specify files or patterns)'))
2398 '(do not specify files or patterns)'))
2398
2399
2399 status = self.status(match=match, clean=force)
2400 status = self.status(match=match, clean=force)
2400 if force:
2401 if force:
2401 status.modified.extend(status.clean) # mq may commit clean files
2402 status.modified.extend(status.clean) # mq may commit clean files
2402
2403
2403 # check subrepos
2404 # check subrepos
2404 subs, commitsubs, newstate = subrepoutil.precommit(
2405 subs, commitsubs, newstate = subrepoutil.precommit(
2405 self.ui, wctx, status, match, force=force)
2406 self.ui, wctx, status, match, force=force)
2406
2407
2407 # make sure all explicit patterns are matched
2408 # make sure all explicit patterns are matched
2408 if not force:
2409 if not force:
2409 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
2410 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
2410
2411
2411 cctx = context.workingcommitctx(self, status,
2412 cctx = context.workingcommitctx(self, status,
2412 text, user, date, extra)
2413 text, user, date, extra)
2413
2414
2414 # internal config: ui.allowemptycommit
2415 # internal config: ui.allowemptycommit
2415 allowemptycommit = (wctx.branch() != wctx.p1().branch()
2416 allowemptycommit = (wctx.branch() != wctx.p1().branch()
2416 or extra.get('close') or merge or cctx.files()
2417 or extra.get('close') or merge or cctx.files()
2417 or self.ui.configbool('ui', 'allowemptycommit'))
2418 or self.ui.configbool('ui', 'allowemptycommit'))
2418 if not allowemptycommit:
2419 if not allowemptycommit:
2419 return None
2420 return None
2420
2421
2421 if merge and cctx.deleted():
2422 if merge and cctx.deleted():
2422 raise error.Abort(_("cannot commit merge with missing files"))
2423 raise error.Abort(_("cannot commit merge with missing files"))
2423
2424
2424 ms = mergemod.mergestate.read(self)
2425 ms = mergemod.mergestate.read(self)
2425 mergeutil.checkunresolved(ms)
2426 mergeutil.checkunresolved(ms)
2426
2427
2427 if editor:
2428 if editor:
2428 cctx._text = editor(self, cctx, subs)
2429 cctx._text = editor(self, cctx, subs)
2429 edited = (text != cctx._text)
2430 edited = (text != cctx._text)
2430
2431
2431 # Save commit message in case this transaction gets rolled back
2432 # Save commit message in case this transaction gets rolled back
2432 # (e.g. by a pretxncommit hook). Leave the content alone on
2433 # (e.g. by a pretxncommit hook). Leave the content alone on
2433 # the assumption that the user will use the same editor again.
2434 # the assumption that the user will use the same editor again.
2434 msgfn = self.savecommitmessage(cctx._text)
2435 msgfn = self.savecommitmessage(cctx._text)
2435
2436
2436 # commit subs and write new state
2437 # commit subs and write new state
2437 if subs:
2438 if subs:
2438 for s in sorted(commitsubs):
2439 for s in sorted(commitsubs):
2439 sub = wctx.sub(s)
2440 sub = wctx.sub(s)
2440 self.ui.status(_('committing subrepository %s\n') %
2441 self.ui.status(_('committing subrepository %s\n') %
2441 subrepoutil.subrelpath(sub))
2442 subrepoutil.subrelpath(sub))
2442 sr = sub.commit(cctx._text, user, date)
2443 sr = sub.commit(cctx._text, user, date)
2443 newstate[s] = (newstate[s][0], sr)
2444 newstate[s] = (newstate[s][0], sr)
2444 subrepoutil.writestate(self, newstate)
2445 subrepoutil.writestate(self, newstate)
2445
2446
2446 p1, p2 = self.dirstate.parents()
2447 p1, p2 = self.dirstate.parents()
2447 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
2448 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
2448 try:
2449 try:
2449 self.hook("precommit", throw=True, parent1=hookp1,
2450 self.hook("precommit", throw=True, parent1=hookp1,
2450 parent2=hookp2)
2451 parent2=hookp2)
2451 tr = self.transaction('commit')
2452 tr = self.transaction('commit')
2452 ret = self.commitctx(cctx, True)
2453 ret = self.commitctx(cctx, True)
2453 except: # re-raises
2454 except: # re-raises
2454 if edited:
2455 if edited:
2455 self.ui.write(
2456 self.ui.write(
2456 _('note: commit message saved in %s\n') % msgfn)
2457 _('note: commit message saved in %s\n') % msgfn)
2457 raise
2458 raise
2458 # update bookmarks, dirstate and mergestate
2459 # update bookmarks, dirstate and mergestate
2459 bookmarks.update(self, [p1, p2], ret)
2460 bookmarks.update(self, [p1, p2], ret)
2460 cctx.markcommitted(ret)
2461 cctx.markcommitted(ret)
2461 ms.reset()
2462 ms.reset()
2462 tr.close()
2463 tr.close()
2463
2464
2464 finally:
2465 finally:
2465 lockmod.release(tr, lock, wlock)
2466 lockmod.release(tr, lock, wlock)
2466
2467
2467 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2468 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2468 # hack for command that use a temporary commit (eg: histedit)
2469 # hack for command that use a temporary commit (eg: histedit)
2469 # temporary commit got stripped before hook release
2470 # temporary commit got stripped before hook release
2470 if self.changelog.hasnode(ret):
2471 if self.changelog.hasnode(ret):
2471 self.hook("commit", node=node, parent1=parent1,
2472 self.hook("commit", node=node, parent1=parent1,
2472 parent2=parent2)
2473 parent2=parent2)
2473 self._afterlock(commithook)
2474 self._afterlock(commithook)
2474 return ret
2475 return ret
2475
2476
2476 @unfilteredmethod
2477 @unfilteredmethod
2477 def commitctx(self, ctx, error=False):
2478 def commitctx(self, ctx, error=False):
2478 """Add a new revision to current repository.
2479 """Add a new revision to current repository.
2479 Revision information is passed via the context argument.
2480 Revision information is passed via the context argument.
2480
2481
2481 ctx.files() should list all files involved in this commit, i.e.
2482 ctx.files() should list all files involved in this commit, i.e.
2482 modified/added/removed files. On merge, it may be wider than the
2483 modified/added/removed files. On merge, it may be wider than the
2483 ctx.files() to be committed, since any file nodes derived directly
2484 ctx.files() to be committed, since any file nodes derived directly
2484 from p1 or p2 are excluded from the committed ctx.files().
2485 from p1 or p2 are excluded from the committed ctx.files().
2485 """
2486 """
2486
2487
2487 tr = None
2488 tr = None
2488 p1, p2 = ctx.p1(), ctx.p2()
2489 p1, p2 = ctx.p1(), ctx.p2()
2489 user = ctx.user()
2490 user = ctx.user()
2490
2491
2491 lock = self.lock()
2492 lock = self.lock()
2492 try:
2493 try:
2493 tr = self.transaction("commit")
2494 tr = self.transaction("commit")
2494 trp = weakref.proxy(tr)
2495 trp = weakref.proxy(tr)
2495
2496
2496 if ctx.manifestnode():
2497 if ctx.manifestnode():
2497 # reuse an existing manifest revision
2498 # reuse an existing manifest revision
2498 self.ui.debug('reusing known manifest\n')
2499 self.ui.debug('reusing known manifest\n')
2499 mn = ctx.manifestnode()
2500 mn = ctx.manifestnode()
2500 files = ctx.files()
2501 files = ctx.files()
2501 elif ctx.files():
2502 elif ctx.files():
2502 m1ctx = p1.manifestctx()
2503 m1ctx = p1.manifestctx()
2503 m2ctx = p2.manifestctx()
2504 m2ctx = p2.manifestctx()
2504 mctx = m1ctx.copy()
2505 mctx = m1ctx.copy()
2505
2506
2506 m = mctx.read()
2507 m = mctx.read()
2507 m1 = m1ctx.read()
2508 m1 = m1ctx.read()
2508 m2 = m2ctx.read()
2509 m2 = m2ctx.read()
2509
2510
2510 # check in files
2511 # check in files
2511 added = []
2512 added = []
2512 changed = []
2513 changed = []
2513 removed = list(ctx.removed())
2514 removed = list(ctx.removed())
2514 linkrev = len(self)
2515 linkrev = len(self)
2515 self.ui.note(_("committing files:\n"))
2516 self.ui.note(_("committing files:\n"))
2516 for f in sorted(ctx.modified() + ctx.added()):
2517 for f in sorted(ctx.modified() + ctx.added()):
2517 self.ui.note(f + "\n")
2518 self.ui.note(f + "\n")
2518 try:
2519 try:
2519 fctx = ctx[f]
2520 fctx = ctx[f]
2520 if fctx is None:
2521 if fctx is None:
2521 removed.append(f)
2522 removed.append(f)
2522 else:
2523 else:
2523 added.append(f)
2524 added.append(f)
2524 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2525 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2525 trp, changed)
2526 trp, changed)
2526 m.setflag(f, fctx.flags())
2527 m.setflag(f, fctx.flags())
2527 except OSError as inst:
2528 except OSError as inst:
2528 self.ui.warn(_("trouble committing %s!\n") % f)
2529 self.ui.warn(_("trouble committing %s!\n") % f)
2529 raise
2530 raise
2530 except IOError as inst:
2531 except IOError as inst:
2531 errcode = getattr(inst, 'errno', errno.ENOENT)
2532 errcode = getattr(inst, 'errno', errno.ENOENT)
2532 if error or errcode and errcode != errno.ENOENT:
2533 if error or errcode and errcode != errno.ENOENT:
2533 self.ui.warn(_("trouble committing %s!\n") % f)
2534 self.ui.warn(_("trouble committing %s!\n") % f)
2534 raise
2535 raise
2535
2536
2536 # update manifest
2537 # update manifest
2537 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2538 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2538 drop = [f for f in removed if f in m]
2539 drop = [f for f in removed if f in m]
2539 for f in drop:
2540 for f in drop:
2540 del m[f]
2541 del m[f]
2541 files = changed + removed
2542 files = changed + removed
2542 md = None
2543 md = None
2543 if not files:
2544 if not files:
2544 # if no "files" actually changed in terms of the changelog,
2545 # if no "files" actually changed in terms of the changelog,
2545 # try hard to detect unmodified manifest entry so that the
2546 # try hard to detect unmodified manifest entry so that the
2546 # exact same commit can be reproduced later on convert.
2547 # exact same commit can be reproduced later on convert.
2547 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
2548 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
2548 if not files and md:
2549 if not files and md:
2549 self.ui.debug('not reusing manifest (no file change in '
2550 self.ui.debug('not reusing manifest (no file change in '
2550 'changelog, but manifest differs)\n')
2551 'changelog, but manifest differs)\n')
2551 if files or md:
2552 if files or md:
2552 self.ui.note(_("committing manifest\n"))
2553 self.ui.note(_("committing manifest\n"))
2553 # we're using narrowmatch here since it's already applied at
2554 # we're using narrowmatch here since it's already applied at
2554 # other stages (such as dirstate.walk), so we're already
2555 # other stages (such as dirstate.walk), so we're already
2555 # ignoring things outside of narrowspec in most cases. The
2556 # ignoring things outside of narrowspec in most cases. The
2556 # one case where we might have files outside the narrowspec
2557 # one case where we might have files outside the narrowspec
2557 # at this point is merges, and we already error out in the
2558 # at this point is merges, and we already error out in the
2558 # case where the merge has files outside of the narrowspec,
2559 # case where the merge has files outside of the narrowspec,
2559 # so this is safe.
2560 # so this is safe.
2560 mn = mctx.write(trp, linkrev,
2561 mn = mctx.write(trp, linkrev,
2561 p1.manifestnode(), p2.manifestnode(),
2562 p1.manifestnode(), p2.manifestnode(),
2562 added, drop, match=self.narrowmatch())
2563 added, drop, match=self.narrowmatch())
2563 else:
2564 else:
2564 self.ui.debug('reusing manifest form p1 (listed files '
2565 self.ui.debug('reusing manifest form p1 (listed files '
2565 'actually unchanged)\n')
2566 'actually unchanged)\n')
2566 mn = p1.manifestnode()
2567 mn = p1.manifestnode()
2567 else:
2568 else:
2568 self.ui.debug('reusing manifest from p1 (no file change)\n')
2569 self.ui.debug('reusing manifest from p1 (no file change)\n')
2569 mn = p1.manifestnode()
2570 mn = p1.manifestnode()
2570 files = []
2571 files = []
2571
2572
2572 # update changelog
2573 # update changelog
2573 self.ui.note(_("committing changelog\n"))
2574 self.ui.note(_("committing changelog\n"))
2574 self.changelog.delayupdate(tr)
2575 self.changelog.delayupdate(tr)
2575 n = self.changelog.add(mn, files, ctx.description(),
2576 n = self.changelog.add(mn, files, ctx.description(),
2576 trp, p1.node(), p2.node(),
2577 trp, p1.node(), p2.node(),
2577 user, ctx.date(), ctx.extra().copy())
2578 user, ctx.date(), ctx.extra().copy())
2578 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2579 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2579 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2580 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2580 parent2=xp2)
2581 parent2=xp2)
2581 # set the new commit is proper phase
2582 # set the new commit is proper phase
2582 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2583 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2583 if targetphase:
2584 if targetphase:
2584 # retract boundary do not alter parent changeset.
2585 # retract boundary do not alter parent changeset.
2585 # if a parent have higher the resulting phase will
2586 # if a parent have higher the resulting phase will
2586 # be compliant anyway
2587 # be compliant anyway
2587 #
2588 #
2588 # if minimal phase was 0 we don't need to retract anything
2589 # if minimal phase was 0 we don't need to retract anything
2589 phases.registernew(self, tr, targetphase, [n])
2590 phases.registernew(self, tr, targetphase, [n])
2590 tr.close()
2591 tr.close()
2591 return n
2592 return n
2592 finally:
2593 finally:
2593 if tr:
2594 if tr:
2594 tr.release()
2595 tr.release()
2595 lock.release()
2596 lock.release()
2596
2597
2597 @unfilteredmethod
2598 @unfilteredmethod
2598 def destroying(self):
2599 def destroying(self):
2599 '''Inform the repository that nodes are about to be destroyed.
2600 '''Inform the repository that nodes are about to be destroyed.
2600 Intended for use by strip and rollback, so there's a common
2601 Intended for use by strip and rollback, so there's a common
2601 place for anything that has to be done before destroying history.
2602 place for anything that has to be done before destroying history.
2602
2603
2603 This is mostly useful for saving state that is in memory and waiting
2604 This is mostly useful for saving state that is in memory and waiting
2604 to be flushed when the current lock is released. Because a call to
2605 to be flushed when the current lock is released. Because a call to
2605 destroyed is imminent, the repo will be invalidated causing those
2606 destroyed is imminent, the repo will be invalidated causing those
2606 changes to stay in memory (waiting for the next unlock), or vanish
2607 changes to stay in memory (waiting for the next unlock), or vanish
2607 completely.
2608 completely.
2608 '''
2609 '''
2609 # When using the same lock to commit and strip, the phasecache is left
2610 # When using the same lock to commit and strip, the phasecache is left
2610 # dirty after committing. Then when we strip, the repo is invalidated,
2611 # dirty after committing. Then when we strip, the repo is invalidated,
2611 # causing those changes to disappear.
2612 # causing those changes to disappear.
2612 if '_phasecache' in vars(self):
2613 if '_phasecache' in vars(self):
2613 self._phasecache.write()
2614 self._phasecache.write()
2614
2615
2615 @unfilteredmethod
2616 @unfilteredmethod
2616 def destroyed(self):
2617 def destroyed(self):
2617 '''Inform the repository that nodes have been destroyed.
2618 '''Inform the repository that nodes have been destroyed.
2618 Intended for use by strip and rollback, so there's a common
2619 Intended for use by strip and rollback, so there's a common
2619 place for anything that has to be done after destroying history.
2620 place for anything that has to be done after destroying history.
2620 '''
2621 '''
2621 # When one tries to:
2622 # When one tries to:
2622 # 1) destroy nodes thus calling this method (e.g. strip)
2623 # 1) destroy nodes thus calling this method (e.g. strip)
2623 # 2) use phasecache somewhere (e.g. commit)
2624 # 2) use phasecache somewhere (e.g. commit)
2624 #
2625 #
2625 # then 2) will fail because the phasecache contains nodes that were
2626 # then 2) will fail because the phasecache contains nodes that were
2626 # removed. We can either remove phasecache from the filecache,
2627 # removed. We can either remove phasecache from the filecache,
2627 # causing it to reload next time it is accessed, or simply filter
2628 # causing it to reload next time it is accessed, or simply filter
2628 # the removed nodes now and write the updated cache.
2629 # the removed nodes now and write the updated cache.
2629 self._phasecache.filterunknown(self)
2630 self._phasecache.filterunknown(self)
2630 self._phasecache.write()
2631 self._phasecache.write()
2631
2632
2632 # refresh all repository caches
2633 # refresh all repository caches
2633 self.updatecaches()
2634 self.updatecaches()
2634
2635
2635 # Ensure the persistent tag cache is updated. Doing it now
2636 # Ensure the persistent tag cache is updated. Doing it now
2636 # means that the tag cache only has to worry about destroyed
2637 # means that the tag cache only has to worry about destroyed
2637 # heads immediately after a strip/rollback. That in turn
2638 # heads immediately after a strip/rollback. That in turn
2638 # guarantees that "cachetip == currenttip" (comparing both rev
2639 # guarantees that "cachetip == currenttip" (comparing both rev
2639 # and node) always means no nodes have been added or destroyed.
2640 # and node) always means no nodes have been added or destroyed.
2640
2641
2641 # XXX this is suboptimal when qrefresh'ing: we strip the current
2642 # XXX this is suboptimal when qrefresh'ing: we strip the current
2642 # head, refresh the tag cache, then immediately add a new head.
2643 # head, refresh the tag cache, then immediately add a new head.
2643 # But I think doing it this way is necessary for the "instant
2644 # But I think doing it this way is necessary for the "instant
2644 # tag cache retrieval" case to work.
2645 # tag cache retrieval" case to work.
2645 self.invalidate()
2646 self.invalidate()
2646
2647
2647 def status(self, node1='.', node2=None, match=None,
2648 def status(self, node1='.', node2=None, match=None,
2648 ignored=False, clean=False, unknown=False,
2649 ignored=False, clean=False, unknown=False,
2649 listsubrepos=False):
2650 listsubrepos=False):
2650 '''a convenience method that calls node1.status(node2)'''
2651 '''a convenience method that calls node1.status(node2)'''
2651 return self[node1].status(node2, match, ignored, clean, unknown,
2652 return self[node1].status(node2, match, ignored, clean, unknown,
2652 listsubrepos)
2653 listsubrepos)
2653
2654
2654 def addpostdsstatus(self, ps):
2655 def addpostdsstatus(self, ps):
2655 """Add a callback to run within the wlock, at the point at which status
2656 """Add a callback to run within the wlock, at the point at which status
2656 fixups happen.
2657 fixups happen.
2657
2658
2658 On status completion, callback(wctx, status) will be called with the
2659 On status completion, callback(wctx, status) will be called with the
2659 wlock held, unless the dirstate has changed from underneath or the wlock
2660 wlock held, unless the dirstate has changed from underneath or the wlock
2660 couldn't be grabbed.
2661 couldn't be grabbed.
2661
2662
2662 Callbacks should not capture and use a cached copy of the dirstate --
2663 Callbacks should not capture and use a cached copy of the dirstate --
2663 it might change in the meanwhile. Instead, they should access the
2664 it might change in the meanwhile. Instead, they should access the
2664 dirstate via wctx.repo().dirstate.
2665 dirstate via wctx.repo().dirstate.
2665
2666
2666 This list is emptied out after each status run -- extensions should
2667 This list is emptied out after each status run -- extensions should
2667 make sure it adds to this list each time dirstate.status is called.
2668 make sure it adds to this list each time dirstate.status is called.
2668 Extensions should also make sure they don't call this for statuses
2669 Extensions should also make sure they don't call this for statuses
2669 that don't involve the dirstate.
2670 that don't involve the dirstate.
2670 """
2671 """
2671
2672
2672 # The list is located here for uniqueness reasons -- it is actually
2673 # The list is located here for uniqueness reasons -- it is actually
2673 # managed by the workingctx, but that isn't unique per-repo.
2674 # managed by the workingctx, but that isn't unique per-repo.
2674 self._postdsstatus.append(ps)
2675 self._postdsstatus.append(ps)
2675
2676
2676 def postdsstatus(self):
2677 def postdsstatus(self):
2677 """Used by workingctx to get the list of post-dirstate-status hooks."""
2678 """Used by workingctx to get the list of post-dirstate-status hooks."""
2678 return self._postdsstatus
2679 return self._postdsstatus
2679
2680
2680 def clearpostdsstatus(self):
2681 def clearpostdsstatus(self):
2681 """Used by workingctx to clear post-dirstate-status hooks."""
2682 """Used by workingctx to clear post-dirstate-status hooks."""
2682 del self._postdsstatus[:]
2683 del self._postdsstatus[:]
2683
2684
2684 def heads(self, start=None):
2685 def heads(self, start=None):
2685 if start is None:
2686 if start is None:
2686 cl = self.changelog
2687 cl = self.changelog
2687 headrevs = reversed(cl.headrevs())
2688 headrevs = reversed(cl.headrevs())
2688 return [cl.node(rev) for rev in headrevs]
2689 return [cl.node(rev) for rev in headrevs]
2689
2690
2690 heads = self.changelog.heads(start)
2691 heads = self.changelog.heads(start)
2691 # sort the output in rev descending order
2692 # sort the output in rev descending order
2692 return sorted(heads, key=self.changelog.rev, reverse=True)
2693 return sorted(heads, key=self.changelog.rev, reverse=True)
2693
2694
2694 def branchheads(self, branch=None, start=None, closed=False):
2695 def branchheads(self, branch=None, start=None, closed=False):
2695 '''return a (possibly filtered) list of heads for the given branch
2696 '''return a (possibly filtered) list of heads for the given branch
2696
2697
2697 Heads are returned in topological order, from newest to oldest.
2698 Heads are returned in topological order, from newest to oldest.
2698 If branch is None, use the dirstate branch.
2699 If branch is None, use the dirstate branch.
2699 If start is not None, return only heads reachable from start.
2700 If start is not None, return only heads reachable from start.
2700 If closed is True, return heads that are marked as closed as well.
2701 If closed is True, return heads that are marked as closed as well.
2701 '''
2702 '''
2702 if branch is None:
2703 if branch is None:
2703 branch = self[None].branch()
2704 branch = self[None].branch()
2704 branches = self.branchmap()
2705 branches = self.branchmap()
2705 if branch not in branches:
2706 if branch not in branches:
2706 return []
2707 return []
2707 # the cache returns heads ordered lowest to highest
2708 # the cache returns heads ordered lowest to highest
2708 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2709 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2709 if start is not None:
2710 if start is not None:
2710 # filter out the heads that cannot be reached from startrev
2711 # filter out the heads that cannot be reached from startrev
2711 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2712 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2712 bheads = [h for h in bheads if h in fbheads]
2713 bheads = [h for h in bheads if h in fbheads]
2713 return bheads
2714 return bheads
2714
2715
2715 def branches(self, nodes):
2716 def branches(self, nodes):
2716 if not nodes:
2717 if not nodes:
2717 nodes = [self.changelog.tip()]
2718 nodes = [self.changelog.tip()]
2718 b = []
2719 b = []
2719 for n in nodes:
2720 for n in nodes:
2720 t = n
2721 t = n
2721 while True:
2722 while True:
2722 p = self.changelog.parents(n)
2723 p = self.changelog.parents(n)
2723 if p[1] != nullid or p[0] == nullid:
2724 if p[1] != nullid or p[0] == nullid:
2724 b.append((t, n, p[0], p[1]))
2725 b.append((t, n, p[0], p[1]))
2725 break
2726 break
2726 n = p[0]
2727 n = p[0]
2727 return b
2728 return b
2728
2729
2729 def between(self, pairs):
2730 def between(self, pairs):
2730 r = []
2731 r = []
2731
2732
2732 for top, bottom in pairs:
2733 for top, bottom in pairs:
2733 n, l, i = top, [], 0
2734 n, l, i = top, [], 0
2734 f = 1
2735 f = 1
2735
2736
2736 while n != bottom and n != nullid:
2737 while n != bottom and n != nullid:
2737 p = self.changelog.parents(n)[0]
2738 p = self.changelog.parents(n)[0]
2738 if i == f:
2739 if i == f:
2739 l.append(n)
2740 l.append(n)
2740 f = f * 2
2741 f = f * 2
2741 n = p
2742 n = p
2742 i += 1
2743 i += 1
2743
2744
2744 r.append(l)
2745 r.append(l)
2745
2746
2746 return r
2747 return r
2747
2748
2748 def checkpush(self, pushop):
2749 def checkpush(self, pushop):
2749 """Extensions can override this function if additional checks have
2750 """Extensions can override this function if additional checks have
2750 to be performed before pushing, or call it if they override push
2751 to be performed before pushing, or call it if they override push
2751 command.
2752 command.
2752 """
2753 """
2753
2754
2754 @unfilteredpropertycache
2755 @unfilteredpropertycache
2755 def prepushoutgoinghooks(self):
2756 def prepushoutgoinghooks(self):
2756 """Return util.hooks consists of a pushop with repo, remote, outgoing
2757 """Return util.hooks consists of a pushop with repo, remote, outgoing
2757 methods, which are called before pushing changesets.
2758 methods, which are called before pushing changesets.
2758 """
2759 """
2759 return util.hooks()
2760 return util.hooks()
2760
2761
2761 def pushkey(self, namespace, key, old, new):
2762 def pushkey(self, namespace, key, old, new):
2762 try:
2763 try:
2763 tr = self.currenttransaction()
2764 tr = self.currenttransaction()
2764 hookargs = {}
2765 hookargs = {}
2765 if tr is not None:
2766 if tr is not None:
2766 hookargs.update(tr.hookargs)
2767 hookargs.update(tr.hookargs)
2767 hookargs = pycompat.strkwargs(hookargs)
2768 hookargs = pycompat.strkwargs(hookargs)
2768 hookargs[r'namespace'] = namespace
2769 hookargs[r'namespace'] = namespace
2769 hookargs[r'key'] = key
2770 hookargs[r'key'] = key
2770 hookargs[r'old'] = old
2771 hookargs[r'old'] = old
2771 hookargs[r'new'] = new
2772 hookargs[r'new'] = new
2772 self.hook('prepushkey', throw=True, **hookargs)
2773 self.hook('prepushkey', throw=True, **hookargs)
2773 except error.HookAbort as exc:
2774 except error.HookAbort as exc:
2774 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2775 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2775 if exc.hint:
2776 if exc.hint:
2776 self.ui.write_err(_("(%s)\n") % exc.hint)
2777 self.ui.write_err(_("(%s)\n") % exc.hint)
2777 return False
2778 return False
2778 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2779 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2779 ret = pushkey.push(self, namespace, key, old, new)
2780 ret = pushkey.push(self, namespace, key, old, new)
2780 def runhook():
2781 def runhook():
2781 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2782 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2782 ret=ret)
2783 ret=ret)
2783 self._afterlock(runhook)
2784 self._afterlock(runhook)
2784 return ret
2785 return ret
2785
2786
2786 def listkeys(self, namespace):
2787 def listkeys(self, namespace):
2787 self.hook('prelistkeys', throw=True, namespace=namespace)
2788 self.hook('prelistkeys', throw=True, namespace=namespace)
2788 self.ui.debug('listing keys for "%s"\n' % namespace)
2789 self.ui.debug('listing keys for "%s"\n' % namespace)
2789 values = pushkey.list(self, namespace)
2790 values = pushkey.list(self, namespace)
2790 self.hook('listkeys', namespace=namespace, values=values)
2791 self.hook('listkeys', namespace=namespace, values=values)
2791 return values
2792 return values
2792
2793
2793 def debugwireargs(self, one, two, three=None, four=None, five=None):
2794 def debugwireargs(self, one, two, three=None, four=None, five=None):
2794 '''used to test argument passing over the wire'''
2795 '''used to test argument passing over the wire'''
2795 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2796 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2796 pycompat.bytestr(four),
2797 pycompat.bytestr(four),
2797 pycompat.bytestr(five))
2798 pycompat.bytestr(five))
2798
2799
2799 def savecommitmessage(self, text):
2800 def savecommitmessage(self, text):
2800 fp = self.vfs('last-message.txt', 'wb')
2801 fp = self.vfs('last-message.txt', 'wb')
2801 try:
2802 try:
2802 fp.write(text)
2803 fp.write(text)
2803 finally:
2804 finally:
2804 fp.close()
2805 fp.close()
2805 return self.pathto(fp.name[len(self.root) + 1:])
2806 return self.pathto(fp.name[len(self.root) + 1:])
2806
2807
2807 # used to avoid circular references so destructors work
2808 # used to avoid circular references so destructors work
2808 def aftertrans(files):
2809 def aftertrans(files):
2809 renamefiles = [tuple(t) for t in files]
2810 renamefiles = [tuple(t) for t in files]
2810 def a():
2811 def a():
2811 for vfs, src, dest in renamefiles:
2812 for vfs, src, dest in renamefiles:
2812 # if src and dest refer to a same file, vfs.rename is a no-op,
2813 # if src and dest refer to a same file, vfs.rename is a no-op,
2813 # leaving both src and dest on disk. delete dest to make sure
2814 # leaving both src and dest on disk. delete dest to make sure
2814 # the rename couldn't be such a no-op.
2815 # the rename couldn't be such a no-op.
2815 vfs.tryunlink(dest)
2816 vfs.tryunlink(dest)
2816 try:
2817 try:
2817 vfs.rename(src, dest)
2818 vfs.rename(src, dest)
2818 except OSError: # journal file does not yet exist
2819 except OSError: # journal file does not yet exist
2819 pass
2820 pass
2820 return a
2821 return a
2821
2822
2822 def undoname(fn):
2823 def undoname(fn):
2823 base, name = os.path.split(fn)
2824 base, name = os.path.split(fn)
2824 assert name.startswith('journal')
2825 assert name.startswith('journal')
2825 return os.path.join(base, name.replace('journal', 'undo', 1))
2826 return os.path.join(base, name.replace('journal', 'undo', 1))
2826
2827
2827 def instance(ui, path, create, intents=None, createopts=None):
2828 def instance(ui, path, create, intents=None, createopts=None):
2828 localpath = util.urllocalpath(path)
2829 localpath = util.urllocalpath(path)
2829 if create:
2830 if create:
2830 createrepository(ui, localpath, createopts=createopts)
2831 createrepository(ui, localpath, createopts=createopts)
2831
2832
2832 return makelocalrepository(ui, localpath, intents=intents)
2833 return makelocalrepository(ui, localpath, intents=intents)
2833
2834
2834 def islocal(path):
2835 def islocal(path):
2835 return True
2836 return True
2836
2837
2837 def defaultcreateopts(ui, createopts=None):
2838 def defaultcreateopts(ui, createopts=None):
2838 """Populate the default creation options for a repository.
2839 """Populate the default creation options for a repository.
2839
2840
2840 A dictionary of explicitly requested creation options can be passed
2841 A dictionary of explicitly requested creation options can be passed
2841 in. Missing keys will be populated.
2842 in. Missing keys will be populated.
2842 """
2843 """
2843 createopts = dict(createopts or {})
2844 createopts = dict(createopts or {})
2844
2845
2845 if 'backend' not in createopts:
2846 if 'backend' not in createopts:
2846 # experimental config: storage.new-repo-backend
2847 # experimental config: storage.new-repo-backend
2847 createopts['backend'] = ui.config('storage', 'new-repo-backend')
2848 createopts['backend'] = ui.config('storage', 'new-repo-backend')
2848
2849
2849 return createopts
2850 return createopts
2850
2851
2851 def newreporequirements(ui, createopts):
2852 def newreporequirements(ui, createopts):
2852 """Determine the set of requirements for a new local repository.
2853 """Determine the set of requirements for a new local repository.
2853
2854
2854 Extensions can wrap this function to specify custom requirements for
2855 Extensions can wrap this function to specify custom requirements for
2855 new repositories.
2856 new repositories.
2856 """
2857 """
2857 # If the repo is being created from a shared repository, we copy
2858 # If the repo is being created from a shared repository, we copy
2858 # its requirements.
2859 # its requirements.
2859 if 'sharedrepo' in createopts:
2860 if 'sharedrepo' in createopts:
2860 requirements = set(createopts['sharedrepo'].requirements)
2861 requirements = set(createopts['sharedrepo'].requirements)
2861 if createopts.get('sharedrelative'):
2862 if createopts.get('sharedrelative'):
2862 requirements.add('relshared')
2863 requirements.add('relshared')
2863 else:
2864 else:
2864 requirements.add('shared')
2865 requirements.add('shared')
2865
2866
2866 return requirements
2867 return requirements
2867
2868
2868 if 'backend' not in createopts:
2869 if 'backend' not in createopts:
2869 raise error.ProgrammingError('backend key not present in createopts; '
2870 raise error.ProgrammingError('backend key not present in createopts; '
2870 'was defaultcreateopts() called?')
2871 'was defaultcreateopts() called?')
2871
2872
2872 if createopts['backend'] != 'revlogv1':
2873 if createopts['backend'] != 'revlogv1':
2873 raise error.Abort(_('unable to determine repository requirements for '
2874 raise error.Abort(_('unable to determine repository requirements for '
2874 'storage backend: %s') % createopts['backend'])
2875 'storage backend: %s') % createopts['backend'])
2875
2876
2876 requirements = {'revlogv1'}
2877 requirements = {'revlogv1'}
2877 if ui.configbool('format', 'usestore'):
2878 if ui.configbool('format', 'usestore'):
2878 requirements.add('store')
2879 requirements.add('store')
2879 if ui.configbool('format', 'usefncache'):
2880 if ui.configbool('format', 'usefncache'):
2880 requirements.add('fncache')
2881 requirements.add('fncache')
2881 if ui.configbool('format', 'dotencode'):
2882 if ui.configbool('format', 'dotencode'):
2882 requirements.add('dotencode')
2883 requirements.add('dotencode')
2883
2884
2884 compengine = ui.config('experimental', 'format.compression')
2885 compengine = ui.config('experimental', 'format.compression')
2885 if compengine not in util.compengines:
2886 if compengine not in util.compengines:
2886 raise error.Abort(_('compression engine %s defined by '
2887 raise error.Abort(_('compression engine %s defined by '
2887 'experimental.format.compression not available') %
2888 'experimental.format.compression not available') %
2888 compengine,
2889 compengine,
2889 hint=_('run "hg debuginstall" to list available '
2890 hint=_('run "hg debuginstall" to list available '
2890 'compression engines'))
2891 'compression engines'))
2891
2892
2892 # zlib is the historical default and doesn't need an explicit requirement.
2893 # zlib is the historical default and doesn't need an explicit requirement.
2893 if compengine != 'zlib':
2894 if compengine != 'zlib':
2894 requirements.add('exp-compression-%s' % compengine)
2895 requirements.add('exp-compression-%s' % compengine)
2895
2896
2896 if scmutil.gdinitconfig(ui):
2897 if scmutil.gdinitconfig(ui):
2897 requirements.add('generaldelta')
2898 requirements.add('generaldelta')
2898 if ui.configbool('experimental', 'treemanifest'):
2899 if ui.configbool('experimental', 'treemanifest'):
2899 requirements.add('treemanifest')
2900 requirements.add('treemanifest')
2900 # experimental config: format.sparse-revlog
2901 # experimental config: format.sparse-revlog
2901 if ui.configbool('format', 'sparse-revlog'):
2902 if ui.configbool('format', 'sparse-revlog'):
2902 requirements.add(SPARSEREVLOG_REQUIREMENT)
2903 requirements.add(SPARSEREVLOG_REQUIREMENT)
2903
2904
2904 revlogv2 = ui.config('experimental', 'revlogv2')
2905 revlogv2 = ui.config('experimental', 'revlogv2')
2905 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2906 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2906 requirements.remove('revlogv1')
2907 requirements.remove('revlogv1')
2907 # generaldelta is implied by revlogv2.
2908 # generaldelta is implied by revlogv2.
2908 requirements.discard('generaldelta')
2909 requirements.discard('generaldelta')
2909 requirements.add(REVLOGV2_REQUIREMENT)
2910 requirements.add(REVLOGV2_REQUIREMENT)
2910 # experimental config: format.internal-phase
2911 # experimental config: format.internal-phase
2911 if ui.configbool('format', 'internal-phase'):
2912 if ui.configbool('format', 'internal-phase'):
2912 requirements.add('internal-phase')
2913 requirements.add('internal-phase')
2913
2914
2914 if createopts.get('narrowfiles'):
2915 if createopts.get('narrowfiles'):
2915 requirements.add(repository.NARROW_REQUIREMENT)
2916 requirements.add(repository.NARROW_REQUIREMENT)
2916
2917
2917 if createopts.get('lfs'):
2918 if createopts.get('lfs'):
2918 requirements.add('lfs')
2919 requirements.add('lfs')
2919
2920
2920 return requirements
2921 return requirements
2921
2922
2922 def filterknowncreateopts(ui, createopts):
2923 def filterknowncreateopts(ui, createopts):
2923 """Filters a dict of repo creation options against options that are known.
2924 """Filters a dict of repo creation options against options that are known.
2924
2925
2925 Receives a dict of repo creation options and returns a dict of those
2926 Receives a dict of repo creation options and returns a dict of those
2926 options that we don't know how to handle.
2927 options that we don't know how to handle.
2927
2928
2928 This function is called as part of repository creation. If the
2929 This function is called as part of repository creation. If the
2929 returned dict contains any items, repository creation will not
2930 returned dict contains any items, repository creation will not
2930 be allowed, as it means there was a request to create a repository
2931 be allowed, as it means there was a request to create a repository
2931 with options not recognized by loaded code.
2932 with options not recognized by loaded code.
2932
2933
2933 Extensions can wrap this function to filter out creation options
2934 Extensions can wrap this function to filter out creation options
2934 they know how to handle.
2935 they know how to handle.
2935 """
2936 """
2936 known = {
2937 known = {
2937 'backend',
2938 'backend',
2938 'lfs',
2939 'lfs',
2939 'narrowfiles',
2940 'narrowfiles',
2940 'sharedrepo',
2941 'sharedrepo',
2941 'sharedrelative',
2942 'sharedrelative',
2942 'shareditems',
2943 'shareditems',
2943 'shallowfilestore',
2944 'shallowfilestore',
2944 }
2945 }
2945
2946
2946 return {k: v for k, v in createopts.items() if k not in known}
2947 return {k: v for k, v in createopts.items() if k not in known}
2947
2948
2948 def createrepository(ui, path, createopts=None):
2949 def createrepository(ui, path, createopts=None):
2949 """Create a new repository in a vfs.
2950 """Create a new repository in a vfs.
2950
2951
2951 ``path`` path to the new repo's working directory.
2952 ``path`` path to the new repo's working directory.
2952 ``createopts`` options for the new repository.
2953 ``createopts`` options for the new repository.
2953
2954
2954 The following keys for ``createopts`` are recognized:
2955 The following keys for ``createopts`` are recognized:
2955
2956
2956 backend
2957 backend
2957 The storage backend to use.
2958 The storage backend to use.
2958 lfs
2959 lfs
2959 Repository will be created with ``lfs`` requirement. The lfs extension
2960 Repository will be created with ``lfs`` requirement. The lfs extension
2960 will automatically be loaded when the repository is accessed.
2961 will automatically be loaded when the repository is accessed.
2961 narrowfiles
2962 narrowfiles
2962 Set up repository to support narrow file storage.
2963 Set up repository to support narrow file storage.
2963 sharedrepo
2964 sharedrepo
2964 Repository object from which storage should be shared.
2965 Repository object from which storage should be shared.
2965 sharedrelative
2966 sharedrelative
2966 Boolean indicating if the path to the shared repo should be
2967 Boolean indicating if the path to the shared repo should be
2967 stored as relative. By default, the pointer to the "parent" repo
2968 stored as relative. By default, the pointer to the "parent" repo
2968 is stored as an absolute path.
2969 is stored as an absolute path.
2969 shareditems
2970 shareditems
2970 Set of items to share to the new repository (in addition to storage).
2971 Set of items to share to the new repository (in addition to storage).
2971 shallowfilestore
2972 shallowfilestore
2972 Indicates that storage for files should be shallow (not all ancestor
2973 Indicates that storage for files should be shallow (not all ancestor
2973 revisions are known).
2974 revisions are known).
2974 """
2975 """
2975 createopts = defaultcreateopts(ui, createopts=createopts)
2976 createopts = defaultcreateopts(ui, createopts=createopts)
2976
2977
2977 unknownopts = filterknowncreateopts(ui, createopts)
2978 unknownopts = filterknowncreateopts(ui, createopts)
2978
2979
2979 if not isinstance(unknownopts, dict):
2980 if not isinstance(unknownopts, dict):
2980 raise error.ProgrammingError('filterknowncreateopts() did not return '
2981 raise error.ProgrammingError('filterknowncreateopts() did not return '
2981 'a dict')
2982 'a dict')
2982
2983
2983 if unknownopts:
2984 if unknownopts:
2984 raise error.Abort(_('unable to create repository because of unknown '
2985 raise error.Abort(_('unable to create repository because of unknown '
2985 'creation option: %s') %
2986 'creation option: %s') %
2986 ', '.join(sorted(unknownopts)),
2987 ', '.join(sorted(unknownopts)),
2987 hint=_('is a required extension not loaded?'))
2988 hint=_('is a required extension not loaded?'))
2988
2989
2989 requirements = newreporequirements(ui, createopts=createopts)
2990 requirements = newreporequirements(ui, createopts=createopts)
2990
2991
2991 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
2992 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
2992
2993
2993 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
2994 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
2994 if hgvfs.exists():
2995 if hgvfs.exists():
2995 raise error.RepoError(_('repository %s already exists') % path)
2996 raise error.RepoError(_('repository %s already exists') % path)
2996
2997
2997 if 'sharedrepo' in createopts:
2998 if 'sharedrepo' in createopts:
2998 sharedpath = createopts['sharedrepo'].sharedpath
2999 sharedpath = createopts['sharedrepo'].sharedpath
2999
3000
3000 if createopts.get('sharedrelative'):
3001 if createopts.get('sharedrelative'):
3001 try:
3002 try:
3002 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3003 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3003 except (IOError, ValueError) as e:
3004 except (IOError, ValueError) as e:
3004 # ValueError is raised on Windows if the drive letters differ
3005 # ValueError is raised on Windows if the drive letters differ
3005 # on each path.
3006 # on each path.
3006 raise error.Abort(_('cannot calculate relative path'),
3007 raise error.Abort(_('cannot calculate relative path'),
3007 hint=stringutil.forcebytestr(e))
3008 hint=stringutil.forcebytestr(e))
3008
3009
3009 if not wdirvfs.exists():
3010 if not wdirvfs.exists():
3010 wdirvfs.makedirs()
3011 wdirvfs.makedirs()
3011
3012
3012 hgvfs.makedir(notindexed=True)
3013 hgvfs.makedir(notindexed=True)
3013
3014
3014 if b'store' in requirements and 'sharedrepo' not in createopts:
3015 if b'store' in requirements and 'sharedrepo' not in createopts:
3015 hgvfs.mkdir(b'store')
3016 hgvfs.mkdir(b'store')
3016
3017
3017 # We create an invalid changelog outside the store so very old
3018 # We create an invalid changelog outside the store so very old
3018 # Mercurial versions (which didn't know about the requirements
3019 # Mercurial versions (which didn't know about the requirements
3019 # file) encounter an error on reading the changelog. This
3020 # file) encounter an error on reading the changelog. This
3020 # effectively locks out old clients and prevents them from
3021 # effectively locks out old clients and prevents them from
3021 # mucking with a repo in an unknown format.
3022 # mucking with a repo in an unknown format.
3022 #
3023 #
3023 # The revlog header has version 2, which won't be recognized by
3024 # The revlog header has version 2, which won't be recognized by
3024 # such old clients.
3025 # such old clients.
3025 hgvfs.append(b'00changelog.i',
3026 hgvfs.append(b'00changelog.i',
3026 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3027 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3027 b'layout')
3028 b'layout')
3028
3029
3029 scmutil.writerequires(hgvfs, requirements)
3030 scmutil.writerequires(hgvfs, requirements)
3030
3031
3031 # Write out file telling readers where to find the shared store.
3032 # Write out file telling readers where to find the shared store.
3032 if 'sharedrepo' in createopts:
3033 if 'sharedrepo' in createopts:
3033 hgvfs.write(b'sharedpath', sharedpath)
3034 hgvfs.write(b'sharedpath', sharedpath)
3034
3035
3035 if createopts.get('shareditems'):
3036 if createopts.get('shareditems'):
3036 shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n'
3037 shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n'
3037 hgvfs.write(b'shared', shared)
3038 hgvfs.write(b'shared', shared)
3038
3039
3039 def poisonrepository(repo):
3040 def poisonrepository(repo):
3040 """Poison a repository instance so it can no longer be used."""
3041 """Poison a repository instance so it can no longer be used."""
3041 # Perform any cleanup on the instance.
3042 # Perform any cleanup on the instance.
3042 repo.close()
3043 repo.close()
3043
3044
3044 # Our strategy is to replace the type of the object with one that
3045 # Our strategy is to replace the type of the object with one that
3045 # has all attribute lookups result in error.
3046 # has all attribute lookups result in error.
3046 #
3047 #
3047 # But we have to allow the close() method because some constructors
3048 # But we have to allow the close() method because some constructors
3048 # of repos call close() on repo references.
3049 # of repos call close() on repo references.
3049 class poisonedrepository(object):
3050 class poisonedrepository(object):
3050 def __getattribute__(self, item):
3051 def __getattribute__(self, item):
3051 if item == r'close':
3052 if item == r'close':
3052 return object.__getattribute__(self, item)
3053 return object.__getattribute__(self, item)
3053
3054
3054 raise error.ProgrammingError('repo instances should not be used '
3055 raise error.ProgrammingError('repo instances should not be used '
3055 'after unshare')
3056 'after unshare')
3056
3057
3057 def close(self):
3058 def close(self):
3058 pass
3059 pass
3059
3060
3060 # We may have a repoview, which intercepts __setattr__. So be sure
3061 # We may have a repoview, which intercepts __setattr__. So be sure
3061 # we operate at the lowest level possible.
3062 # we operate at the lowest level possible.
3062 object.__setattr__(repo, r'__class__', poisonedrepository)
3063 object.__setattr__(repo, r'__class__', poisonedrepository)
General Comments 0
You need to be logged in to leave comments. Login now