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