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