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