##// END OF EJS Templates
dirstate-v2: backup the data file during the transaction (issue6730)...
marmoute -
r50362:0705afae stable
parent child Browse files
Show More
@@ -1,1509 +1,1559 b''
1 # dirstate.py - working directory tracking for mercurial
1 # dirstate.py - working directory tracking for mercurial
2 #
2 #
3 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
3 # Copyright 2005-2007 Olivia Mackall <olivia@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
8
9 import collections
9 import collections
10 import contextlib
10 import contextlib
11 import os
11 import os
12 import stat
12 import stat
13 import uuid
13 import uuid
14
14
15 from .i18n import _
15 from .i18n import _
16 from .pycompat import delattr
16 from .pycompat import delattr
17
17
18 from hgdemandimport import tracing
18 from hgdemandimport import tracing
19
19
20 from . import (
20 from . import (
21 dirstatemap,
21 dirstatemap,
22 encoding,
22 encoding,
23 error,
23 error,
24 match as matchmod,
24 match as matchmod,
25 node,
25 node,
26 pathutil,
26 pathutil,
27 policy,
27 policy,
28 pycompat,
28 pycompat,
29 scmutil,
29 scmutil,
30 util,
30 util,
31 )
31 )
32
32
33 from .dirstateutils import (
33 from .dirstateutils import (
34 docket as docketmod,
34 timestamp,
35 timestamp,
35 )
36 )
36
37
37 from .interfaces import (
38 from .interfaces import (
38 dirstate as intdirstate,
39 dirstate as intdirstate,
39 util as interfaceutil,
40 util as interfaceutil,
40 )
41 )
41
42
42 parsers = policy.importmod('parsers')
43 parsers = policy.importmod('parsers')
43 rustmod = policy.importrust('dirstate')
44 rustmod = policy.importrust('dirstate')
44
45
45 HAS_FAST_DIRSTATE_V2 = rustmod is not None
46 HAS_FAST_DIRSTATE_V2 = rustmod is not None
46
47
47 propertycache = util.propertycache
48 propertycache = util.propertycache
48 filecache = scmutil.filecache
49 filecache = scmutil.filecache
49 _rangemask = dirstatemap.rangemask
50 _rangemask = dirstatemap.rangemask
50
51
51 DirstateItem = dirstatemap.DirstateItem
52 DirstateItem = dirstatemap.DirstateItem
52
53
53
54
54 class repocache(filecache):
55 class repocache(filecache):
55 """filecache for files in .hg/"""
56 """filecache for files in .hg/"""
56
57
57 def join(self, obj, fname):
58 def join(self, obj, fname):
58 return obj._opener.join(fname)
59 return obj._opener.join(fname)
59
60
60
61
61 class rootcache(filecache):
62 class rootcache(filecache):
62 """filecache for files in the repository root"""
63 """filecache for files in the repository root"""
63
64
64 def join(self, obj, fname):
65 def join(self, obj, fname):
65 return obj._join(fname)
66 return obj._join(fname)
66
67
67
68
68 def requires_parents_change(func):
69 def requires_parents_change(func):
69 def wrap(self, *args, **kwargs):
70 def wrap(self, *args, **kwargs):
70 if not self.pendingparentchange():
71 if not self.pendingparentchange():
71 msg = 'calling `%s` outside of a parentchange context'
72 msg = 'calling `%s` outside of a parentchange context'
72 msg %= func.__name__
73 msg %= func.__name__
73 raise error.ProgrammingError(msg)
74 raise error.ProgrammingError(msg)
74 return func(self, *args, **kwargs)
75 return func(self, *args, **kwargs)
75
76
76 return wrap
77 return wrap
77
78
78
79
79 def requires_no_parents_change(func):
80 def requires_no_parents_change(func):
80 def wrap(self, *args, **kwargs):
81 def wrap(self, *args, **kwargs):
81 if self.pendingparentchange():
82 if self.pendingparentchange():
82 msg = 'calling `%s` inside of a parentchange context'
83 msg = 'calling `%s` inside of a parentchange context'
83 msg %= func.__name__
84 msg %= func.__name__
84 raise error.ProgrammingError(msg)
85 raise error.ProgrammingError(msg)
85 return func(self, *args, **kwargs)
86 return func(self, *args, **kwargs)
86
87
87 return wrap
88 return wrap
88
89
89
90
90 @interfaceutil.implementer(intdirstate.idirstate)
91 @interfaceutil.implementer(intdirstate.idirstate)
91 class dirstate:
92 class dirstate:
92 def __init__(
93 def __init__(
93 self,
94 self,
94 opener,
95 opener,
95 ui,
96 ui,
96 root,
97 root,
97 validate,
98 validate,
98 sparsematchfn,
99 sparsematchfn,
99 nodeconstants,
100 nodeconstants,
100 use_dirstate_v2,
101 use_dirstate_v2,
101 use_tracked_hint=False,
102 use_tracked_hint=False,
102 ):
103 ):
103 """Create a new dirstate object.
104 """Create a new dirstate object.
104
105
105 opener is an open()-like callable that can be used to open the
106 opener is an open()-like callable that can be used to open the
106 dirstate file; root is the root of the directory tracked by
107 dirstate file; root is the root of the directory tracked by
107 the dirstate.
108 the dirstate.
108 """
109 """
109 self._use_dirstate_v2 = use_dirstate_v2
110 self._use_dirstate_v2 = use_dirstate_v2
110 self._use_tracked_hint = use_tracked_hint
111 self._use_tracked_hint = use_tracked_hint
111 self._nodeconstants = nodeconstants
112 self._nodeconstants = nodeconstants
112 self._opener = opener
113 self._opener = opener
113 self._validate = validate
114 self._validate = validate
114 self._root = root
115 self._root = root
115 # Either build a sparse-matcher or None if sparse is disabled
116 # Either build a sparse-matcher or None if sparse is disabled
116 self._sparsematchfn = sparsematchfn
117 self._sparsematchfn = sparsematchfn
117 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
118 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
118 # UNC path pointing to root share (issue4557)
119 # UNC path pointing to root share (issue4557)
119 self._rootdir = pathutil.normasprefix(root)
120 self._rootdir = pathutil.normasprefix(root)
120 # True is any internal state may be different
121 # True is any internal state may be different
121 self._dirty = False
122 self._dirty = False
122 # True if the set of tracked file may be different
123 # True if the set of tracked file may be different
123 self._dirty_tracked_set = False
124 self._dirty_tracked_set = False
124 self._ui = ui
125 self._ui = ui
125 self._filecache = {}
126 self._filecache = {}
126 self._parentwriters = 0
127 self._parentwriters = 0
127 self._filename = b'dirstate'
128 self._filename = b'dirstate'
128 self._filename_th = b'dirstate-tracked-hint'
129 self._filename_th = b'dirstate-tracked-hint'
129 self._pendingfilename = b'%s.pending' % self._filename
130 self._pendingfilename = b'%s.pending' % self._filename
130 self._plchangecallbacks = {}
131 self._plchangecallbacks = {}
131 self._origpl = None
132 self._origpl = None
132 self._mapcls = dirstatemap.dirstatemap
133 self._mapcls = dirstatemap.dirstatemap
133 # Access and cache cwd early, so we don't access it for the first time
134 # Access and cache cwd early, so we don't access it for the first time
134 # after a working-copy update caused it to not exist (accessing it then
135 # after a working-copy update caused it to not exist (accessing it then
135 # raises an exception).
136 # raises an exception).
136 self._cwd
137 self._cwd
137
138
138 def prefetch_parents(self):
139 def prefetch_parents(self):
139 """make sure the parents are loaded
140 """make sure the parents are loaded
140
141
141 Used to avoid a race condition.
142 Used to avoid a race condition.
142 """
143 """
143 self._pl
144 self._pl
144
145
145 @contextlib.contextmanager
146 @contextlib.contextmanager
146 def parentchange(self):
147 def parentchange(self):
147 """Context manager for handling dirstate parents.
148 """Context manager for handling dirstate parents.
148
149
149 If an exception occurs in the scope of the context manager,
150 If an exception occurs in the scope of the context manager,
150 the incoherent dirstate won't be written when wlock is
151 the incoherent dirstate won't be written when wlock is
151 released.
152 released.
152 """
153 """
153 self._parentwriters += 1
154 self._parentwriters += 1
154 yield
155 yield
155 # Typically we want the "undo" step of a context manager in a
156 # Typically we want the "undo" step of a context manager in a
156 # finally block so it happens even when an exception
157 # finally block so it happens even when an exception
157 # occurs. In this case, however, we only want to decrement
158 # occurs. In this case, however, we only want to decrement
158 # parentwriters if the code in the with statement exits
159 # parentwriters if the code in the with statement exits
159 # normally, so we don't have a try/finally here on purpose.
160 # normally, so we don't have a try/finally here on purpose.
160 self._parentwriters -= 1
161 self._parentwriters -= 1
161
162
162 def pendingparentchange(self):
163 def pendingparentchange(self):
163 """Returns true if the dirstate is in the middle of a set of changes
164 """Returns true if the dirstate is in the middle of a set of changes
164 that modify the dirstate parent.
165 that modify the dirstate parent.
165 """
166 """
166 return self._parentwriters > 0
167 return self._parentwriters > 0
167
168
168 @propertycache
169 @propertycache
169 def _map(self):
170 def _map(self):
170 """Return the dirstate contents (see documentation for dirstatemap)."""
171 """Return the dirstate contents (see documentation for dirstatemap)."""
171 self._map = self._mapcls(
172 self._map = self._mapcls(
172 self._ui,
173 self._ui,
173 self._opener,
174 self._opener,
174 self._root,
175 self._root,
175 self._nodeconstants,
176 self._nodeconstants,
176 self._use_dirstate_v2,
177 self._use_dirstate_v2,
177 )
178 )
178 return self._map
179 return self._map
179
180
180 @property
181 @property
181 def _sparsematcher(self):
182 def _sparsematcher(self):
182 """The matcher for the sparse checkout.
183 """The matcher for the sparse checkout.
183
184
184 The working directory may not include every file from a manifest. The
185 The working directory may not include every file from a manifest. The
185 matcher obtained by this property will match a path if it is to be
186 matcher obtained by this property will match a path if it is to be
186 included in the working directory.
187 included in the working directory.
187
188
188 When sparse if disabled, return None.
189 When sparse if disabled, return None.
189 """
190 """
190 if self._sparsematchfn is None:
191 if self._sparsematchfn is None:
191 return None
192 return None
192 # TODO there is potential to cache this property. For now, the matcher
193 # TODO there is potential to cache this property. For now, the matcher
193 # is resolved on every access. (But the called function does use a
194 # is resolved on every access. (But the called function does use a
194 # cache to keep the lookup fast.)
195 # cache to keep the lookup fast.)
195 return self._sparsematchfn()
196 return self._sparsematchfn()
196
197
197 @repocache(b'branch')
198 @repocache(b'branch')
198 def _branch(self):
199 def _branch(self):
199 try:
200 try:
200 return self._opener.read(b"branch").strip() or b"default"
201 return self._opener.read(b"branch").strip() or b"default"
201 except FileNotFoundError:
202 except FileNotFoundError:
202 return b"default"
203 return b"default"
203
204
204 @property
205 @property
205 def _pl(self):
206 def _pl(self):
206 return self._map.parents()
207 return self._map.parents()
207
208
208 def hasdir(self, d):
209 def hasdir(self, d):
209 return self._map.hastrackeddir(d)
210 return self._map.hastrackeddir(d)
210
211
211 @rootcache(b'.hgignore')
212 @rootcache(b'.hgignore')
212 def _ignore(self):
213 def _ignore(self):
213 files = self._ignorefiles()
214 files = self._ignorefiles()
214 if not files:
215 if not files:
215 return matchmod.never()
216 return matchmod.never()
216
217
217 pats = [b'include:%s' % f for f in files]
218 pats = [b'include:%s' % f for f in files]
218 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
219 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
219
220
220 @propertycache
221 @propertycache
221 def _slash(self):
222 def _slash(self):
222 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
223 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
223
224
224 @propertycache
225 @propertycache
225 def _checklink(self):
226 def _checklink(self):
226 return util.checklink(self._root)
227 return util.checklink(self._root)
227
228
228 @propertycache
229 @propertycache
229 def _checkexec(self):
230 def _checkexec(self):
230 return bool(util.checkexec(self._root))
231 return bool(util.checkexec(self._root))
231
232
232 @propertycache
233 @propertycache
233 def _checkcase(self):
234 def _checkcase(self):
234 return not util.fscasesensitive(self._join(b'.hg'))
235 return not util.fscasesensitive(self._join(b'.hg'))
235
236
236 def _join(self, f):
237 def _join(self, f):
237 # much faster than os.path.join()
238 # much faster than os.path.join()
238 # it's safe because f is always a relative path
239 # it's safe because f is always a relative path
239 return self._rootdir + f
240 return self._rootdir + f
240
241
241 def flagfunc(self, buildfallback):
242 def flagfunc(self, buildfallback):
242 """build a callable that returns flags associated with a filename
243 """build a callable that returns flags associated with a filename
243
244
244 The information is extracted from three possible layers:
245 The information is extracted from three possible layers:
245 1. the file system if it supports the information
246 1. the file system if it supports the information
246 2. the "fallback" information stored in the dirstate if any
247 2. the "fallback" information stored in the dirstate if any
247 3. a more expensive mechanism inferring the flags from the parents.
248 3. a more expensive mechanism inferring the flags from the parents.
248 """
249 """
249
250
250 # small hack to cache the result of buildfallback()
251 # small hack to cache the result of buildfallback()
251 fallback_func = []
252 fallback_func = []
252
253
253 def get_flags(x):
254 def get_flags(x):
254 entry = None
255 entry = None
255 fallback_value = None
256 fallback_value = None
256 try:
257 try:
257 st = os.lstat(self._join(x))
258 st = os.lstat(self._join(x))
258 except OSError:
259 except OSError:
259 return b''
260 return b''
260
261
261 if self._checklink:
262 if self._checklink:
262 if util.statislink(st):
263 if util.statislink(st):
263 return b'l'
264 return b'l'
264 else:
265 else:
265 entry = self.get_entry(x)
266 entry = self.get_entry(x)
266 if entry.has_fallback_symlink:
267 if entry.has_fallback_symlink:
267 if entry.fallback_symlink:
268 if entry.fallback_symlink:
268 return b'l'
269 return b'l'
269 else:
270 else:
270 if not fallback_func:
271 if not fallback_func:
271 fallback_func.append(buildfallback())
272 fallback_func.append(buildfallback())
272 fallback_value = fallback_func[0](x)
273 fallback_value = fallback_func[0](x)
273 if b'l' in fallback_value:
274 if b'l' in fallback_value:
274 return b'l'
275 return b'l'
275
276
276 if self._checkexec:
277 if self._checkexec:
277 if util.statisexec(st):
278 if util.statisexec(st):
278 return b'x'
279 return b'x'
279 else:
280 else:
280 if entry is None:
281 if entry is None:
281 entry = self.get_entry(x)
282 entry = self.get_entry(x)
282 if entry.has_fallback_exec:
283 if entry.has_fallback_exec:
283 if entry.fallback_exec:
284 if entry.fallback_exec:
284 return b'x'
285 return b'x'
285 else:
286 else:
286 if fallback_value is None:
287 if fallback_value is None:
287 if not fallback_func:
288 if not fallback_func:
288 fallback_func.append(buildfallback())
289 fallback_func.append(buildfallback())
289 fallback_value = fallback_func[0](x)
290 fallback_value = fallback_func[0](x)
290 if b'x' in fallback_value:
291 if b'x' in fallback_value:
291 return b'x'
292 return b'x'
292 return b''
293 return b''
293
294
294 return get_flags
295 return get_flags
295
296
296 @propertycache
297 @propertycache
297 def _cwd(self):
298 def _cwd(self):
298 # internal config: ui.forcecwd
299 # internal config: ui.forcecwd
299 forcecwd = self._ui.config(b'ui', b'forcecwd')
300 forcecwd = self._ui.config(b'ui', b'forcecwd')
300 if forcecwd:
301 if forcecwd:
301 return forcecwd
302 return forcecwd
302 return encoding.getcwd()
303 return encoding.getcwd()
303
304
304 def getcwd(self):
305 def getcwd(self):
305 """Return the path from which a canonical path is calculated.
306 """Return the path from which a canonical path is calculated.
306
307
307 This path should be used to resolve file patterns or to convert
308 This path should be used to resolve file patterns or to convert
308 canonical paths back to file paths for display. It shouldn't be
309 canonical paths back to file paths for display. It shouldn't be
309 used to get real file paths. Use vfs functions instead.
310 used to get real file paths. Use vfs functions instead.
310 """
311 """
311 cwd = self._cwd
312 cwd = self._cwd
312 if cwd == self._root:
313 if cwd == self._root:
313 return b''
314 return b''
314 # self._root ends with a path separator if self._root is '/' or 'C:\'
315 # self._root ends with a path separator if self._root is '/' or 'C:\'
315 rootsep = self._root
316 rootsep = self._root
316 if not util.endswithsep(rootsep):
317 if not util.endswithsep(rootsep):
317 rootsep += pycompat.ossep
318 rootsep += pycompat.ossep
318 if cwd.startswith(rootsep):
319 if cwd.startswith(rootsep):
319 return cwd[len(rootsep) :]
320 return cwd[len(rootsep) :]
320 else:
321 else:
321 # we're outside the repo. return an absolute path.
322 # we're outside the repo. return an absolute path.
322 return cwd
323 return cwd
323
324
324 def pathto(self, f, cwd=None):
325 def pathto(self, f, cwd=None):
325 if cwd is None:
326 if cwd is None:
326 cwd = self.getcwd()
327 cwd = self.getcwd()
327 path = util.pathto(self._root, cwd, f)
328 path = util.pathto(self._root, cwd, f)
328 if self._slash:
329 if self._slash:
329 return util.pconvert(path)
330 return util.pconvert(path)
330 return path
331 return path
331
332
332 def get_entry(self, path):
333 def get_entry(self, path):
333 """return a DirstateItem for the associated path"""
334 """return a DirstateItem for the associated path"""
334 entry = self._map.get(path)
335 entry = self._map.get(path)
335 if entry is None:
336 if entry is None:
336 return DirstateItem()
337 return DirstateItem()
337 return entry
338 return entry
338
339
339 def __contains__(self, key):
340 def __contains__(self, key):
340 return key in self._map
341 return key in self._map
341
342
342 def __iter__(self):
343 def __iter__(self):
343 return iter(sorted(self._map))
344 return iter(sorted(self._map))
344
345
345 def items(self):
346 def items(self):
346 return self._map.items()
347 return self._map.items()
347
348
348 iteritems = items
349 iteritems = items
349
350
350 def parents(self):
351 def parents(self):
351 return [self._validate(p) for p in self._pl]
352 return [self._validate(p) for p in self._pl]
352
353
353 def p1(self):
354 def p1(self):
354 return self._validate(self._pl[0])
355 return self._validate(self._pl[0])
355
356
356 def p2(self):
357 def p2(self):
357 return self._validate(self._pl[1])
358 return self._validate(self._pl[1])
358
359
359 @property
360 @property
360 def in_merge(self):
361 def in_merge(self):
361 """True if a merge is in progress"""
362 """True if a merge is in progress"""
362 return self._pl[1] != self._nodeconstants.nullid
363 return self._pl[1] != self._nodeconstants.nullid
363
364
364 def branch(self):
365 def branch(self):
365 return encoding.tolocal(self._branch)
366 return encoding.tolocal(self._branch)
366
367
367 def setparents(self, p1, p2=None):
368 def setparents(self, p1, p2=None):
368 """Set dirstate parents to p1 and p2.
369 """Set dirstate parents to p1 and p2.
369
370
370 When moving from two parents to one, "merged" entries a
371 When moving from two parents to one, "merged" entries a
371 adjusted to normal and previous copy records discarded and
372 adjusted to normal and previous copy records discarded and
372 returned by the call.
373 returned by the call.
373
374
374 See localrepo.setparents()
375 See localrepo.setparents()
375 """
376 """
376 if p2 is None:
377 if p2 is None:
377 p2 = self._nodeconstants.nullid
378 p2 = self._nodeconstants.nullid
378 if self._parentwriters == 0:
379 if self._parentwriters == 0:
379 raise ValueError(
380 raise ValueError(
380 b"cannot set dirstate parent outside of "
381 b"cannot set dirstate parent outside of "
381 b"dirstate.parentchange context manager"
382 b"dirstate.parentchange context manager"
382 )
383 )
383
384
384 self._dirty = True
385 self._dirty = True
385 oldp2 = self._pl[1]
386 oldp2 = self._pl[1]
386 if self._origpl is None:
387 if self._origpl is None:
387 self._origpl = self._pl
388 self._origpl = self._pl
388 nullid = self._nodeconstants.nullid
389 nullid = self._nodeconstants.nullid
389 # True if we need to fold p2 related state back to a linear case
390 # True if we need to fold p2 related state back to a linear case
390 fold_p2 = oldp2 != nullid and p2 == nullid
391 fold_p2 = oldp2 != nullid and p2 == nullid
391 return self._map.setparents(p1, p2, fold_p2=fold_p2)
392 return self._map.setparents(p1, p2, fold_p2=fold_p2)
392
393
393 def setbranch(self, branch):
394 def setbranch(self, branch):
394 self.__class__._branch.set(self, encoding.fromlocal(branch))
395 self.__class__._branch.set(self, encoding.fromlocal(branch))
395 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
396 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
396 try:
397 try:
397 f.write(self._branch + b'\n')
398 f.write(self._branch + b'\n')
398 f.close()
399 f.close()
399
400
400 # make sure filecache has the correct stat info for _branch after
401 # make sure filecache has the correct stat info for _branch after
401 # replacing the underlying file
402 # replacing the underlying file
402 ce = self._filecache[b'_branch']
403 ce = self._filecache[b'_branch']
403 if ce:
404 if ce:
404 ce.refresh()
405 ce.refresh()
405 except: # re-raises
406 except: # re-raises
406 f.discard()
407 f.discard()
407 raise
408 raise
408
409
409 def invalidate(self):
410 def invalidate(self):
410 """Causes the next access to reread the dirstate.
411 """Causes the next access to reread the dirstate.
411
412
412 This is different from localrepo.invalidatedirstate() because it always
413 This is different from localrepo.invalidatedirstate() because it always
413 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
414 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
414 check whether the dirstate has changed before rereading it."""
415 check whether the dirstate has changed before rereading it."""
415
416
416 for a in ("_map", "_branch", "_ignore"):
417 for a in ("_map", "_branch", "_ignore"):
417 if a in self.__dict__:
418 if a in self.__dict__:
418 delattr(self, a)
419 delattr(self, a)
419 self._dirty = False
420 self._dirty = False
420 self._dirty_tracked_set = False
421 self._dirty_tracked_set = False
421 self._parentwriters = 0
422 self._parentwriters = 0
422 self._origpl = None
423 self._origpl = None
423
424
424 def copy(self, source, dest):
425 def copy(self, source, dest):
425 """Mark dest as a copy of source. Unmark dest if source is None."""
426 """Mark dest as a copy of source. Unmark dest if source is None."""
426 if source == dest:
427 if source == dest:
427 return
428 return
428 self._dirty = True
429 self._dirty = True
429 if source is not None:
430 if source is not None:
430 self._check_sparse(source)
431 self._check_sparse(source)
431 self._map.copymap[dest] = source
432 self._map.copymap[dest] = source
432 else:
433 else:
433 self._map.copymap.pop(dest, None)
434 self._map.copymap.pop(dest, None)
434
435
435 def copied(self, file):
436 def copied(self, file):
436 return self._map.copymap.get(file, None)
437 return self._map.copymap.get(file, None)
437
438
438 def copies(self):
439 def copies(self):
439 return self._map.copymap
440 return self._map.copymap
440
441
441 @requires_no_parents_change
442 @requires_no_parents_change
442 def set_tracked(self, filename, reset_copy=False):
443 def set_tracked(self, filename, reset_copy=False):
443 """a "public" method for generic code to mark a file as tracked
444 """a "public" method for generic code to mark a file as tracked
444
445
445 This function is to be called outside of "update/merge" case. For
446 This function is to be called outside of "update/merge" case. For
446 example by a command like `hg add X`.
447 example by a command like `hg add X`.
447
448
448 if reset_copy is set, any existing copy information will be dropped.
449 if reset_copy is set, any existing copy information will be dropped.
449
450
450 return True the file was previously untracked, False otherwise.
451 return True the file was previously untracked, False otherwise.
451 """
452 """
452 self._dirty = True
453 self._dirty = True
453 entry = self._map.get(filename)
454 entry = self._map.get(filename)
454 if entry is None or not entry.tracked:
455 if entry is None or not entry.tracked:
455 self._check_new_tracked_filename(filename)
456 self._check_new_tracked_filename(filename)
456 pre_tracked = self._map.set_tracked(filename)
457 pre_tracked = self._map.set_tracked(filename)
457 if reset_copy:
458 if reset_copy:
458 self._map.copymap.pop(filename, None)
459 self._map.copymap.pop(filename, None)
459 if pre_tracked:
460 if pre_tracked:
460 self._dirty_tracked_set = True
461 self._dirty_tracked_set = True
461 return pre_tracked
462 return pre_tracked
462
463
463 @requires_no_parents_change
464 @requires_no_parents_change
464 def set_untracked(self, filename):
465 def set_untracked(self, filename):
465 """a "public" method for generic code to mark a file as untracked
466 """a "public" method for generic code to mark a file as untracked
466
467
467 This function is to be called outside of "update/merge" case. For
468 This function is to be called outside of "update/merge" case. For
468 example by a command like `hg remove X`.
469 example by a command like `hg remove X`.
469
470
470 return True the file was previously tracked, False otherwise.
471 return True the file was previously tracked, False otherwise.
471 """
472 """
472 ret = self._map.set_untracked(filename)
473 ret = self._map.set_untracked(filename)
473 if ret:
474 if ret:
474 self._dirty = True
475 self._dirty = True
475 self._dirty_tracked_set = True
476 self._dirty_tracked_set = True
476 return ret
477 return ret
477
478
478 @requires_no_parents_change
479 @requires_no_parents_change
479 def set_clean(self, filename, parentfiledata):
480 def set_clean(self, filename, parentfiledata):
480 """record that the current state of the file on disk is known to be clean"""
481 """record that the current state of the file on disk is known to be clean"""
481 self._dirty = True
482 self._dirty = True
482 if not self._map[filename].tracked:
483 if not self._map[filename].tracked:
483 self._check_new_tracked_filename(filename)
484 self._check_new_tracked_filename(filename)
484 (mode, size, mtime) = parentfiledata
485 (mode, size, mtime) = parentfiledata
485 self._map.set_clean(filename, mode, size, mtime)
486 self._map.set_clean(filename, mode, size, mtime)
486
487
487 @requires_no_parents_change
488 @requires_no_parents_change
488 def set_possibly_dirty(self, filename):
489 def set_possibly_dirty(self, filename):
489 """record that the current state of the file on disk is unknown"""
490 """record that the current state of the file on disk is unknown"""
490 self._dirty = True
491 self._dirty = True
491 self._map.set_possibly_dirty(filename)
492 self._map.set_possibly_dirty(filename)
492
493
493 @requires_parents_change
494 @requires_parents_change
494 def update_file_p1(
495 def update_file_p1(
495 self,
496 self,
496 filename,
497 filename,
497 p1_tracked,
498 p1_tracked,
498 ):
499 ):
499 """Set a file as tracked in the parent (or not)
500 """Set a file as tracked in the parent (or not)
500
501
501 This is to be called when adjust the dirstate to a new parent after an history
502 This is to be called when adjust the dirstate to a new parent after an history
502 rewriting operation.
503 rewriting operation.
503
504
504 It should not be called during a merge (p2 != nullid) and only within
505 It should not be called during a merge (p2 != nullid) and only within
505 a `with dirstate.parentchange():` context.
506 a `with dirstate.parentchange():` context.
506 """
507 """
507 if self.in_merge:
508 if self.in_merge:
508 msg = b'update_file_reference should not be called when merging'
509 msg = b'update_file_reference should not be called when merging'
509 raise error.ProgrammingError(msg)
510 raise error.ProgrammingError(msg)
510 entry = self._map.get(filename)
511 entry = self._map.get(filename)
511 if entry is None:
512 if entry is None:
512 wc_tracked = False
513 wc_tracked = False
513 else:
514 else:
514 wc_tracked = entry.tracked
515 wc_tracked = entry.tracked
515 if not (p1_tracked or wc_tracked):
516 if not (p1_tracked or wc_tracked):
516 # the file is no longer relevant to anyone
517 # the file is no longer relevant to anyone
517 if self._map.get(filename) is not None:
518 if self._map.get(filename) is not None:
518 self._map.reset_state(filename)
519 self._map.reset_state(filename)
519 self._dirty = True
520 self._dirty = True
520 elif (not p1_tracked) and wc_tracked:
521 elif (not p1_tracked) and wc_tracked:
521 if entry is not None and entry.added:
522 if entry is not None and entry.added:
522 return # avoid dropping copy information (maybe?)
523 return # avoid dropping copy information (maybe?)
523
524
524 self._map.reset_state(
525 self._map.reset_state(
525 filename,
526 filename,
526 wc_tracked,
527 wc_tracked,
527 p1_tracked,
528 p1_tracked,
528 # the underlying reference might have changed, we will have to
529 # the underlying reference might have changed, we will have to
529 # check it.
530 # check it.
530 has_meaningful_mtime=False,
531 has_meaningful_mtime=False,
531 )
532 )
532
533
533 @requires_parents_change
534 @requires_parents_change
534 def update_file(
535 def update_file(
535 self,
536 self,
536 filename,
537 filename,
537 wc_tracked,
538 wc_tracked,
538 p1_tracked,
539 p1_tracked,
539 p2_info=False,
540 p2_info=False,
540 possibly_dirty=False,
541 possibly_dirty=False,
541 parentfiledata=None,
542 parentfiledata=None,
542 ):
543 ):
543 """update the information about a file in the dirstate
544 """update the information about a file in the dirstate
544
545
545 This is to be called when the direstates parent changes to keep track
546 This is to be called when the direstates parent changes to keep track
546 of what is the file situation in regards to the working copy and its parent.
547 of what is the file situation in regards to the working copy and its parent.
547
548
548 This function must be called within a `dirstate.parentchange` context.
549 This function must be called within a `dirstate.parentchange` context.
549
550
550 note: the API is at an early stage and we might need to adjust it
551 note: the API is at an early stage and we might need to adjust it
551 depending of what information ends up being relevant and useful to
552 depending of what information ends up being relevant and useful to
552 other processing.
553 other processing.
553 """
554 """
554
555
555 # note: I do not think we need to double check name clash here since we
556 # note: I do not think we need to double check name clash here since we
556 # are in a update/merge case that should already have taken care of
557 # are in a update/merge case that should already have taken care of
557 # this. The test agrees
558 # this. The test agrees
558
559
559 self._dirty = True
560 self._dirty = True
560 old_entry = self._map.get(filename)
561 old_entry = self._map.get(filename)
561 if old_entry is None:
562 if old_entry is None:
562 prev_tracked = False
563 prev_tracked = False
563 else:
564 else:
564 prev_tracked = old_entry.tracked
565 prev_tracked = old_entry.tracked
565 if prev_tracked != wc_tracked:
566 if prev_tracked != wc_tracked:
566 self._dirty_tracked_set = True
567 self._dirty_tracked_set = True
567
568
568 self._map.reset_state(
569 self._map.reset_state(
569 filename,
570 filename,
570 wc_tracked,
571 wc_tracked,
571 p1_tracked,
572 p1_tracked,
572 p2_info=p2_info,
573 p2_info=p2_info,
573 has_meaningful_mtime=not possibly_dirty,
574 has_meaningful_mtime=not possibly_dirty,
574 parentfiledata=parentfiledata,
575 parentfiledata=parentfiledata,
575 )
576 )
576
577
577 def _check_new_tracked_filename(self, filename):
578 def _check_new_tracked_filename(self, filename):
578 scmutil.checkfilename(filename)
579 scmutil.checkfilename(filename)
579 if self._map.hastrackeddir(filename):
580 if self._map.hastrackeddir(filename):
580 msg = _(b'directory %r already in dirstate')
581 msg = _(b'directory %r already in dirstate')
581 msg %= pycompat.bytestr(filename)
582 msg %= pycompat.bytestr(filename)
582 raise error.Abort(msg)
583 raise error.Abort(msg)
583 # shadows
584 # shadows
584 for d in pathutil.finddirs(filename):
585 for d in pathutil.finddirs(filename):
585 if self._map.hastrackeddir(d):
586 if self._map.hastrackeddir(d):
586 break
587 break
587 entry = self._map.get(d)
588 entry = self._map.get(d)
588 if entry is not None and not entry.removed:
589 if entry is not None and not entry.removed:
589 msg = _(b'file %r in dirstate clashes with %r')
590 msg = _(b'file %r in dirstate clashes with %r')
590 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
591 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
591 raise error.Abort(msg)
592 raise error.Abort(msg)
592 self._check_sparse(filename)
593 self._check_sparse(filename)
593
594
594 def _check_sparse(self, filename):
595 def _check_sparse(self, filename):
595 """Check that a filename is inside the sparse profile"""
596 """Check that a filename is inside the sparse profile"""
596 sparsematch = self._sparsematcher
597 sparsematch = self._sparsematcher
597 if sparsematch is not None and not sparsematch.always():
598 if sparsematch is not None and not sparsematch.always():
598 if not sparsematch(filename):
599 if not sparsematch(filename):
599 msg = _(b"cannot add '%s' - it is outside the sparse checkout")
600 msg = _(b"cannot add '%s' - it is outside the sparse checkout")
600 hint = _(
601 hint = _(
601 b'include file with `hg debugsparse --include <pattern>` or use '
602 b'include file with `hg debugsparse --include <pattern>` or use '
602 b'`hg add -s <file>` to include file directory while adding'
603 b'`hg add -s <file>` to include file directory while adding'
603 )
604 )
604 raise error.Abort(msg % filename, hint=hint)
605 raise error.Abort(msg % filename, hint=hint)
605
606
606 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
607 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
607 if exists is None:
608 if exists is None:
608 exists = os.path.lexists(os.path.join(self._root, path))
609 exists = os.path.lexists(os.path.join(self._root, path))
609 if not exists:
610 if not exists:
610 # Maybe a path component exists
611 # Maybe a path component exists
611 if not ignoremissing and b'/' in path:
612 if not ignoremissing and b'/' in path:
612 d, f = path.rsplit(b'/', 1)
613 d, f = path.rsplit(b'/', 1)
613 d = self._normalize(d, False, ignoremissing, None)
614 d = self._normalize(d, False, ignoremissing, None)
614 folded = d + b"/" + f
615 folded = d + b"/" + f
615 else:
616 else:
616 # No path components, preserve original case
617 # No path components, preserve original case
617 folded = path
618 folded = path
618 else:
619 else:
619 # recursively normalize leading directory components
620 # recursively normalize leading directory components
620 # against dirstate
621 # against dirstate
621 if b'/' in normed:
622 if b'/' in normed:
622 d, f = normed.rsplit(b'/', 1)
623 d, f = normed.rsplit(b'/', 1)
623 d = self._normalize(d, False, ignoremissing, True)
624 d = self._normalize(d, False, ignoremissing, True)
624 r = self._root + b"/" + d
625 r = self._root + b"/" + d
625 folded = d + b"/" + util.fspath(f, r)
626 folded = d + b"/" + util.fspath(f, r)
626 else:
627 else:
627 folded = util.fspath(normed, self._root)
628 folded = util.fspath(normed, self._root)
628 storemap[normed] = folded
629 storemap[normed] = folded
629
630
630 return folded
631 return folded
631
632
632 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
633 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
633 normed = util.normcase(path)
634 normed = util.normcase(path)
634 folded = self._map.filefoldmap.get(normed, None)
635 folded = self._map.filefoldmap.get(normed, None)
635 if folded is None:
636 if folded is None:
636 if isknown:
637 if isknown:
637 folded = path
638 folded = path
638 else:
639 else:
639 folded = self._discoverpath(
640 folded = self._discoverpath(
640 path, normed, ignoremissing, exists, self._map.filefoldmap
641 path, normed, ignoremissing, exists, self._map.filefoldmap
641 )
642 )
642 return folded
643 return folded
643
644
644 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
645 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
645 normed = util.normcase(path)
646 normed = util.normcase(path)
646 folded = self._map.filefoldmap.get(normed, None)
647 folded = self._map.filefoldmap.get(normed, None)
647 if folded is None:
648 if folded is None:
648 folded = self._map.dirfoldmap.get(normed, None)
649 folded = self._map.dirfoldmap.get(normed, None)
649 if folded is None:
650 if folded is None:
650 if isknown:
651 if isknown:
651 folded = path
652 folded = path
652 else:
653 else:
653 # store discovered result in dirfoldmap so that future
654 # store discovered result in dirfoldmap so that future
654 # normalizefile calls don't start matching directories
655 # normalizefile calls don't start matching directories
655 folded = self._discoverpath(
656 folded = self._discoverpath(
656 path, normed, ignoremissing, exists, self._map.dirfoldmap
657 path, normed, ignoremissing, exists, self._map.dirfoldmap
657 )
658 )
658 return folded
659 return folded
659
660
660 def normalize(self, path, isknown=False, ignoremissing=False):
661 def normalize(self, path, isknown=False, ignoremissing=False):
661 """
662 """
662 normalize the case of a pathname when on a casefolding filesystem
663 normalize the case of a pathname when on a casefolding filesystem
663
664
664 isknown specifies whether the filename came from walking the
665 isknown specifies whether the filename came from walking the
665 disk, to avoid extra filesystem access.
666 disk, to avoid extra filesystem access.
666
667
667 If ignoremissing is True, missing path are returned
668 If ignoremissing is True, missing path are returned
668 unchanged. Otherwise, we try harder to normalize possibly
669 unchanged. Otherwise, we try harder to normalize possibly
669 existing path components.
670 existing path components.
670
671
671 The normalized case is determined based on the following precedence:
672 The normalized case is determined based on the following precedence:
672
673
673 - version of name already stored in the dirstate
674 - version of name already stored in the dirstate
674 - version of name stored on disk
675 - version of name stored on disk
675 - version provided via command arguments
676 - version provided via command arguments
676 """
677 """
677
678
678 if self._checkcase:
679 if self._checkcase:
679 return self._normalize(path, isknown, ignoremissing)
680 return self._normalize(path, isknown, ignoremissing)
680 return path
681 return path
681
682
682 def clear(self):
683 def clear(self):
683 self._map.clear()
684 self._map.clear()
684 self._dirty = True
685 self._dirty = True
685
686
686 def rebuild(self, parent, allfiles, changedfiles=None):
687 def rebuild(self, parent, allfiles, changedfiles=None):
687
688
688 matcher = self._sparsematcher
689 matcher = self._sparsematcher
689 if matcher is not None and not matcher.always():
690 if matcher is not None and not matcher.always():
690 # should not add non-matching files
691 # should not add non-matching files
691 allfiles = [f for f in allfiles if matcher(f)]
692 allfiles = [f for f in allfiles if matcher(f)]
692 if changedfiles:
693 if changedfiles:
693 changedfiles = [f for f in changedfiles if matcher(f)]
694 changedfiles = [f for f in changedfiles if matcher(f)]
694
695
695 if changedfiles is not None:
696 if changedfiles is not None:
696 # these files will be deleted from the dirstate when they are
697 # these files will be deleted from the dirstate when they are
697 # not found to be in allfiles
698 # not found to be in allfiles
698 dirstatefilestoremove = {f for f in self if not matcher(f)}
699 dirstatefilestoremove = {f for f in self if not matcher(f)}
699 changedfiles = dirstatefilestoremove.union(changedfiles)
700 changedfiles = dirstatefilestoremove.union(changedfiles)
700
701
701 if changedfiles is None:
702 if changedfiles is None:
702 # Rebuild entire dirstate
703 # Rebuild entire dirstate
703 to_lookup = allfiles
704 to_lookup = allfiles
704 to_drop = []
705 to_drop = []
705 self.clear()
706 self.clear()
706 elif len(changedfiles) < 10:
707 elif len(changedfiles) < 10:
707 # Avoid turning allfiles into a set, which can be expensive if it's
708 # Avoid turning allfiles into a set, which can be expensive if it's
708 # large.
709 # large.
709 to_lookup = []
710 to_lookup = []
710 to_drop = []
711 to_drop = []
711 for f in changedfiles:
712 for f in changedfiles:
712 if f in allfiles:
713 if f in allfiles:
713 to_lookup.append(f)
714 to_lookup.append(f)
714 else:
715 else:
715 to_drop.append(f)
716 to_drop.append(f)
716 else:
717 else:
717 changedfilesset = set(changedfiles)
718 changedfilesset = set(changedfiles)
718 to_lookup = changedfilesset & set(allfiles)
719 to_lookup = changedfilesset & set(allfiles)
719 to_drop = changedfilesset - to_lookup
720 to_drop = changedfilesset - to_lookup
720
721
721 if self._origpl is None:
722 if self._origpl is None:
722 self._origpl = self._pl
723 self._origpl = self._pl
723 self._map.setparents(parent, self._nodeconstants.nullid)
724 self._map.setparents(parent, self._nodeconstants.nullid)
724
725
725 for f in to_lookup:
726 for f in to_lookup:
726
727
727 if self.in_merge:
728 if self.in_merge:
728 self.set_tracked(f)
729 self.set_tracked(f)
729 else:
730 else:
730 self._map.reset_state(
731 self._map.reset_state(
731 f,
732 f,
732 wc_tracked=True,
733 wc_tracked=True,
733 p1_tracked=True,
734 p1_tracked=True,
734 )
735 )
735 for f in to_drop:
736 for f in to_drop:
736 self._map.reset_state(f)
737 self._map.reset_state(f)
737
738
738 self._dirty = True
739 self._dirty = True
739
740
740 def identity(self):
741 def identity(self):
741 """Return identity of dirstate itself to detect changing in storage
742 """Return identity of dirstate itself to detect changing in storage
742
743
743 If identity of previous dirstate is equal to this, writing
744 If identity of previous dirstate is equal to this, writing
744 changes based on the former dirstate out can keep consistency.
745 changes based on the former dirstate out can keep consistency.
745 """
746 """
746 return self._map.identity
747 return self._map.identity
747
748
748 def write(self, tr):
749 def write(self, tr):
749 if not self._dirty:
750 if not self._dirty:
750 return
751 return
751
752
752 write_key = self._use_tracked_hint and self._dirty_tracked_set
753 write_key = self._use_tracked_hint and self._dirty_tracked_set
753 if tr:
754 if tr:
754 # delay writing in-memory changes out
755 # delay writing in-memory changes out
755 tr.addfilegenerator(
756 tr.addfilegenerator(
756 b'dirstate-1-main',
757 b'dirstate-1-main',
757 (self._filename,),
758 (self._filename,),
758 lambda f: self._writedirstate(tr, f),
759 lambda f: self._writedirstate(tr, f),
759 location=b'plain',
760 location=b'plain',
760 post_finalize=True,
761 post_finalize=True,
761 )
762 )
762 if write_key:
763 if write_key:
763 tr.addfilegenerator(
764 tr.addfilegenerator(
764 b'dirstate-2-key-post',
765 b'dirstate-2-key-post',
765 (self._filename_th,),
766 (self._filename_th,),
766 lambda f: self._write_tracked_hint(tr, f),
767 lambda f: self._write_tracked_hint(tr, f),
767 location=b'plain',
768 location=b'plain',
768 post_finalize=True,
769 post_finalize=True,
769 )
770 )
770 return
771 return
771
772
772 file = lambda f: self._opener(f, b"w", atomictemp=True, checkambig=True)
773 file = lambda f: self._opener(f, b"w", atomictemp=True, checkambig=True)
773 with file(self._filename) as f:
774 with file(self._filename) as f:
774 self._writedirstate(tr, f)
775 self._writedirstate(tr, f)
775 if write_key:
776 if write_key:
776 # we update the key-file after writing to make sure reader have a
777 # we update the key-file after writing to make sure reader have a
777 # key that match the newly written content
778 # key that match the newly written content
778 with file(self._filename_th) as f:
779 with file(self._filename_th) as f:
779 self._write_tracked_hint(tr, f)
780 self._write_tracked_hint(tr, f)
780
781
781 def delete_tracked_hint(self):
782 def delete_tracked_hint(self):
782 """remove the tracked_hint file
783 """remove the tracked_hint file
783
784
784 To be used by format downgrades operation"""
785 To be used by format downgrades operation"""
785 self._opener.unlink(self._filename_th)
786 self._opener.unlink(self._filename_th)
786 self._use_tracked_hint = False
787 self._use_tracked_hint = False
787
788
788 def addparentchangecallback(self, category, callback):
789 def addparentchangecallback(self, category, callback):
789 """add a callback to be called when the wd parents are changed
790 """add a callback to be called when the wd parents are changed
790
791
791 Callback will be called with the following arguments:
792 Callback will be called with the following arguments:
792 dirstate, (oldp1, oldp2), (newp1, newp2)
793 dirstate, (oldp1, oldp2), (newp1, newp2)
793
794
794 Category is a unique identifier to allow overwriting an old callback
795 Category is a unique identifier to allow overwriting an old callback
795 with a newer callback.
796 with a newer callback.
796 """
797 """
797 self._plchangecallbacks[category] = callback
798 self._plchangecallbacks[category] = callback
798
799
799 def _writedirstate(self, tr, st):
800 def _writedirstate(self, tr, st):
800 # notify callbacks about parents change
801 # notify callbacks about parents change
801 if self._origpl is not None and self._origpl != self._pl:
802 if self._origpl is not None and self._origpl != self._pl:
802 for c, callback in sorted(self._plchangecallbacks.items()):
803 for c, callback in sorted(self._plchangecallbacks.items()):
803 callback(self, self._origpl, self._pl)
804 callback(self, self._origpl, self._pl)
804 self._origpl = None
805 self._origpl = None
805 self._map.write(tr, st)
806 self._map.write(tr, st)
806 self._dirty = False
807 self._dirty = False
807 self._dirty_tracked_set = False
808 self._dirty_tracked_set = False
808
809
809 def _write_tracked_hint(self, tr, f):
810 def _write_tracked_hint(self, tr, f):
810 key = node.hex(uuid.uuid4().bytes)
811 key = node.hex(uuid.uuid4().bytes)
811 f.write(b"1\n%s\n" % key) # 1 is the format version
812 f.write(b"1\n%s\n" % key) # 1 is the format version
812
813
813 def _dirignore(self, f):
814 def _dirignore(self, f):
814 if self._ignore(f):
815 if self._ignore(f):
815 return True
816 return True
816 for p in pathutil.finddirs(f):
817 for p in pathutil.finddirs(f):
817 if self._ignore(p):
818 if self._ignore(p):
818 return True
819 return True
819 return False
820 return False
820
821
821 def _ignorefiles(self):
822 def _ignorefiles(self):
822 files = []
823 files = []
823 if os.path.exists(self._join(b'.hgignore')):
824 if os.path.exists(self._join(b'.hgignore')):
824 files.append(self._join(b'.hgignore'))
825 files.append(self._join(b'.hgignore'))
825 for name, path in self._ui.configitems(b"ui"):
826 for name, path in self._ui.configitems(b"ui"):
826 if name == b'ignore' or name.startswith(b'ignore.'):
827 if name == b'ignore' or name.startswith(b'ignore.'):
827 # we need to use os.path.join here rather than self._join
828 # we need to use os.path.join here rather than self._join
828 # because path is arbitrary and user-specified
829 # because path is arbitrary and user-specified
829 files.append(os.path.join(self._rootdir, util.expandpath(path)))
830 files.append(os.path.join(self._rootdir, util.expandpath(path)))
830 return files
831 return files
831
832
832 def _ignorefileandline(self, f):
833 def _ignorefileandline(self, f):
833 files = collections.deque(self._ignorefiles())
834 files = collections.deque(self._ignorefiles())
834 visited = set()
835 visited = set()
835 while files:
836 while files:
836 i = files.popleft()
837 i = files.popleft()
837 patterns = matchmod.readpatternfile(
838 patterns = matchmod.readpatternfile(
838 i, self._ui.warn, sourceinfo=True
839 i, self._ui.warn, sourceinfo=True
839 )
840 )
840 for pattern, lineno, line in patterns:
841 for pattern, lineno, line in patterns:
841 kind, p = matchmod._patsplit(pattern, b'glob')
842 kind, p = matchmod._patsplit(pattern, b'glob')
842 if kind == b"subinclude":
843 if kind == b"subinclude":
843 if p not in visited:
844 if p not in visited:
844 files.append(p)
845 files.append(p)
845 continue
846 continue
846 m = matchmod.match(
847 m = matchmod.match(
847 self._root, b'', [], [pattern], warn=self._ui.warn
848 self._root, b'', [], [pattern], warn=self._ui.warn
848 )
849 )
849 if m(f):
850 if m(f):
850 return (i, lineno, line)
851 return (i, lineno, line)
851 visited.add(i)
852 visited.add(i)
852 return (None, -1, b"")
853 return (None, -1, b"")
853
854
854 def _walkexplicit(self, match, subrepos):
855 def _walkexplicit(self, match, subrepos):
855 """Get stat data about the files explicitly specified by match.
856 """Get stat data about the files explicitly specified by match.
856
857
857 Return a triple (results, dirsfound, dirsnotfound).
858 Return a triple (results, dirsfound, dirsnotfound).
858 - results is a mapping from filename to stat result. It also contains
859 - results is a mapping from filename to stat result. It also contains
859 listings mapping subrepos and .hg to None.
860 listings mapping subrepos and .hg to None.
860 - dirsfound is a list of files found to be directories.
861 - dirsfound is a list of files found to be directories.
861 - dirsnotfound is a list of files that the dirstate thinks are
862 - dirsnotfound is a list of files that the dirstate thinks are
862 directories and that were not found."""
863 directories and that were not found."""
863
864
864 def badtype(mode):
865 def badtype(mode):
865 kind = _(b'unknown')
866 kind = _(b'unknown')
866 if stat.S_ISCHR(mode):
867 if stat.S_ISCHR(mode):
867 kind = _(b'character device')
868 kind = _(b'character device')
868 elif stat.S_ISBLK(mode):
869 elif stat.S_ISBLK(mode):
869 kind = _(b'block device')
870 kind = _(b'block device')
870 elif stat.S_ISFIFO(mode):
871 elif stat.S_ISFIFO(mode):
871 kind = _(b'fifo')
872 kind = _(b'fifo')
872 elif stat.S_ISSOCK(mode):
873 elif stat.S_ISSOCK(mode):
873 kind = _(b'socket')
874 kind = _(b'socket')
874 elif stat.S_ISDIR(mode):
875 elif stat.S_ISDIR(mode):
875 kind = _(b'directory')
876 kind = _(b'directory')
876 return _(b'unsupported file type (type is %s)') % kind
877 return _(b'unsupported file type (type is %s)') % kind
877
878
878 badfn = match.bad
879 badfn = match.bad
879 dmap = self._map
880 dmap = self._map
880 lstat = os.lstat
881 lstat = os.lstat
881 getkind = stat.S_IFMT
882 getkind = stat.S_IFMT
882 dirkind = stat.S_IFDIR
883 dirkind = stat.S_IFDIR
883 regkind = stat.S_IFREG
884 regkind = stat.S_IFREG
884 lnkkind = stat.S_IFLNK
885 lnkkind = stat.S_IFLNK
885 join = self._join
886 join = self._join
886 dirsfound = []
887 dirsfound = []
887 foundadd = dirsfound.append
888 foundadd = dirsfound.append
888 dirsnotfound = []
889 dirsnotfound = []
889 notfoundadd = dirsnotfound.append
890 notfoundadd = dirsnotfound.append
890
891
891 if not match.isexact() and self._checkcase:
892 if not match.isexact() and self._checkcase:
892 normalize = self._normalize
893 normalize = self._normalize
893 else:
894 else:
894 normalize = None
895 normalize = None
895
896
896 files = sorted(match.files())
897 files = sorted(match.files())
897 subrepos.sort()
898 subrepos.sort()
898 i, j = 0, 0
899 i, j = 0, 0
899 while i < len(files) and j < len(subrepos):
900 while i < len(files) and j < len(subrepos):
900 subpath = subrepos[j] + b"/"
901 subpath = subrepos[j] + b"/"
901 if files[i] < subpath:
902 if files[i] < subpath:
902 i += 1
903 i += 1
903 continue
904 continue
904 while i < len(files) and files[i].startswith(subpath):
905 while i < len(files) and files[i].startswith(subpath):
905 del files[i]
906 del files[i]
906 j += 1
907 j += 1
907
908
908 if not files or b'' in files:
909 if not files or b'' in files:
909 files = [b'']
910 files = [b'']
910 # constructing the foldmap is expensive, so don't do it for the
911 # constructing the foldmap is expensive, so don't do it for the
911 # common case where files is ['']
912 # common case where files is ['']
912 normalize = None
913 normalize = None
913 results = dict.fromkeys(subrepos)
914 results = dict.fromkeys(subrepos)
914 results[b'.hg'] = None
915 results[b'.hg'] = None
915
916
916 for ff in files:
917 for ff in files:
917 if normalize:
918 if normalize:
918 nf = normalize(ff, False, True)
919 nf = normalize(ff, False, True)
919 else:
920 else:
920 nf = ff
921 nf = ff
921 if nf in results:
922 if nf in results:
922 continue
923 continue
923
924
924 try:
925 try:
925 st = lstat(join(nf))
926 st = lstat(join(nf))
926 kind = getkind(st.st_mode)
927 kind = getkind(st.st_mode)
927 if kind == dirkind:
928 if kind == dirkind:
928 if nf in dmap:
929 if nf in dmap:
929 # file replaced by dir on disk but still in dirstate
930 # file replaced by dir on disk but still in dirstate
930 results[nf] = None
931 results[nf] = None
931 foundadd((nf, ff))
932 foundadd((nf, ff))
932 elif kind == regkind or kind == lnkkind:
933 elif kind == regkind or kind == lnkkind:
933 results[nf] = st
934 results[nf] = st
934 else:
935 else:
935 badfn(ff, badtype(kind))
936 badfn(ff, badtype(kind))
936 if nf in dmap:
937 if nf in dmap:
937 results[nf] = None
938 results[nf] = None
938 except OSError as inst: # nf not found on disk - it is dirstate only
939 except OSError as inst: # nf not found on disk - it is dirstate only
939 if nf in dmap: # does it exactly match a missing file?
940 if nf in dmap: # does it exactly match a missing file?
940 results[nf] = None
941 results[nf] = None
941 else: # does it match a missing directory?
942 else: # does it match a missing directory?
942 if self._map.hasdir(nf):
943 if self._map.hasdir(nf):
943 notfoundadd(nf)
944 notfoundadd(nf)
944 else:
945 else:
945 badfn(ff, encoding.strtolocal(inst.strerror))
946 badfn(ff, encoding.strtolocal(inst.strerror))
946
947
947 # match.files() may contain explicitly-specified paths that shouldn't
948 # match.files() may contain explicitly-specified paths that shouldn't
948 # be taken; drop them from the list of files found. dirsfound/notfound
949 # be taken; drop them from the list of files found. dirsfound/notfound
949 # aren't filtered here because they will be tested later.
950 # aren't filtered here because they will be tested later.
950 if match.anypats():
951 if match.anypats():
951 for f in list(results):
952 for f in list(results):
952 if f == b'.hg' or f in subrepos:
953 if f == b'.hg' or f in subrepos:
953 # keep sentinel to disable further out-of-repo walks
954 # keep sentinel to disable further out-of-repo walks
954 continue
955 continue
955 if not match(f):
956 if not match(f):
956 del results[f]
957 del results[f]
957
958
958 # Case insensitive filesystems cannot rely on lstat() failing to detect
959 # Case insensitive filesystems cannot rely on lstat() failing to detect
959 # a case-only rename. Prune the stat object for any file that does not
960 # a case-only rename. Prune the stat object for any file that does not
960 # match the case in the filesystem, if there are multiple files that
961 # match the case in the filesystem, if there are multiple files that
961 # normalize to the same path.
962 # normalize to the same path.
962 if match.isexact() and self._checkcase:
963 if match.isexact() and self._checkcase:
963 normed = {}
964 normed = {}
964
965
965 for f, st in results.items():
966 for f, st in results.items():
966 if st is None:
967 if st is None:
967 continue
968 continue
968
969
969 nc = util.normcase(f)
970 nc = util.normcase(f)
970 paths = normed.get(nc)
971 paths = normed.get(nc)
971
972
972 if paths is None:
973 if paths is None:
973 paths = set()
974 paths = set()
974 normed[nc] = paths
975 normed[nc] = paths
975
976
976 paths.add(f)
977 paths.add(f)
977
978
978 for norm, paths in normed.items():
979 for norm, paths in normed.items():
979 if len(paths) > 1:
980 if len(paths) > 1:
980 for path in paths:
981 for path in paths:
981 folded = self._discoverpath(
982 folded = self._discoverpath(
982 path, norm, True, None, self._map.dirfoldmap
983 path, norm, True, None, self._map.dirfoldmap
983 )
984 )
984 if path != folded:
985 if path != folded:
985 results[path] = None
986 results[path] = None
986
987
987 return results, dirsfound, dirsnotfound
988 return results, dirsfound, dirsnotfound
988
989
989 def walk(self, match, subrepos, unknown, ignored, full=True):
990 def walk(self, match, subrepos, unknown, ignored, full=True):
990 """
991 """
991 Walk recursively through the directory tree, finding all files
992 Walk recursively through the directory tree, finding all files
992 matched by match.
993 matched by match.
993
994
994 If full is False, maybe skip some known-clean files.
995 If full is False, maybe skip some known-clean files.
995
996
996 Return a dict mapping filename to stat-like object (either
997 Return a dict mapping filename to stat-like object (either
997 mercurial.osutil.stat instance or return value of os.stat()).
998 mercurial.osutil.stat instance or return value of os.stat()).
998
999
999 """
1000 """
1000 # full is a flag that extensions that hook into walk can use -- this
1001 # full is a flag that extensions that hook into walk can use -- this
1001 # implementation doesn't use it at all. This satisfies the contract
1002 # implementation doesn't use it at all. This satisfies the contract
1002 # because we only guarantee a "maybe".
1003 # because we only guarantee a "maybe".
1003
1004
1004 if ignored:
1005 if ignored:
1005 ignore = util.never
1006 ignore = util.never
1006 dirignore = util.never
1007 dirignore = util.never
1007 elif unknown:
1008 elif unknown:
1008 ignore = self._ignore
1009 ignore = self._ignore
1009 dirignore = self._dirignore
1010 dirignore = self._dirignore
1010 else:
1011 else:
1011 # if not unknown and not ignored, drop dir recursion and step 2
1012 # if not unknown and not ignored, drop dir recursion and step 2
1012 ignore = util.always
1013 ignore = util.always
1013 dirignore = util.always
1014 dirignore = util.always
1014
1015
1015 if self._sparsematchfn is not None:
1016 if self._sparsematchfn is not None:
1016 em = matchmod.exact(match.files())
1017 em = matchmod.exact(match.files())
1017 sm = matchmod.unionmatcher([self._sparsematcher, em])
1018 sm = matchmod.unionmatcher([self._sparsematcher, em])
1018 match = matchmod.intersectmatchers(match, sm)
1019 match = matchmod.intersectmatchers(match, sm)
1019
1020
1020 matchfn = match.matchfn
1021 matchfn = match.matchfn
1021 matchalways = match.always()
1022 matchalways = match.always()
1022 matchtdir = match.traversedir
1023 matchtdir = match.traversedir
1023 dmap = self._map
1024 dmap = self._map
1024 listdir = util.listdir
1025 listdir = util.listdir
1025 lstat = os.lstat
1026 lstat = os.lstat
1026 dirkind = stat.S_IFDIR
1027 dirkind = stat.S_IFDIR
1027 regkind = stat.S_IFREG
1028 regkind = stat.S_IFREG
1028 lnkkind = stat.S_IFLNK
1029 lnkkind = stat.S_IFLNK
1029 join = self._join
1030 join = self._join
1030
1031
1031 exact = skipstep3 = False
1032 exact = skipstep3 = False
1032 if match.isexact(): # match.exact
1033 if match.isexact(): # match.exact
1033 exact = True
1034 exact = True
1034 dirignore = util.always # skip step 2
1035 dirignore = util.always # skip step 2
1035 elif match.prefix(): # match.match, no patterns
1036 elif match.prefix(): # match.match, no patterns
1036 skipstep3 = True
1037 skipstep3 = True
1037
1038
1038 if not exact and self._checkcase:
1039 if not exact and self._checkcase:
1039 normalize = self._normalize
1040 normalize = self._normalize
1040 normalizefile = self._normalizefile
1041 normalizefile = self._normalizefile
1041 skipstep3 = False
1042 skipstep3 = False
1042 else:
1043 else:
1043 normalize = self._normalize
1044 normalize = self._normalize
1044 normalizefile = None
1045 normalizefile = None
1045
1046
1046 # step 1: find all explicit files
1047 # step 1: find all explicit files
1047 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1048 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1048 if matchtdir:
1049 if matchtdir:
1049 for d in work:
1050 for d in work:
1050 matchtdir(d[0])
1051 matchtdir(d[0])
1051 for d in dirsnotfound:
1052 for d in dirsnotfound:
1052 matchtdir(d)
1053 matchtdir(d)
1053
1054
1054 skipstep3 = skipstep3 and not (work or dirsnotfound)
1055 skipstep3 = skipstep3 and not (work or dirsnotfound)
1055 work = [d for d in work if not dirignore(d[0])]
1056 work = [d for d in work if not dirignore(d[0])]
1056
1057
1057 # step 2: visit subdirectories
1058 # step 2: visit subdirectories
1058 def traverse(work, alreadynormed):
1059 def traverse(work, alreadynormed):
1059 wadd = work.append
1060 wadd = work.append
1060 while work:
1061 while work:
1061 tracing.counter('dirstate.walk work', len(work))
1062 tracing.counter('dirstate.walk work', len(work))
1062 nd = work.pop()
1063 nd = work.pop()
1063 visitentries = match.visitchildrenset(nd)
1064 visitentries = match.visitchildrenset(nd)
1064 if not visitentries:
1065 if not visitentries:
1065 continue
1066 continue
1066 if visitentries == b'this' or visitentries == b'all':
1067 if visitentries == b'this' or visitentries == b'all':
1067 visitentries = None
1068 visitentries = None
1068 skip = None
1069 skip = None
1069 if nd != b'':
1070 if nd != b'':
1070 skip = b'.hg'
1071 skip = b'.hg'
1071 try:
1072 try:
1072 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1073 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1073 entries = listdir(join(nd), stat=True, skip=skip)
1074 entries = listdir(join(nd), stat=True, skip=skip)
1074 except (PermissionError, FileNotFoundError) as inst:
1075 except (PermissionError, FileNotFoundError) as inst:
1075 match.bad(
1076 match.bad(
1076 self.pathto(nd), encoding.strtolocal(inst.strerror)
1077 self.pathto(nd), encoding.strtolocal(inst.strerror)
1077 )
1078 )
1078 continue
1079 continue
1079 for f, kind, st in entries:
1080 for f, kind, st in entries:
1080 # Some matchers may return files in the visitentries set,
1081 # Some matchers may return files in the visitentries set,
1081 # instead of 'this', if the matcher explicitly mentions them
1082 # instead of 'this', if the matcher explicitly mentions them
1082 # and is not an exactmatcher. This is acceptable; we do not
1083 # and is not an exactmatcher. This is acceptable; we do not
1083 # make any hard assumptions about file-or-directory below
1084 # make any hard assumptions about file-or-directory below
1084 # based on the presence of `f` in visitentries. If
1085 # based on the presence of `f` in visitentries. If
1085 # visitchildrenset returned a set, we can always skip the
1086 # visitchildrenset returned a set, we can always skip the
1086 # entries *not* in the set it provided regardless of whether
1087 # entries *not* in the set it provided regardless of whether
1087 # they're actually a file or a directory.
1088 # they're actually a file or a directory.
1088 if visitentries and f not in visitentries:
1089 if visitentries and f not in visitentries:
1089 continue
1090 continue
1090 if normalizefile:
1091 if normalizefile:
1091 # even though f might be a directory, we're only
1092 # even though f might be a directory, we're only
1092 # interested in comparing it to files currently in the
1093 # interested in comparing it to files currently in the
1093 # dmap -- therefore normalizefile is enough
1094 # dmap -- therefore normalizefile is enough
1094 nf = normalizefile(
1095 nf = normalizefile(
1095 nd and (nd + b"/" + f) or f, True, True
1096 nd and (nd + b"/" + f) or f, True, True
1096 )
1097 )
1097 else:
1098 else:
1098 nf = nd and (nd + b"/" + f) or f
1099 nf = nd and (nd + b"/" + f) or f
1099 if nf not in results:
1100 if nf not in results:
1100 if kind == dirkind:
1101 if kind == dirkind:
1101 if not ignore(nf):
1102 if not ignore(nf):
1102 if matchtdir:
1103 if matchtdir:
1103 matchtdir(nf)
1104 matchtdir(nf)
1104 wadd(nf)
1105 wadd(nf)
1105 if nf in dmap and (matchalways or matchfn(nf)):
1106 if nf in dmap and (matchalways or matchfn(nf)):
1106 results[nf] = None
1107 results[nf] = None
1107 elif kind == regkind or kind == lnkkind:
1108 elif kind == regkind or kind == lnkkind:
1108 if nf in dmap:
1109 if nf in dmap:
1109 if matchalways or matchfn(nf):
1110 if matchalways or matchfn(nf):
1110 results[nf] = st
1111 results[nf] = st
1111 elif (matchalways or matchfn(nf)) and not ignore(
1112 elif (matchalways or matchfn(nf)) and not ignore(
1112 nf
1113 nf
1113 ):
1114 ):
1114 # unknown file -- normalize if necessary
1115 # unknown file -- normalize if necessary
1115 if not alreadynormed:
1116 if not alreadynormed:
1116 nf = normalize(nf, False, True)
1117 nf = normalize(nf, False, True)
1117 results[nf] = st
1118 results[nf] = st
1118 elif nf in dmap and (matchalways or matchfn(nf)):
1119 elif nf in dmap and (matchalways or matchfn(nf)):
1119 results[nf] = None
1120 results[nf] = None
1120
1121
1121 for nd, d in work:
1122 for nd, d in work:
1122 # alreadynormed means that processwork doesn't have to do any
1123 # alreadynormed means that processwork doesn't have to do any
1123 # expensive directory normalization
1124 # expensive directory normalization
1124 alreadynormed = not normalize or nd == d
1125 alreadynormed = not normalize or nd == d
1125 traverse([d], alreadynormed)
1126 traverse([d], alreadynormed)
1126
1127
1127 for s in subrepos:
1128 for s in subrepos:
1128 del results[s]
1129 del results[s]
1129 del results[b'.hg']
1130 del results[b'.hg']
1130
1131
1131 # step 3: visit remaining files from dmap
1132 # step 3: visit remaining files from dmap
1132 if not skipstep3 and not exact:
1133 if not skipstep3 and not exact:
1133 # If a dmap file is not in results yet, it was either
1134 # If a dmap file is not in results yet, it was either
1134 # a) not matching matchfn b) ignored, c) missing, or d) under a
1135 # a) not matching matchfn b) ignored, c) missing, or d) under a
1135 # symlink directory.
1136 # symlink directory.
1136 if not results and matchalways:
1137 if not results and matchalways:
1137 visit = [f for f in dmap]
1138 visit = [f for f in dmap]
1138 else:
1139 else:
1139 visit = [f for f in dmap if f not in results and matchfn(f)]
1140 visit = [f for f in dmap if f not in results and matchfn(f)]
1140 visit.sort()
1141 visit.sort()
1141
1142
1142 if unknown:
1143 if unknown:
1143 # unknown == True means we walked all dirs under the roots
1144 # unknown == True means we walked all dirs under the roots
1144 # that wasn't ignored, and everything that matched was stat'ed
1145 # that wasn't ignored, and everything that matched was stat'ed
1145 # and is already in results.
1146 # and is already in results.
1146 # The rest must thus be ignored or under a symlink.
1147 # The rest must thus be ignored or under a symlink.
1147 audit_path = pathutil.pathauditor(self._root, cached=True)
1148 audit_path = pathutil.pathauditor(self._root, cached=True)
1148
1149
1149 for nf in iter(visit):
1150 for nf in iter(visit):
1150 # If a stat for the same file was already added with a
1151 # If a stat for the same file was already added with a
1151 # different case, don't add one for this, since that would
1152 # different case, don't add one for this, since that would
1152 # make it appear as if the file exists under both names
1153 # make it appear as if the file exists under both names
1153 # on disk.
1154 # on disk.
1154 if (
1155 if (
1155 normalizefile
1156 normalizefile
1156 and normalizefile(nf, True, True) in results
1157 and normalizefile(nf, True, True) in results
1157 ):
1158 ):
1158 results[nf] = None
1159 results[nf] = None
1159 # Report ignored items in the dmap as long as they are not
1160 # Report ignored items in the dmap as long as they are not
1160 # under a symlink directory.
1161 # under a symlink directory.
1161 elif audit_path.check(nf):
1162 elif audit_path.check(nf):
1162 try:
1163 try:
1163 results[nf] = lstat(join(nf))
1164 results[nf] = lstat(join(nf))
1164 # file was just ignored, no links, and exists
1165 # file was just ignored, no links, and exists
1165 except OSError:
1166 except OSError:
1166 # file doesn't exist
1167 # file doesn't exist
1167 results[nf] = None
1168 results[nf] = None
1168 else:
1169 else:
1169 # It's either missing or under a symlink directory
1170 # It's either missing or under a symlink directory
1170 # which we in this case report as missing
1171 # which we in this case report as missing
1171 results[nf] = None
1172 results[nf] = None
1172 else:
1173 else:
1173 # We may not have walked the full directory tree above,
1174 # We may not have walked the full directory tree above,
1174 # so stat and check everything we missed.
1175 # so stat and check everything we missed.
1175 iv = iter(visit)
1176 iv = iter(visit)
1176 for st in util.statfiles([join(i) for i in visit]):
1177 for st in util.statfiles([join(i) for i in visit]):
1177 results[next(iv)] = st
1178 results[next(iv)] = st
1178 return results
1179 return results
1179
1180
1180 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1181 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1181 if self._sparsematchfn is not None:
1182 if self._sparsematchfn is not None:
1182 em = matchmod.exact(matcher.files())
1183 em = matchmod.exact(matcher.files())
1183 sm = matchmod.unionmatcher([self._sparsematcher, em])
1184 sm = matchmod.unionmatcher([self._sparsematcher, em])
1184 matcher = matchmod.intersectmatchers(matcher, sm)
1185 matcher = matchmod.intersectmatchers(matcher, sm)
1185 # Force Rayon (Rust parallelism library) to respect the number of
1186 # Force Rayon (Rust parallelism library) to respect the number of
1186 # workers. This is a temporary workaround until Rust code knows
1187 # workers. This is a temporary workaround until Rust code knows
1187 # how to read the config file.
1188 # how to read the config file.
1188 numcpus = self._ui.configint(b"worker", b"numcpus")
1189 numcpus = self._ui.configint(b"worker", b"numcpus")
1189 if numcpus is not None:
1190 if numcpus is not None:
1190 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1191 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1191
1192
1192 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1193 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1193 if not workers_enabled:
1194 if not workers_enabled:
1194 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1195 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1195
1196
1196 (
1197 (
1197 lookup,
1198 lookup,
1198 modified,
1199 modified,
1199 added,
1200 added,
1200 removed,
1201 removed,
1201 deleted,
1202 deleted,
1202 clean,
1203 clean,
1203 ignored,
1204 ignored,
1204 unknown,
1205 unknown,
1205 warnings,
1206 warnings,
1206 bad,
1207 bad,
1207 traversed,
1208 traversed,
1208 dirty,
1209 dirty,
1209 ) = rustmod.status(
1210 ) = rustmod.status(
1210 self._map._map,
1211 self._map._map,
1211 matcher,
1212 matcher,
1212 self._rootdir,
1213 self._rootdir,
1213 self._ignorefiles(),
1214 self._ignorefiles(),
1214 self._checkexec,
1215 self._checkexec,
1215 bool(list_clean),
1216 bool(list_clean),
1216 bool(list_ignored),
1217 bool(list_ignored),
1217 bool(list_unknown),
1218 bool(list_unknown),
1218 bool(matcher.traversedir),
1219 bool(matcher.traversedir),
1219 )
1220 )
1220
1221
1221 self._dirty |= dirty
1222 self._dirty |= dirty
1222
1223
1223 if matcher.traversedir:
1224 if matcher.traversedir:
1224 for dir in traversed:
1225 for dir in traversed:
1225 matcher.traversedir(dir)
1226 matcher.traversedir(dir)
1226
1227
1227 if self._ui.warn:
1228 if self._ui.warn:
1228 for item in warnings:
1229 for item in warnings:
1229 if isinstance(item, tuple):
1230 if isinstance(item, tuple):
1230 file_path, syntax = item
1231 file_path, syntax = item
1231 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1232 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1232 file_path,
1233 file_path,
1233 syntax,
1234 syntax,
1234 )
1235 )
1235 self._ui.warn(msg)
1236 self._ui.warn(msg)
1236 else:
1237 else:
1237 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1238 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1238 self._ui.warn(
1239 self._ui.warn(
1239 msg
1240 msg
1240 % (
1241 % (
1241 pathutil.canonpath(
1242 pathutil.canonpath(
1242 self._rootdir, self._rootdir, item
1243 self._rootdir, self._rootdir, item
1243 ),
1244 ),
1244 b"No such file or directory",
1245 b"No such file or directory",
1245 )
1246 )
1246 )
1247 )
1247
1248
1248 for (fn, message) in bad:
1249 for (fn, message) in bad:
1249 matcher.bad(fn, encoding.strtolocal(message))
1250 matcher.bad(fn, encoding.strtolocal(message))
1250
1251
1251 status = scmutil.status(
1252 status = scmutil.status(
1252 modified=modified,
1253 modified=modified,
1253 added=added,
1254 added=added,
1254 removed=removed,
1255 removed=removed,
1255 deleted=deleted,
1256 deleted=deleted,
1256 unknown=unknown,
1257 unknown=unknown,
1257 ignored=ignored,
1258 ignored=ignored,
1258 clean=clean,
1259 clean=clean,
1259 )
1260 )
1260 return (lookup, status)
1261 return (lookup, status)
1261
1262
1262 def status(self, match, subrepos, ignored, clean, unknown):
1263 def status(self, match, subrepos, ignored, clean, unknown):
1263 """Determine the status of the working copy relative to the
1264 """Determine the status of the working copy relative to the
1264 dirstate and return a pair of (unsure, status), where status is of type
1265 dirstate and return a pair of (unsure, status), where status is of type
1265 scmutil.status and:
1266 scmutil.status and:
1266
1267
1267 unsure:
1268 unsure:
1268 files that might have been modified since the dirstate was
1269 files that might have been modified since the dirstate was
1269 written, but need to be read to be sure (size is the same
1270 written, but need to be read to be sure (size is the same
1270 but mtime differs)
1271 but mtime differs)
1271 status.modified:
1272 status.modified:
1272 files that have definitely been modified since the dirstate
1273 files that have definitely been modified since the dirstate
1273 was written (different size or mode)
1274 was written (different size or mode)
1274 status.clean:
1275 status.clean:
1275 files that have definitely not been modified since the
1276 files that have definitely not been modified since the
1276 dirstate was written
1277 dirstate was written
1277 """
1278 """
1278 listignored, listclean, listunknown = ignored, clean, unknown
1279 listignored, listclean, listunknown = ignored, clean, unknown
1279 lookup, modified, added, unknown, ignored = [], [], [], [], []
1280 lookup, modified, added, unknown, ignored = [], [], [], [], []
1280 removed, deleted, clean = [], [], []
1281 removed, deleted, clean = [], [], []
1281
1282
1282 dmap = self._map
1283 dmap = self._map
1283 dmap.preload()
1284 dmap.preload()
1284
1285
1285 use_rust = True
1286 use_rust = True
1286
1287
1287 allowed_matchers = (
1288 allowed_matchers = (
1288 matchmod.alwaysmatcher,
1289 matchmod.alwaysmatcher,
1289 matchmod.exactmatcher,
1290 matchmod.exactmatcher,
1290 matchmod.includematcher,
1291 matchmod.includematcher,
1291 matchmod.intersectionmatcher,
1292 matchmod.intersectionmatcher,
1292 matchmod.nevermatcher,
1293 matchmod.nevermatcher,
1293 matchmod.unionmatcher,
1294 matchmod.unionmatcher,
1294 )
1295 )
1295
1296
1296 if rustmod is None:
1297 if rustmod is None:
1297 use_rust = False
1298 use_rust = False
1298 elif self._checkcase:
1299 elif self._checkcase:
1299 # Case-insensitive filesystems are not handled yet
1300 # Case-insensitive filesystems are not handled yet
1300 use_rust = False
1301 use_rust = False
1301 elif subrepos:
1302 elif subrepos:
1302 use_rust = False
1303 use_rust = False
1303 elif not isinstance(match, allowed_matchers):
1304 elif not isinstance(match, allowed_matchers):
1304 # Some matchers have yet to be implemented
1305 # Some matchers have yet to be implemented
1305 use_rust = False
1306 use_rust = False
1306
1307
1307 # Get the time from the filesystem so we can disambiguate files that
1308 # Get the time from the filesystem so we can disambiguate files that
1308 # appear modified in the present or future.
1309 # appear modified in the present or future.
1309 try:
1310 try:
1310 mtime_boundary = timestamp.get_fs_now(self._opener)
1311 mtime_boundary = timestamp.get_fs_now(self._opener)
1311 except OSError:
1312 except OSError:
1312 # In largefiles or readonly context
1313 # In largefiles or readonly context
1313 mtime_boundary = None
1314 mtime_boundary = None
1314
1315
1315 if use_rust:
1316 if use_rust:
1316 try:
1317 try:
1317 res = self._rust_status(
1318 res = self._rust_status(
1318 match, listclean, listignored, listunknown
1319 match, listclean, listignored, listunknown
1319 )
1320 )
1320 return res + (mtime_boundary,)
1321 return res + (mtime_boundary,)
1321 except rustmod.FallbackError:
1322 except rustmod.FallbackError:
1322 pass
1323 pass
1323
1324
1324 def noop(f):
1325 def noop(f):
1325 pass
1326 pass
1326
1327
1327 dcontains = dmap.__contains__
1328 dcontains = dmap.__contains__
1328 dget = dmap.__getitem__
1329 dget = dmap.__getitem__
1329 ladd = lookup.append # aka "unsure"
1330 ladd = lookup.append # aka "unsure"
1330 madd = modified.append
1331 madd = modified.append
1331 aadd = added.append
1332 aadd = added.append
1332 uadd = unknown.append if listunknown else noop
1333 uadd = unknown.append if listunknown else noop
1333 iadd = ignored.append if listignored else noop
1334 iadd = ignored.append if listignored else noop
1334 radd = removed.append
1335 radd = removed.append
1335 dadd = deleted.append
1336 dadd = deleted.append
1336 cadd = clean.append if listclean else noop
1337 cadd = clean.append if listclean else noop
1337 mexact = match.exact
1338 mexact = match.exact
1338 dirignore = self._dirignore
1339 dirignore = self._dirignore
1339 checkexec = self._checkexec
1340 checkexec = self._checkexec
1340 checklink = self._checklink
1341 checklink = self._checklink
1341 copymap = self._map.copymap
1342 copymap = self._map.copymap
1342
1343
1343 # We need to do full walks when either
1344 # We need to do full walks when either
1344 # - we're listing all clean files, or
1345 # - we're listing all clean files, or
1345 # - match.traversedir does something, because match.traversedir should
1346 # - match.traversedir does something, because match.traversedir should
1346 # be called for every dir in the working dir
1347 # be called for every dir in the working dir
1347 full = listclean or match.traversedir is not None
1348 full = listclean or match.traversedir is not None
1348 for fn, st in self.walk(
1349 for fn, st in self.walk(
1349 match, subrepos, listunknown, listignored, full=full
1350 match, subrepos, listunknown, listignored, full=full
1350 ).items():
1351 ).items():
1351 if not dcontains(fn):
1352 if not dcontains(fn):
1352 if (listignored or mexact(fn)) and dirignore(fn):
1353 if (listignored or mexact(fn)) and dirignore(fn):
1353 if listignored:
1354 if listignored:
1354 iadd(fn)
1355 iadd(fn)
1355 else:
1356 else:
1356 uadd(fn)
1357 uadd(fn)
1357 continue
1358 continue
1358
1359
1359 t = dget(fn)
1360 t = dget(fn)
1360 mode = t.mode
1361 mode = t.mode
1361 size = t.size
1362 size = t.size
1362
1363
1363 if not st and t.tracked:
1364 if not st and t.tracked:
1364 dadd(fn)
1365 dadd(fn)
1365 elif t.p2_info:
1366 elif t.p2_info:
1366 madd(fn)
1367 madd(fn)
1367 elif t.added:
1368 elif t.added:
1368 aadd(fn)
1369 aadd(fn)
1369 elif t.removed:
1370 elif t.removed:
1370 radd(fn)
1371 radd(fn)
1371 elif t.tracked:
1372 elif t.tracked:
1372 if not checklink and t.has_fallback_symlink:
1373 if not checklink and t.has_fallback_symlink:
1373 # If the file system does not support symlink, the mode
1374 # If the file system does not support symlink, the mode
1374 # might not be correctly stored in the dirstate, so do not
1375 # might not be correctly stored in the dirstate, so do not
1375 # trust it.
1376 # trust it.
1376 ladd(fn)
1377 ladd(fn)
1377 elif not checkexec and t.has_fallback_exec:
1378 elif not checkexec and t.has_fallback_exec:
1378 # If the file system does not support exec bits, the mode
1379 # If the file system does not support exec bits, the mode
1379 # might not be correctly stored in the dirstate, so do not
1380 # might not be correctly stored in the dirstate, so do not
1380 # trust it.
1381 # trust it.
1381 ladd(fn)
1382 ladd(fn)
1382 elif (
1383 elif (
1383 size >= 0
1384 size >= 0
1384 and (
1385 and (
1385 (size != st.st_size and size != st.st_size & _rangemask)
1386 (size != st.st_size and size != st.st_size & _rangemask)
1386 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1387 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1387 )
1388 )
1388 or fn in copymap
1389 or fn in copymap
1389 ):
1390 ):
1390 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1391 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1391 # issue6456: Size returned may be longer due to
1392 # issue6456: Size returned may be longer due to
1392 # encryption on EXT-4 fscrypt, undecided.
1393 # encryption on EXT-4 fscrypt, undecided.
1393 ladd(fn)
1394 ladd(fn)
1394 else:
1395 else:
1395 madd(fn)
1396 madd(fn)
1396 elif not t.mtime_likely_equal_to(timestamp.mtime_of(st)):
1397 elif not t.mtime_likely_equal_to(timestamp.mtime_of(st)):
1397 # There might be a change in the future if for example the
1398 # There might be a change in the future if for example the
1398 # internal clock is off, but this is a case where the issues
1399 # internal clock is off, but this is a case where the issues
1399 # the user would face would be a lot worse and there is
1400 # the user would face would be a lot worse and there is
1400 # nothing we can really do.
1401 # nothing we can really do.
1401 ladd(fn)
1402 ladd(fn)
1402 elif listclean:
1403 elif listclean:
1403 cadd(fn)
1404 cadd(fn)
1404 status = scmutil.status(
1405 status = scmutil.status(
1405 modified, added, removed, deleted, unknown, ignored, clean
1406 modified, added, removed, deleted, unknown, ignored, clean
1406 )
1407 )
1407 return (lookup, status, mtime_boundary)
1408 return (lookup, status, mtime_boundary)
1408
1409
1409 def matches(self, match):
1410 def matches(self, match):
1410 """
1411 """
1411 return files in the dirstate (in whatever state) filtered by match
1412 return files in the dirstate (in whatever state) filtered by match
1412 """
1413 """
1413 dmap = self._map
1414 dmap = self._map
1414 if rustmod is not None:
1415 if rustmod is not None:
1415 dmap = self._map._map
1416 dmap = self._map._map
1416
1417
1417 if match.always():
1418 if match.always():
1418 return dmap.keys()
1419 return dmap.keys()
1419 files = match.files()
1420 files = match.files()
1420 if match.isexact():
1421 if match.isexact():
1421 # fast path -- filter the other way around, since typically files is
1422 # fast path -- filter the other way around, since typically files is
1422 # much smaller than dmap
1423 # much smaller than dmap
1423 return [f for f in files if f in dmap]
1424 return [f for f in files if f in dmap]
1424 if match.prefix() and all(fn in dmap for fn in files):
1425 if match.prefix() and all(fn in dmap for fn in files):
1425 # fast path -- all the values are known to be files, so just return
1426 # fast path -- all the values are known to be files, so just return
1426 # that
1427 # that
1427 return list(files)
1428 return list(files)
1428 return [f for f in dmap if match(f)]
1429 return [f for f in dmap if match(f)]
1429
1430
1430 def _actualfilename(self, tr):
1431 def _actualfilename(self, tr):
1431 if tr:
1432 if tr:
1432 return self._pendingfilename
1433 return self._pendingfilename
1433 else:
1434 else:
1434 return self._filename
1435 return self._filename
1435
1436
1437 def data_backup_filename(self, backupname):
1438 if not self._use_dirstate_v2:
1439 return None
1440 return backupname + b'.v2-data'
1441
1442 def _new_backup_data_filename(self, backupname):
1443 """return a filename to backup a data-file or None"""
1444 if not self._use_dirstate_v2:
1445 return None
1446 data_filename = self._map.docket.data_filename()
1447 return data_filename, self.data_backup_filename(backupname)
1448
1449 def backup_data_file(self, backupname):
1450 if not self._use_dirstate_v2:
1451 return None
1452 docket = docketmod.DirstateDocket.parse(
1453 self._opener.read(backupname),
1454 self._nodeconstants,
1455 )
1456 return self.data_backup_filename(backupname), docket.data_filename()
1457
1436 def savebackup(self, tr, backupname):
1458 def savebackup(self, tr, backupname):
1437 '''Save current dirstate into backup file'''
1459 '''Save current dirstate into backup file'''
1438 filename = self._actualfilename(tr)
1460 filename = self._actualfilename(tr)
1439 assert backupname != filename
1461 assert backupname != filename
1440
1462
1441 # use '_writedirstate' instead of 'write' to write changes certainly,
1463 # use '_writedirstate' instead of 'write' to write changes certainly,
1442 # because the latter omits writing out if transaction is running.
1464 # because the latter omits writing out if transaction is running.
1443 # output file will be used to create backup of dirstate at this point.
1465 # output file will be used to create backup of dirstate at this point.
1444 if self._dirty or not self._opener.exists(filename):
1466 if self._dirty or not self._opener.exists(filename):
1445 self._writedirstate(
1467 self._writedirstate(
1446 tr,
1468 tr,
1447 self._opener(filename, b"w", atomictemp=True, checkambig=True),
1469 self._opener(filename, b"w", atomictemp=True, checkambig=True),
1448 )
1470 )
1449
1471
1450 if tr:
1472 if tr:
1451 # ensure that subsequent tr.writepending returns True for
1473 # ensure that subsequent tr.writepending returns True for
1452 # changes written out above, even if dirstate is never
1474 # changes written out above, even if dirstate is never
1453 # changed after this
1475 # changed after this
1454 tr.addfilegenerator(
1476 tr.addfilegenerator(
1455 b'dirstate-1-main',
1477 b'dirstate-1-main',
1456 (self._filename,),
1478 (self._filename,),
1457 lambda f: self._writedirstate(tr, f),
1479 lambda f: self._writedirstate(tr, f),
1458 location=b'plain',
1480 location=b'plain',
1459 post_finalize=True,
1481 post_finalize=True,
1460 )
1482 )
1461
1483
1462 # ensure that pending file written above is unlinked at
1484 # ensure that pending file written above is unlinked at
1463 # failure, even if tr.writepending isn't invoked until the
1485 # failure, even if tr.writepending isn't invoked until the
1464 # end of this transaction
1486 # end of this transaction
1465 tr.registertmp(filename, location=b'plain')
1487 tr.registertmp(filename, location=b'plain')
1466
1488
1467 self._opener.tryunlink(backupname)
1489 self._opener.tryunlink(backupname)
1468 # hardlink backup is okay because _writedirstate is always called
1490 # hardlink backup is okay because _writedirstate is always called
1469 # with an "atomictemp=True" file.
1491 # with an "atomictemp=True" file.
1470 util.copyfile(
1492 util.copyfile(
1471 self._opener.join(filename),
1493 self._opener.join(filename),
1472 self._opener.join(backupname),
1494 self._opener.join(backupname),
1473 hardlink=True,
1495 hardlink=True,
1474 )
1496 )
1497 data_pair = self._new_backup_data_filename(backupname)
1498 if data_pair is not None:
1499 data_filename, bck_data_filename = data_pair
1500 util.copyfile(
1501 self._opener.join(data_filename),
1502 self._opener.join(bck_data_filename),
1503 hardlink=True,
1504 )
1505 if tr is not None:
1506 # ensure that pending file written above is unlinked at
1507 # failure, even if tr.writepending isn't invoked until the
1508 # end of this transaction
1509 tr.registertmp(bck_data_filename, location=b'plain')
1475
1510
1476 def restorebackup(self, tr, backupname):
1511 def restorebackup(self, tr, backupname):
1477 '''Restore dirstate by backup file'''
1512 '''Restore dirstate by backup file'''
1478 # this "invalidate()" prevents "wlock.release()" from writing
1513 # this "invalidate()" prevents "wlock.release()" from writing
1479 # changes of dirstate out after restoring from backup file
1514 # changes of dirstate out after restoring from backup file
1480 self.invalidate()
1515 self.invalidate()
1481 filename = self._actualfilename(tr)
1516 filename = self._actualfilename(tr)
1482 o = self._opener
1517 o = self._opener
1518 data_pair = self.backup_data_file(backupname)
1483 if util.samefile(o.join(backupname), o.join(filename)):
1519 if util.samefile(o.join(backupname), o.join(filename)):
1484 o.unlink(backupname)
1520 o.unlink(backupname)
1485 else:
1521 else:
1486 o.rename(backupname, filename, checkambig=True)
1522 o.rename(backupname, filename, checkambig=True)
1487
1523
1524 if data_pair is not None:
1525 data_backup, target = data_pair
1526 if o.exists(target) and util.samefile(
1527 o.join(data_backup), o.join(target)
1528 ):
1529 o.unlink(data_backup)
1530 else:
1531 o.rename(data_backup, target, checkambig=True)
1532
1488 def clearbackup(self, tr, backupname):
1533 def clearbackup(self, tr, backupname):
1489 '''Clear backup file'''
1534 '''Clear backup file'''
1490 self._opener.unlink(backupname)
1535 o = self._opener
1536 data_backup = self.backup_data_file(backupname)
1537 o.unlink(backupname)
1538
1539 if data_backup is not None:
1540 o.unlink(data_backup[0])
1491
1541
1492 def verify(self, m1, m2):
1542 def verify(self, m1, m2):
1493 """check the dirstate content again the parent manifest and yield errors"""
1543 """check the dirstate content again the parent manifest and yield errors"""
1494 missing_from_p1 = b"%s in state %s, but not in manifest1\n"
1544 missing_from_p1 = b"%s in state %s, but not in manifest1\n"
1495 unexpected_in_p1 = b"%s in state %s, but also in manifest1\n"
1545 unexpected_in_p1 = b"%s in state %s, but also in manifest1\n"
1496 missing_from_ps = b"%s in state %s, but not in either manifest\n"
1546 missing_from_ps = b"%s in state %s, but not in either manifest\n"
1497 missing_from_ds = b"%s in manifest1, but listed as state %s\n"
1547 missing_from_ds = b"%s in manifest1, but listed as state %s\n"
1498 for f, entry in self.items():
1548 for f, entry in self.items():
1499 state = entry.state
1549 state = entry.state
1500 if state in b"nr" and f not in m1:
1550 if state in b"nr" and f not in m1:
1501 yield (missing_from_p1, f, state)
1551 yield (missing_from_p1, f, state)
1502 if state in b"a" and f in m1:
1552 if state in b"a" and f in m1:
1503 yield (unexpected_in_p1, f, state)
1553 yield (unexpected_in_p1, f, state)
1504 if state in b"m" and f not in m1 and f not in m2:
1554 if state in b"m" and f not in m1 and f not in m2:
1505 yield (missing_from_ps, f, state)
1555 yield (missing_from_ps, f, state)
1506 for f in m1:
1556 for f in m1:
1507 state = self.get_entry(f).state
1557 state = self.get_entry(f).state
1508 if state not in b"nrm":
1558 if state not in b"nrm":
1509 yield (missing_from_ds, f, state)
1559 yield (missing_from_ds, f, state)
@@ -1,3946 +1,3953 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 # coding: utf-8
2 # coding: utf-8
3 #
3 #
4 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
4 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9
9
10 import functools
10 import functools
11 import os
11 import os
12 import random
12 import random
13 import sys
13 import sys
14 import time
14 import time
15 import weakref
15 import weakref
16
16
17 from concurrent import futures
17 from concurrent import futures
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 nullrev,
22 nullrev,
23 sha1nodeconstants,
23 sha1nodeconstants,
24 short,
24 short,
25 )
25 )
26 from .pycompat import (
26 from .pycompat import (
27 delattr,
27 delattr,
28 getattr,
28 getattr,
29 )
29 )
30 from . import (
30 from . import (
31 bookmarks,
31 bookmarks,
32 branchmap,
32 branchmap,
33 bundle2,
33 bundle2,
34 bundlecaches,
34 bundlecaches,
35 changegroup,
35 changegroup,
36 color,
36 color,
37 commit,
37 commit,
38 context,
38 context,
39 dirstate,
39 dirstate,
40 dirstateguard,
40 dirstateguard,
41 discovery,
41 discovery,
42 encoding,
42 encoding,
43 error,
43 error,
44 exchange,
44 exchange,
45 extensions,
45 extensions,
46 filelog,
46 filelog,
47 hook,
47 hook,
48 lock as lockmod,
48 lock as lockmod,
49 match as matchmod,
49 match as matchmod,
50 mergestate as mergestatemod,
50 mergestate as mergestatemod,
51 mergeutil,
51 mergeutil,
52 namespaces,
52 namespaces,
53 narrowspec,
53 narrowspec,
54 obsolete,
54 obsolete,
55 pathutil,
55 pathutil,
56 phases,
56 phases,
57 pushkey,
57 pushkey,
58 pycompat,
58 pycompat,
59 rcutil,
59 rcutil,
60 repoview,
60 repoview,
61 requirements as requirementsmod,
61 requirements as requirementsmod,
62 revlog,
62 revlog,
63 revset,
63 revset,
64 revsetlang,
64 revsetlang,
65 scmutil,
65 scmutil,
66 sparse,
66 sparse,
67 store as storemod,
67 store as storemod,
68 subrepoutil,
68 subrepoutil,
69 tags as tagsmod,
69 tags as tagsmod,
70 transaction,
70 transaction,
71 txnutil,
71 txnutil,
72 util,
72 util,
73 vfs as vfsmod,
73 vfs as vfsmod,
74 wireprototypes,
74 wireprototypes,
75 )
75 )
76
76
77 from .interfaces import (
77 from .interfaces import (
78 repository,
78 repository,
79 util as interfaceutil,
79 util as interfaceutil,
80 )
80 )
81
81
82 from .utils import (
82 from .utils import (
83 hashutil,
83 hashutil,
84 procutil,
84 procutil,
85 stringutil,
85 stringutil,
86 urlutil,
86 urlutil,
87 )
87 )
88
88
89 from .revlogutils import (
89 from .revlogutils import (
90 concurrency_checker as revlogchecker,
90 concurrency_checker as revlogchecker,
91 constants as revlogconst,
91 constants as revlogconst,
92 sidedata as sidedatamod,
92 sidedata as sidedatamod,
93 )
93 )
94
94
95 release = lockmod.release
95 release = lockmod.release
96 urlerr = util.urlerr
96 urlerr = util.urlerr
97 urlreq = util.urlreq
97 urlreq = util.urlreq
98
98
99 # set of (path, vfs-location) tuples. vfs-location is:
99 # set of (path, vfs-location) tuples. vfs-location is:
100 # - 'plain for vfs relative paths
100 # - 'plain for vfs relative paths
101 # - '' for svfs relative paths
101 # - '' for svfs relative paths
102 _cachedfiles = set()
102 _cachedfiles = set()
103
103
104
104
105 class _basefilecache(scmutil.filecache):
105 class _basefilecache(scmutil.filecache):
106 """All filecache usage on repo are done for logic that should be unfiltered"""
106 """All filecache usage on repo are done for logic that should be unfiltered"""
107
107
108 def __get__(self, repo, type=None):
108 def __get__(self, repo, type=None):
109 if repo is None:
109 if repo is None:
110 return self
110 return self
111 # proxy to unfiltered __dict__ since filtered repo has no entry
111 # proxy to unfiltered __dict__ since filtered repo has no entry
112 unfi = repo.unfiltered()
112 unfi = repo.unfiltered()
113 try:
113 try:
114 return unfi.__dict__[self.sname]
114 return unfi.__dict__[self.sname]
115 except KeyError:
115 except KeyError:
116 pass
116 pass
117 return super(_basefilecache, self).__get__(unfi, type)
117 return super(_basefilecache, self).__get__(unfi, type)
118
118
119 def set(self, repo, value):
119 def set(self, repo, value):
120 return super(_basefilecache, self).set(repo.unfiltered(), value)
120 return super(_basefilecache, self).set(repo.unfiltered(), value)
121
121
122
122
123 class repofilecache(_basefilecache):
123 class repofilecache(_basefilecache):
124 """filecache for files in .hg but outside of .hg/store"""
124 """filecache for files in .hg but outside of .hg/store"""
125
125
126 def __init__(self, *paths):
126 def __init__(self, *paths):
127 super(repofilecache, self).__init__(*paths)
127 super(repofilecache, self).__init__(*paths)
128 for path in paths:
128 for path in paths:
129 _cachedfiles.add((path, b'plain'))
129 _cachedfiles.add((path, b'plain'))
130
130
131 def join(self, obj, fname):
131 def join(self, obj, fname):
132 return obj.vfs.join(fname)
132 return obj.vfs.join(fname)
133
133
134
134
135 class storecache(_basefilecache):
135 class storecache(_basefilecache):
136 """filecache for files in the store"""
136 """filecache for files in the store"""
137
137
138 def __init__(self, *paths):
138 def __init__(self, *paths):
139 super(storecache, self).__init__(*paths)
139 super(storecache, self).__init__(*paths)
140 for path in paths:
140 for path in paths:
141 _cachedfiles.add((path, b''))
141 _cachedfiles.add((path, b''))
142
142
143 def join(self, obj, fname):
143 def join(self, obj, fname):
144 return obj.sjoin(fname)
144 return obj.sjoin(fname)
145
145
146
146
147 class changelogcache(storecache):
147 class changelogcache(storecache):
148 """filecache for the changelog"""
148 """filecache for the changelog"""
149
149
150 def __init__(self):
150 def __init__(self):
151 super(changelogcache, self).__init__()
151 super(changelogcache, self).__init__()
152 _cachedfiles.add((b'00changelog.i', b''))
152 _cachedfiles.add((b'00changelog.i', b''))
153 _cachedfiles.add((b'00changelog.n', b''))
153 _cachedfiles.add((b'00changelog.n', b''))
154
154
155 def tracked_paths(self, obj):
155 def tracked_paths(self, obj):
156 paths = [self.join(obj, b'00changelog.i')]
156 paths = [self.join(obj, b'00changelog.i')]
157 if obj.store.opener.options.get(b'persistent-nodemap', False):
157 if obj.store.opener.options.get(b'persistent-nodemap', False):
158 paths.append(self.join(obj, b'00changelog.n'))
158 paths.append(self.join(obj, b'00changelog.n'))
159 return paths
159 return paths
160
160
161
161
162 class manifestlogcache(storecache):
162 class manifestlogcache(storecache):
163 """filecache for the manifestlog"""
163 """filecache for the manifestlog"""
164
164
165 def __init__(self):
165 def __init__(self):
166 super(manifestlogcache, self).__init__()
166 super(manifestlogcache, self).__init__()
167 _cachedfiles.add((b'00manifest.i', b''))
167 _cachedfiles.add((b'00manifest.i', b''))
168 _cachedfiles.add((b'00manifest.n', b''))
168 _cachedfiles.add((b'00manifest.n', b''))
169
169
170 def tracked_paths(self, obj):
170 def tracked_paths(self, obj):
171 paths = [self.join(obj, b'00manifest.i')]
171 paths = [self.join(obj, b'00manifest.i')]
172 if obj.store.opener.options.get(b'persistent-nodemap', False):
172 if obj.store.opener.options.get(b'persistent-nodemap', False):
173 paths.append(self.join(obj, b'00manifest.n'))
173 paths.append(self.join(obj, b'00manifest.n'))
174 return paths
174 return paths
175
175
176
176
177 class mixedrepostorecache(_basefilecache):
177 class mixedrepostorecache(_basefilecache):
178 """filecache for a mix files in .hg/store and outside"""
178 """filecache for a mix files in .hg/store and outside"""
179
179
180 def __init__(self, *pathsandlocations):
180 def __init__(self, *pathsandlocations):
181 # scmutil.filecache only uses the path for passing back into our
181 # scmutil.filecache only uses the path for passing back into our
182 # join(), so we can safely pass a list of paths and locations
182 # join(), so we can safely pass a list of paths and locations
183 super(mixedrepostorecache, self).__init__(*pathsandlocations)
183 super(mixedrepostorecache, self).__init__(*pathsandlocations)
184 _cachedfiles.update(pathsandlocations)
184 _cachedfiles.update(pathsandlocations)
185
185
186 def join(self, obj, fnameandlocation):
186 def join(self, obj, fnameandlocation):
187 fname, location = fnameandlocation
187 fname, location = fnameandlocation
188 if location == b'plain':
188 if location == b'plain':
189 return obj.vfs.join(fname)
189 return obj.vfs.join(fname)
190 else:
190 else:
191 if location != b'':
191 if location != b'':
192 raise error.ProgrammingError(
192 raise error.ProgrammingError(
193 b'unexpected location: %s' % location
193 b'unexpected location: %s' % location
194 )
194 )
195 return obj.sjoin(fname)
195 return obj.sjoin(fname)
196
196
197
197
198 def isfilecached(repo, name):
198 def isfilecached(repo, name):
199 """check if a repo has already cached "name" filecache-ed property
199 """check if a repo has already cached "name" filecache-ed property
200
200
201 This returns (cachedobj-or-None, iscached) tuple.
201 This returns (cachedobj-or-None, iscached) tuple.
202 """
202 """
203 cacheentry = repo.unfiltered()._filecache.get(name, None)
203 cacheentry = repo.unfiltered()._filecache.get(name, None)
204 if not cacheentry:
204 if not cacheentry:
205 return None, False
205 return None, False
206 return cacheentry.obj, True
206 return cacheentry.obj, True
207
207
208
208
209 class unfilteredpropertycache(util.propertycache):
209 class unfilteredpropertycache(util.propertycache):
210 """propertycache that apply to unfiltered repo only"""
210 """propertycache that apply to unfiltered repo only"""
211
211
212 def __get__(self, repo, type=None):
212 def __get__(self, repo, type=None):
213 unfi = repo.unfiltered()
213 unfi = repo.unfiltered()
214 if unfi is repo:
214 if unfi is repo:
215 return super(unfilteredpropertycache, self).__get__(unfi)
215 return super(unfilteredpropertycache, self).__get__(unfi)
216 return getattr(unfi, self.name)
216 return getattr(unfi, self.name)
217
217
218
218
219 class filteredpropertycache(util.propertycache):
219 class filteredpropertycache(util.propertycache):
220 """propertycache that must take filtering in account"""
220 """propertycache that must take filtering in account"""
221
221
222 def cachevalue(self, obj, value):
222 def cachevalue(self, obj, value):
223 object.__setattr__(obj, self.name, value)
223 object.__setattr__(obj, self.name, value)
224
224
225
225
226 def hasunfilteredcache(repo, name):
226 def hasunfilteredcache(repo, name):
227 """check if a repo has an unfilteredpropertycache value for <name>"""
227 """check if a repo has an unfilteredpropertycache value for <name>"""
228 return name in vars(repo.unfiltered())
228 return name in vars(repo.unfiltered())
229
229
230
230
231 def unfilteredmethod(orig):
231 def unfilteredmethod(orig):
232 """decorate method that always need to be run on unfiltered version"""
232 """decorate method that always need to be run on unfiltered version"""
233
233
234 @functools.wraps(orig)
234 @functools.wraps(orig)
235 def wrapper(repo, *args, **kwargs):
235 def wrapper(repo, *args, **kwargs):
236 return orig(repo.unfiltered(), *args, **kwargs)
236 return orig(repo.unfiltered(), *args, **kwargs)
237
237
238 return wrapper
238 return wrapper
239
239
240
240
241 moderncaps = {
241 moderncaps = {
242 b'lookup',
242 b'lookup',
243 b'branchmap',
243 b'branchmap',
244 b'pushkey',
244 b'pushkey',
245 b'known',
245 b'known',
246 b'getbundle',
246 b'getbundle',
247 b'unbundle',
247 b'unbundle',
248 }
248 }
249 legacycaps = moderncaps.union({b'changegroupsubset'})
249 legacycaps = moderncaps.union({b'changegroupsubset'})
250
250
251
251
252 @interfaceutil.implementer(repository.ipeercommandexecutor)
252 @interfaceutil.implementer(repository.ipeercommandexecutor)
253 class localcommandexecutor:
253 class localcommandexecutor:
254 def __init__(self, peer):
254 def __init__(self, peer):
255 self._peer = peer
255 self._peer = peer
256 self._sent = False
256 self._sent = False
257 self._closed = False
257 self._closed = False
258
258
259 def __enter__(self):
259 def __enter__(self):
260 return self
260 return self
261
261
262 def __exit__(self, exctype, excvalue, exctb):
262 def __exit__(self, exctype, excvalue, exctb):
263 self.close()
263 self.close()
264
264
265 def callcommand(self, command, args):
265 def callcommand(self, command, args):
266 if self._sent:
266 if self._sent:
267 raise error.ProgrammingError(
267 raise error.ProgrammingError(
268 b'callcommand() cannot be used after sendcommands()'
268 b'callcommand() cannot be used after sendcommands()'
269 )
269 )
270
270
271 if self._closed:
271 if self._closed:
272 raise error.ProgrammingError(
272 raise error.ProgrammingError(
273 b'callcommand() cannot be used after close()'
273 b'callcommand() cannot be used after close()'
274 )
274 )
275
275
276 # We don't need to support anything fancy. Just call the named
276 # We don't need to support anything fancy. Just call the named
277 # method on the peer and return a resolved future.
277 # method on the peer and return a resolved future.
278 fn = getattr(self._peer, pycompat.sysstr(command))
278 fn = getattr(self._peer, pycompat.sysstr(command))
279
279
280 f = futures.Future()
280 f = futures.Future()
281
281
282 try:
282 try:
283 result = fn(**pycompat.strkwargs(args))
283 result = fn(**pycompat.strkwargs(args))
284 except Exception:
284 except Exception:
285 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
285 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
286 else:
286 else:
287 f.set_result(result)
287 f.set_result(result)
288
288
289 return f
289 return f
290
290
291 def sendcommands(self):
291 def sendcommands(self):
292 self._sent = True
292 self._sent = True
293
293
294 def close(self):
294 def close(self):
295 self._closed = True
295 self._closed = True
296
296
297
297
298 @interfaceutil.implementer(repository.ipeercommands)
298 @interfaceutil.implementer(repository.ipeercommands)
299 class localpeer(repository.peer):
299 class localpeer(repository.peer):
300 '''peer for a local repo; reflects only the most recent API'''
300 '''peer for a local repo; reflects only the most recent API'''
301
301
302 def __init__(self, repo, caps=None):
302 def __init__(self, repo, caps=None):
303 super(localpeer, self).__init__()
303 super(localpeer, self).__init__()
304
304
305 if caps is None:
305 if caps is None:
306 caps = moderncaps.copy()
306 caps = moderncaps.copy()
307 self._repo = repo.filtered(b'served')
307 self._repo = repo.filtered(b'served')
308 self.ui = repo.ui
308 self.ui = repo.ui
309
309
310 if repo._wanted_sidedata:
310 if repo._wanted_sidedata:
311 formatted = bundle2.format_remote_wanted_sidedata(repo)
311 formatted = bundle2.format_remote_wanted_sidedata(repo)
312 caps.add(b'exp-wanted-sidedata=' + formatted)
312 caps.add(b'exp-wanted-sidedata=' + formatted)
313
313
314 self._caps = repo._restrictcapabilities(caps)
314 self._caps = repo._restrictcapabilities(caps)
315
315
316 # Begin of _basepeer interface.
316 # Begin of _basepeer interface.
317
317
318 def url(self):
318 def url(self):
319 return self._repo.url()
319 return self._repo.url()
320
320
321 def local(self):
321 def local(self):
322 return self._repo
322 return self._repo
323
323
324 def peer(self):
324 def peer(self):
325 return self
325 return self
326
326
327 def canpush(self):
327 def canpush(self):
328 return True
328 return True
329
329
330 def close(self):
330 def close(self):
331 self._repo.close()
331 self._repo.close()
332
332
333 # End of _basepeer interface.
333 # End of _basepeer interface.
334
334
335 # Begin of _basewirecommands interface.
335 # Begin of _basewirecommands interface.
336
336
337 def branchmap(self):
337 def branchmap(self):
338 return self._repo.branchmap()
338 return self._repo.branchmap()
339
339
340 def capabilities(self):
340 def capabilities(self):
341 return self._caps
341 return self._caps
342
342
343 def clonebundles(self):
343 def clonebundles(self):
344 return self._repo.tryread(bundlecaches.CB_MANIFEST_FILE)
344 return self._repo.tryread(bundlecaches.CB_MANIFEST_FILE)
345
345
346 def debugwireargs(self, one, two, three=None, four=None, five=None):
346 def debugwireargs(self, one, two, three=None, four=None, five=None):
347 """Used to test argument passing over the wire"""
347 """Used to test argument passing over the wire"""
348 return b"%s %s %s %s %s" % (
348 return b"%s %s %s %s %s" % (
349 one,
349 one,
350 two,
350 two,
351 pycompat.bytestr(three),
351 pycompat.bytestr(three),
352 pycompat.bytestr(four),
352 pycompat.bytestr(four),
353 pycompat.bytestr(five),
353 pycompat.bytestr(five),
354 )
354 )
355
355
356 def getbundle(
356 def getbundle(
357 self,
357 self,
358 source,
358 source,
359 heads=None,
359 heads=None,
360 common=None,
360 common=None,
361 bundlecaps=None,
361 bundlecaps=None,
362 remote_sidedata=None,
362 remote_sidedata=None,
363 **kwargs
363 **kwargs
364 ):
364 ):
365 chunks = exchange.getbundlechunks(
365 chunks = exchange.getbundlechunks(
366 self._repo,
366 self._repo,
367 source,
367 source,
368 heads=heads,
368 heads=heads,
369 common=common,
369 common=common,
370 bundlecaps=bundlecaps,
370 bundlecaps=bundlecaps,
371 remote_sidedata=remote_sidedata,
371 remote_sidedata=remote_sidedata,
372 **kwargs
372 **kwargs
373 )[1]
373 )[1]
374 cb = util.chunkbuffer(chunks)
374 cb = util.chunkbuffer(chunks)
375
375
376 if exchange.bundle2requested(bundlecaps):
376 if exchange.bundle2requested(bundlecaps):
377 # When requesting a bundle2, getbundle returns a stream to make the
377 # When requesting a bundle2, getbundle returns a stream to make the
378 # wire level function happier. We need to build a proper object
378 # wire level function happier. We need to build a proper object
379 # from it in local peer.
379 # from it in local peer.
380 return bundle2.getunbundler(self.ui, cb)
380 return bundle2.getunbundler(self.ui, cb)
381 else:
381 else:
382 return changegroup.getunbundler(b'01', cb, None)
382 return changegroup.getunbundler(b'01', cb, None)
383
383
384 def heads(self):
384 def heads(self):
385 return self._repo.heads()
385 return self._repo.heads()
386
386
387 def known(self, nodes):
387 def known(self, nodes):
388 return self._repo.known(nodes)
388 return self._repo.known(nodes)
389
389
390 def listkeys(self, namespace):
390 def listkeys(self, namespace):
391 return self._repo.listkeys(namespace)
391 return self._repo.listkeys(namespace)
392
392
393 def lookup(self, key):
393 def lookup(self, key):
394 return self._repo.lookup(key)
394 return self._repo.lookup(key)
395
395
396 def pushkey(self, namespace, key, old, new):
396 def pushkey(self, namespace, key, old, new):
397 return self._repo.pushkey(namespace, key, old, new)
397 return self._repo.pushkey(namespace, key, old, new)
398
398
399 def stream_out(self):
399 def stream_out(self):
400 raise error.Abort(_(b'cannot perform stream clone against local peer'))
400 raise error.Abort(_(b'cannot perform stream clone against local peer'))
401
401
402 def unbundle(self, bundle, heads, url):
402 def unbundle(self, bundle, heads, url):
403 """apply a bundle on a repo
403 """apply a bundle on a repo
404
404
405 This function handles the repo locking itself."""
405 This function handles the repo locking itself."""
406 try:
406 try:
407 try:
407 try:
408 bundle = exchange.readbundle(self.ui, bundle, None)
408 bundle = exchange.readbundle(self.ui, bundle, None)
409 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
409 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
410 if util.safehasattr(ret, b'getchunks'):
410 if util.safehasattr(ret, b'getchunks'):
411 # This is a bundle20 object, turn it into an unbundler.
411 # This is a bundle20 object, turn it into an unbundler.
412 # This little dance should be dropped eventually when the
412 # This little dance should be dropped eventually when the
413 # API is finally improved.
413 # API is finally improved.
414 stream = util.chunkbuffer(ret.getchunks())
414 stream = util.chunkbuffer(ret.getchunks())
415 ret = bundle2.getunbundler(self.ui, stream)
415 ret = bundle2.getunbundler(self.ui, stream)
416 return ret
416 return ret
417 except Exception as exc:
417 except Exception as exc:
418 # If the exception contains output salvaged from a bundle2
418 # If the exception contains output salvaged from a bundle2
419 # reply, we need to make sure it is printed before continuing
419 # reply, we need to make sure it is printed before continuing
420 # to fail. So we build a bundle2 with such output and consume
420 # to fail. So we build a bundle2 with such output and consume
421 # it directly.
421 # it directly.
422 #
422 #
423 # This is not very elegant but allows a "simple" solution for
423 # This is not very elegant but allows a "simple" solution for
424 # issue4594
424 # issue4594
425 output = getattr(exc, '_bundle2salvagedoutput', ())
425 output = getattr(exc, '_bundle2salvagedoutput', ())
426 if output:
426 if output:
427 bundler = bundle2.bundle20(self._repo.ui)
427 bundler = bundle2.bundle20(self._repo.ui)
428 for out in output:
428 for out in output:
429 bundler.addpart(out)
429 bundler.addpart(out)
430 stream = util.chunkbuffer(bundler.getchunks())
430 stream = util.chunkbuffer(bundler.getchunks())
431 b = bundle2.getunbundler(self.ui, stream)
431 b = bundle2.getunbundler(self.ui, stream)
432 bundle2.processbundle(self._repo, b)
432 bundle2.processbundle(self._repo, b)
433 raise
433 raise
434 except error.PushRaced as exc:
434 except error.PushRaced as exc:
435 raise error.ResponseError(
435 raise error.ResponseError(
436 _(b'push failed:'), stringutil.forcebytestr(exc)
436 _(b'push failed:'), stringutil.forcebytestr(exc)
437 )
437 )
438
438
439 # End of _basewirecommands interface.
439 # End of _basewirecommands interface.
440
440
441 # Begin of peer interface.
441 # Begin of peer interface.
442
442
443 def commandexecutor(self):
443 def commandexecutor(self):
444 return localcommandexecutor(self)
444 return localcommandexecutor(self)
445
445
446 # End of peer interface.
446 # End of peer interface.
447
447
448
448
449 @interfaceutil.implementer(repository.ipeerlegacycommands)
449 @interfaceutil.implementer(repository.ipeerlegacycommands)
450 class locallegacypeer(localpeer):
450 class locallegacypeer(localpeer):
451 """peer extension which implements legacy methods too; used for tests with
451 """peer extension which implements legacy methods too; used for tests with
452 restricted capabilities"""
452 restricted capabilities"""
453
453
454 def __init__(self, repo):
454 def __init__(self, repo):
455 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
455 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
456
456
457 # Begin of baselegacywirecommands interface.
457 # Begin of baselegacywirecommands interface.
458
458
459 def between(self, pairs):
459 def between(self, pairs):
460 return self._repo.between(pairs)
460 return self._repo.between(pairs)
461
461
462 def branches(self, nodes):
462 def branches(self, nodes):
463 return self._repo.branches(nodes)
463 return self._repo.branches(nodes)
464
464
465 def changegroup(self, nodes, source):
465 def changegroup(self, nodes, source):
466 outgoing = discovery.outgoing(
466 outgoing = discovery.outgoing(
467 self._repo, missingroots=nodes, ancestorsof=self._repo.heads()
467 self._repo, missingroots=nodes, ancestorsof=self._repo.heads()
468 )
468 )
469 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
469 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
470
470
471 def changegroupsubset(self, bases, heads, source):
471 def changegroupsubset(self, bases, heads, source):
472 outgoing = discovery.outgoing(
472 outgoing = discovery.outgoing(
473 self._repo, missingroots=bases, ancestorsof=heads
473 self._repo, missingroots=bases, ancestorsof=heads
474 )
474 )
475 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
475 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
476
476
477 # End of baselegacywirecommands interface.
477 # End of baselegacywirecommands interface.
478
478
479
479
480 # Functions receiving (ui, features) that extensions can register to impact
480 # Functions receiving (ui, features) that extensions can register to impact
481 # the ability to load repositories with custom requirements. Only
481 # the ability to load repositories with custom requirements. Only
482 # functions defined in loaded extensions are called.
482 # functions defined in loaded extensions are called.
483 #
483 #
484 # The function receives a set of requirement strings that the repository
484 # The function receives a set of requirement strings that the repository
485 # is capable of opening. Functions will typically add elements to the
485 # is capable of opening. Functions will typically add elements to the
486 # set to reflect that the extension knows how to handle that requirements.
486 # set to reflect that the extension knows how to handle that requirements.
487 featuresetupfuncs = set()
487 featuresetupfuncs = set()
488
488
489
489
490 def _getsharedvfs(hgvfs, requirements):
490 def _getsharedvfs(hgvfs, requirements):
491 """returns the vfs object pointing to root of shared source
491 """returns the vfs object pointing to root of shared source
492 repo for a shared repository
492 repo for a shared repository
493
493
494 hgvfs is vfs pointing at .hg/ of current repo (shared one)
494 hgvfs is vfs pointing at .hg/ of current repo (shared one)
495 requirements is a set of requirements of current repo (shared one)
495 requirements is a set of requirements of current repo (shared one)
496 """
496 """
497 # The ``shared`` or ``relshared`` requirements indicate the
497 # The ``shared`` or ``relshared`` requirements indicate the
498 # store lives in the path contained in the ``.hg/sharedpath`` file.
498 # store lives in the path contained in the ``.hg/sharedpath`` file.
499 # This is an absolute path for ``shared`` and relative to
499 # This is an absolute path for ``shared`` and relative to
500 # ``.hg/`` for ``relshared``.
500 # ``.hg/`` for ``relshared``.
501 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
501 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
502 if requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements:
502 if requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements:
503 sharedpath = util.normpath(hgvfs.join(sharedpath))
503 sharedpath = util.normpath(hgvfs.join(sharedpath))
504
504
505 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
505 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
506
506
507 if not sharedvfs.exists():
507 if not sharedvfs.exists():
508 raise error.RepoError(
508 raise error.RepoError(
509 _(b'.hg/sharedpath points to nonexistent directory %s')
509 _(b'.hg/sharedpath points to nonexistent directory %s')
510 % sharedvfs.base
510 % sharedvfs.base
511 )
511 )
512 return sharedvfs
512 return sharedvfs
513
513
514
514
515 def _readrequires(vfs, allowmissing):
515 def _readrequires(vfs, allowmissing):
516 """reads the require file present at root of this vfs
516 """reads the require file present at root of this vfs
517 and return a set of requirements
517 and return a set of requirements
518
518
519 If allowmissing is True, we suppress FileNotFoundError if raised"""
519 If allowmissing is True, we suppress FileNotFoundError if raised"""
520 # requires file contains a newline-delimited list of
520 # requires file contains a newline-delimited list of
521 # features/capabilities the opener (us) must have in order to use
521 # features/capabilities the opener (us) must have in order to use
522 # the repository. This file was introduced in Mercurial 0.9.2,
522 # the repository. This file was introduced in Mercurial 0.9.2,
523 # which means very old repositories may not have one. We assume
523 # which means very old repositories may not have one. We assume
524 # a missing file translates to no requirements.
524 # a missing file translates to no requirements.
525 try:
525 try:
526 return set(vfs.read(b'requires').splitlines())
526 return set(vfs.read(b'requires').splitlines())
527 except FileNotFoundError:
527 except FileNotFoundError:
528 if not allowmissing:
528 if not allowmissing:
529 raise
529 raise
530 return set()
530 return set()
531
531
532
532
533 def makelocalrepository(baseui, path, intents=None):
533 def makelocalrepository(baseui, path, intents=None):
534 """Create a local repository object.
534 """Create a local repository object.
535
535
536 Given arguments needed to construct a local repository, this function
536 Given arguments needed to construct a local repository, this function
537 performs various early repository loading functionality (such as
537 performs various early repository loading functionality (such as
538 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
538 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
539 the repository can be opened, derives a type suitable for representing
539 the repository can be opened, derives a type suitable for representing
540 that repository, and returns an instance of it.
540 that repository, and returns an instance of it.
541
541
542 The returned object conforms to the ``repository.completelocalrepository``
542 The returned object conforms to the ``repository.completelocalrepository``
543 interface.
543 interface.
544
544
545 The repository type is derived by calling a series of factory functions
545 The repository type is derived by calling a series of factory functions
546 for each aspect/interface of the final repository. These are defined by
546 for each aspect/interface of the final repository. These are defined by
547 ``REPO_INTERFACES``.
547 ``REPO_INTERFACES``.
548
548
549 Each factory function is called to produce a type implementing a specific
549 Each factory function is called to produce a type implementing a specific
550 interface. The cumulative list of returned types will be combined into a
550 interface. The cumulative list of returned types will be combined into a
551 new type and that type will be instantiated to represent the local
551 new type and that type will be instantiated to represent the local
552 repository.
552 repository.
553
553
554 The factory functions each receive various state that may be consulted
554 The factory functions each receive various state that may be consulted
555 as part of deriving a type.
555 as part of deriving a type.
556
556
557 Extensions should wrap these factory functions to customize repository type
557 Extensions should wrap these factory functions to customize repository type
558 creation. Note that an extension's wrapped function may be called even if
558 creation. Note that an extension's wrapped function may be called even if
559 that extension is not loaded for the repo being constructed. Extensions
559 that extension is not loaded for the repo being constructed. Extensions
560 should check if their ``__name__`` appears in the
560 should check if their ``__name__`` appears in the
561 ``extensionmodulenames`` set passed to the factory function and no-op if
561 ``extensionmodulenames`` set passed to the factory function and no-op if
562 not.
562 not.
563 """
563 """
564 ui = baseui.copy()
564 ui = baseui.copy()
565 # Prevent copying repo configuration.
565 # Prevent copying repo configuration.
566 ui.copy = baseui.copy
566 ui.copy = baseui.copy
567
567
568 # Working directory VFS rooted at repository root.
568 # Working directory VFS rooted at repository root.
569 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
569 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
570
570
571 # Main VFS for .hg/ directory.
571 # Main VFS for .hg/ directory.
572 hgpath = wdirvfs.join(b'.hg')
572 hgpath = wdirvfs.join(b'.hg')
573 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
573 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
574 # Whether this repository is shared one or not
574 # Whether this repository is shared one or not
575 shared = False
575 shared = False
576 # If this repository is shared, vfs pointing to shared repo
576 # If this repository is shared, vfs pointing to shared repo
577 sharedvfs = None
577 sharedvfs = None
578
578
579 # The .hg/ path should exist and should be a directory. All other
579 # The .hg/ path should exist and should be a directory. All other
580 # cases are errors.
580 # cases are errors.
581 if not hgvfs.isdir():
581 if not hgvfs.isdir():
582 try:
582 try:
583 hgvfs.stat()
583 hgvfs.stat()
584 except FileNotFoundError:
584 except FileNotFoundError:
585 pass
585 pass
586 except ValueError as e:
586 except ValueError as e:
587 # Can be raised on Python 3.8 when path is invalid.
587 # Can be raised on Python 3.8 when path is invalid.
588 raise error.Abort(
588 raise error.Abort(
589 _(b'invalid path %s: %s') % (path, stringutil.forcebytestr(e))
589 _(b'invalid path %s: %s') % (path, stringutil.forcebytestr(e))
590 )
590 )
591
591
592 raise error.RepoError(_(b'repository %s not found') % path)
592 raise error.RepoError(_(b'repository %s not found') % path)
593
593
594 requirements = _readrequires(hgvfs, True)
594 requirements = _readrequires(hgvfs, True)
595 shared = (
595 shared = (
596 requirementsmod.SHARED_REQUIREMENT in requirements
596 requirementsmod.SHARED_REQUIREMENT in requirements
597 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
597 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
598 )
598 )
599 storevfs = None
599 storevfs = None
600 if shared:
600 if shared:
601 # This is a shared repo
601 # This is a shared repo
602 sharedvfs = _getsharedvfs(hgvfs, requirements)
602 sharedvfs = _getsharedvfs(hgvfs, requirements)
603 storevfs = vfsmod.vfs(sharedvfs.join(b'store'))
603 storevfs = vfsmod.vfs(sharedvfs.join(b'store'))
604 else:
604 else:
605 storevfs = vfsmod.vfs(hgvfs.join(b'store'))
605 storevfs = vfsmod.vfs(hgvfs.join(b'store'))
606
606
607 # if .hg/requires contains the sharesafe requirement, it means
607 # if .hg/requires contains the sharesafe requirement, it means
608 # there exists a `.hg/store/requires` too and we should read it
608 # there exists a `.hg/store/requires` too and we should read it
609 # NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
609 # NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
610 # is present. We never write SHARESAFE_REQUIREMENT for a repo if store
610 # is present. We never write SHARESAFE_REQUIREMENT for a repo if store
611 # is not present, refer checkrequirementscompat() for that
611 # is not present, refer checkrequirementscompat() for that
612 #
612 #
613 # However, if SHARESAFE_REQUIREMENT is not present, it means that the
613 # However, if SHARESAFE_REQUIREMENT is not present, it means that the
614 # repository was shared the old way. We check the share source .hg/requires
614 # repository was shared the old way. We check the share source .hg/requires
615 # for SHARESAFE_REQUIREMENT to detect whether the current repository needs
615 # for SHARESAFE_REQUIREMENT to detect whether the current repository needs
616 # to be reshared
616 # to be reshared
617 hint = _(b"see `hg help config.format.use-share-safe` for more information")
617 hint = _(b"see `hg help config.format.use-share-safe` for more information")
618 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
618 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
619
619
620 if (
620 if (
621 shared
621 shared
622 and requirementsmod.SHARESAFE_REQUIREMENT
622 and requirementsmod.SHARESAFE_REQUIREMENT
623 not in _readrequires(sharedvfs, True)
623 not in _readrequires(sharedvfs, True)
624 ):
624 ):
625 mismatch_warn = ui.configbool(
625 mismatch_warn = ui.configbool(
626 b'share', b'safe-mismatch.source-not-safe.warn'
626 b'share', b'safe-mismatch.source-not-safe.warn'
627 )
627 )
628 mismatch_config = ui.config(
628 mismatch_config = ui.config(
629 b'share', b'safe-mismatch.source-not-safe'
629 b'share', b'safe-mismatch.source-not-safe'
630 )
630 )
631 mismatch_verbose_upgrade = ui.configbool(
631 mismatch_verbose_upgrade = ui.configbool(
632 b'share', b'safe-mismatch.source-not-safe:verbose-upgrade'
632 b'share', b'safe-mismatch.source-not-safe:verbose-upgrade'
633 )
633 )
634 if mismatch_config in (
634 if mismatch_config in (
635 b'downgrade-allow',
635 b'downgrade-allow',
636 b'allow',
636 b'allow',
637 b'downgrade-abort',
637 b'downgrade-abort',
638 ):
638 ):
639 # prevent cyclic import localrepo -> upgrade -> localrepo
639 # prevent cyclic import localrepo -> upgrade -> localrepo
640 from . import upgrade
640 from . import upgrade
641
641
642 upgrade.downgrade_share_to_non_safe(
642 upgrade.downgrade_share_to_non_safe(
643 ui,
643 ui,
644 hgvfs,
644 hgvfs,
645 sharedvfs,
645 sharedvfs,
646 requirements,
646 requirements,
647 mismatch_config,
647 mismatch_config,
648 mismatch_warn,
648 mismatch_warn,
649 mismatch_verbose_upgrade,
649 mismatch_verbose_upgrade,
650 )
650 )
651 elif mismatch_config == b'abort':
651 elif mismatch_config == b'abort':
652 raise error.Abort(
652 raise error.Abort(
653 _(b"share source does not support share-safe requirement"),
653 _(b"share source does not support share-safe requirement"),
654 hint=hint,
654 hint=hint,
655 )
655 )
656 else:
656 else:
657 raise error.Abort(
657 raise error.Abort(
658 _(
658 _(
659 b"share-safe mismatch with source.\nUnrecognized"
659 b"share-safe mismatch with source.\nUnrecognized"
660 b" value '%s' of `share.safe-mismatch.source-not-safe`"
660 b" value '%s' of `share.safe-mismatch.source-not-safe`"
661 b" set."
661 b" set."
662 )
662 )
663 % mismatch_config,
663 % mismatch_config,
664 hint=hint,
664 hint=hint,
665 )
665 )
666 else:
666 else:
667 requirements |= _readrequires(storevfs, False)
667 requirements |= _readrequires(storevfs, False)
668 elif shared:
668 elif shared:
669 sourcerequires = _readrequires(sharedvfs, False)
669 sourcerequires = _readrequires(sharedvfs, False)
670 if requirementsmod.SHARESAFE_REQUIREMENT in sourcerequires:
670 if requirementsmod.SHARESAFE_REQUIREMENT in sourcerequires:
671 mismatch_config = ui.config(b'share', b'safe-mismatch.source-safe')
671 mismatch_config = ui.config(b'share', b'safe-mismatch.source-safe')
672 mismatch_warn = ui.configbool(
672 mismatch_warn = ui.configbool(
673 b'share', b'safe-mismatch.source-safe.warn'
673 b'share', b'safe-mismatch.source-safe.warn'
674 )
674 )
675 mismatch_verbose_upgrade = ui.configbool(
675 mismatch_verbose_upgrade = ui.configbool(
676 b'share', b'safe-mismatch.source-safe:verbose-upgrade'
676 b'share', b'safe-mismatch.source-safe:verbose-upgrade'
677 )
677 )
678 if mismatch_config in (
678 if mismatch_config in (
679 b'upgrade-allow',
679 b'upgrade-allow',
680 b'allow',
680 b'allow',
681 b'upgrade-abort',
681 b'upgrade-abort',
682 ):
682 ):
683 # prevent cyclic import localrepo -> upgrade -> localrepo
683 # prevent cyclic import localrepo -> upgrade -> localrepo
684 from . import upgrade
684 from . import upgrade
685
685
686 upgrade.upgrade_share_to_safe(
686 upgrade.upgrade_share_to_safe(
687 ui,
687 ui,
688 hgvfs,
688 hgvfs,
689 storevfs,
689 storevfs,
690 requirements,
690 requirements,
691 mismatch_config,
691 mismatch_config,
692 mismatch_warn,
692 mismatch_warn,
693 mismatch_verbose_upgrade,
693 mismatch_verbose_upgrade,
694 )
694 )
695 elif mismatch_config == b'abort':
695 elif mismatch_config == b'abort':
696 raise error.Abort(
696 raise error.Abort(
697 _(
697 _(
698 b'version mismatch: source uses share-safe'
698 b'version mismatch: source uses share-safe'
699 b' functionality while the current share does not'
699 b' functionality while the current share does not'
700 ),
700 ),
701 hint=hint,
701 hint=hint,
702 )
702 )
703 else:
703 else:
704 raise error.Abort(
704 raise error.Abort(
705 _(
705 _(
706 b"share-safe mismatch with source.\nUnrecognized"
706 b"share-safe mismatch with source.\nUnrecognized"
707 b" value '%s' of `share.safe-mismatch.source-safe` set."
707 b" value '%s' of `share.safe-mismatch.source-safe` set."
708 )
708 )
709 % mismatch_config,
709 % mismatch_config,
710 hint=hint,
710 hint=hint,
711 )
711 )
712
712
713 # The .hg/hgrc file may load extensions or contain config options
713 # The .hg/hgrc file may load extensions or contain config options
714 # that influence repository construction. Attempt to load it and
714 # that influence repository construction. Attempt to load it and
715 # process any new extensions that it may have pulled in.
715 # process any new extensions that it may have pulled in.
716 if loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs):
716 if loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs):
717 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
717 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
718 extensions.loadall(ui)
718 extensions.loadall(ui)
719 extensions.populateui(ui)
719 extensions.populateui(ui)
720
720
721 # Set of module names of extensions loaded for this repository.
721 # Set of module names of extensions loaded for this repository.
722 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
722 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
723
723
724 supportedrequirements = gathersupportedrequirements(ui)
724 supportedrequirements = gathersupportedrequirements(ui)
725
725
726 # We first validate the requirements are known.
726 # We first validate the requirements are known.
727 ensurerequirementsrecognized(requirements, supportedrequirements)
727 ensurerequirementsrecognized(requirements, supportedrequirements)
728
728
729 # Then we validate that the known set is reasonable to use together.
729 # Then we validate that the known set is reasonable to use together.
730 ensurerequirementscompatible(ui, requirements)
730 ensurerequirementscompatible(ui, requirements)
731
731
732 # TODO there are unhandled edge cases related to opening repositories with
732 # TODO there are unhandled edge cases related to opening repositories with
733 # shared storage. If storage is shared, we should also test for requirements
733 # shared storage. If storage is shared, we should also test for requirements
734 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
734 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
735 # that repo, as that repo may load extensions needed to open it. This is a
735 # that repo, as that repo may load extensions needed to open it. This is a
736 # bit complicated because we don't want the other hgrc to overwrite settings
736 # bit complicated because we don't want the other hgrc to overwrite settings
737 # in this hgrc.
737 # in this hgrc.
738 #
738 #
739 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
739 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
740 # file when sharing repos. But if a requirement is added after the share is
740 # file when sharing repos. But if a requirement is added after the share is
741 # performed, thereby introducing a new requirement for the opener, we may
741 # performed, thereby introducing a new requirement for the opener, we may
742 # will not see that and could encounter a run-time error interacting with
742 # will not see that and could encounter a run-time error interacting with
743 # that shared store since it has an unknown-to-us requirement.
743 # that shared store since it has an unknown-to-us requirement.
744
744
745 # At this point, we know we should be capable of opening the repository.
745 # At this point, we know we should be capable of opening the repository.
746 # Now get on with doing that.
746 # Now get on with doing that.
747
747
748 features = set()
748 features = set()
749
749
750 # The "store" part of the repository holds versioned data. How it is
750 # The "store" part of the repository holds versioned data. How it is
751 # accessed is determined by various requirements. If `shared` or
751 # accessed is determined by various requirements. If `shared` or
752 # `relshared` requirements are present, this indicates current repository
752 # `relshared` requirements are present, this indicates current repository
753 # is a share and store exists in path mentioned in `.hg/sharedpath`
753 # is a share and store exists in path mentioned in `.hg/sharedpath`
754 if shared:
754 if shared:
755 storebasepath = sharedvfs.base
755 storebasepath = sharedvfs.base
756 cachepath = sharedvfs.join(b'cache')
756 cachepath = sharedvfs.join(b'cache')
757 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
757 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
758 else:
758 else:
759 storebasepath = hgvfs.base
759 storebasepath = hgvfs.base
760 cachepath = hgvfs.join(b'cache')
760 cachepath = hgvfs.join(b'cache')
761 wcachepath = hgvfs.join(b'wcache')
761 wcachepath = hgvfs.join(b'wcache')
762
762
763 # The store has changed over time and the exact layout is dictated by
763 # The store has changed over time and the exact layout is dictated by
764 # requirements. The store interface abstracts differences across all
764 # requirements. The store interface abstracts differences across all
765 # of them.
765 # of them.
766 store = makestore(
766 store = makestore(
767 requirements,
767 requirements,
768 storebasepath,
768 storebasepath,
769 lambda base: vfsmod.vfs(base, cacheaudited=True),
769 lambda base: vfsmod.vfs(base, cacheaudited=True),
770 )
770 )
771 hgvfs.createmode = store.createmode
771 hgvfs.createmode = store.createmode
772
772
773 storevfs = store.vfs
773 storevfs = store.vfs
774 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
774 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
775
775
776 if (
776 if (
777 requirementsmod.REVLOGV2_REQUIREMENT in requirements
777 requirementsmod.REVLOGV2_REQUIREMENT in requirements
778 or requirementsmod.CHANGELOGV2_REQUIREMENT in requirements
778 or requirementsmod.CHANGELOGV2_REQUIREMENT in requirements
779 ):
779 ):
780 features.add(repository.REPO_FEATURE_SIDE_DATA)
780 features.add(repository.REPO_FEATURE_SIDE_DATA)
781 # the revlogv2 docket introduced race condition that we need to fix
781 # the revlogv2 docket introduced race condition that we need to fix
782 features.discard(repository.REPO_FEATURE_STREAM_CLONE)
782 features.discard(repository.REPO_FEATURE_STREAM_CLONE)
783
783
784 # The cache vfs is used to manage cache files.
784 # The cache vfs is used to manage cache files.
785 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
785 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
786 cachevfs.createmode = store.createmode
786 cachevfs.createmode = store.createmode
787 # The cache vfs is used to manage cache files related to the working copy
787 # The cache vfs is used to manage cache files related to the working copy
788 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
788 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
789 wcachevfs.createmode = store.createmode
789 wcachevfs.createmode = store.createmode
790
790
791 # Now resolve the type for the repository object. We do this by repeatedly
791 # Now resolve the type for the repository object. We do this by repeatedly
792 # calling a factory function to produces types for specific aspects of the
792 # calling a factory function to produces types for specific aspects of the
793 # repo's operation. The aggregate returned types are used as base classes
793 # repo's operation. The aggregate returned types are used as base classes
794 # for a dynamically-derived type, which will represent our new repository.
794 # for a dynamically-derived type, which will represent our new repository.
795
795
796 bases = []
796 bases = []
797 extrastate = {}
797 extrastate = {}
798
798
799 for iface, fn in REPO_INTERFACES:
799 for iface, fn in REPO_INTERFACES:
800 # We pass all potentially useful state to give extensions tons of
800 # We pass all potentially useful state to give extensions tons of
801 # flexibility.
801 # flexibility.
802 typ = fn()(
802 typ = fn()(
803 ui=ui,
803 ui=ui,
804 intents=intents,
804 intents=intents,
805 requirements=requirements,
805 requirements=requirements,
806 features=features,
806 features=features,
807 wdirvfs=wdirvfs,
807 wdirvfs=wdirvfs,
808 hgvfs=hgvfs,
808 hgvfs=hgvfs,
809 store=store,
809 store=store,
810 storevfs=storevfs,
810 storevfs=storevfs,
811 storeoptions=storevfs.options,
811 storeoptions=storevfs.options,
812 cachevfs=cachevfs,
812 cachevfs=cachevfs,
813 wcachevfs=wcachevfs,
813 wcachevfs=wcachevfs,
814 extensionmodulenames=extensionmodulenames,
814 extensionmodulenames=extensionmodulenames,
815 extrastate=extrastate,
815 extrastate=extrastate,
816 baseclasses=bases,
816 baseclasses=bases,
817 )
817 )
818
818
819 if not isinstance(typ, type):
819 if not isinstance(typ, type):
820 raise error.ProgrammingError(
820 raise error.ProgrammingError(
821 b'unable to construct type for %s' % iface
821 b'unable to construct type for %s' % iface
822 )
822 )
823
823
824 bases.append(typ)
824 bases.append(typ)
825
825
826 # type() allows you to use characters in type names that wouldn't be
826 # type() allows you to use characters in type names that wouldn't be
827 # recognized as Python symbols in source code. We abuse that to add
827 # recognized as Python symbols in source code. We abuse that to add
828 # rich information about our constructed repo.
828 # rich information about our constructed repo.
829 name = pycompat.sysstr(
829 name = pycompat.sysstr(
830 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
830 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
831 )
831 )
832
832
833 cls = type(name, tuple(bases), {})
833 cls = type(name, tuple(bases), {})
834
834
835 return cls(
835 return cls(
836 baseui=baseui,
836 baseui=baseui,
837 ui=ui,
837 ui=ui,
838 origroot=path,
838 origroot=path,
839 wdirvfs=wdirvfs,
839 wdirvfs=wdirvfs,
840 hgvfs=hgvfs,
840 hgvfs=hgvfs,
841 requirements=requirements,
841 requirements=requirements,
842 supportedrequirements=supportedrequirements,
842 supportedrequirements=supportedrequirements,
843 sharedpath=storebasepath,
843 sharedpath=storebasepath,
844 store=store,
844 store=store,
845 cachevfs=cachevfs,
845 cachevfs=cachevfs,
846 wcachevfs=wcachevfs,
846 wcachevfs=wcachevfs,
847 features=features,
847 features=features,
848 intents=intents,
848 intents=intents,
849 )
849 )
850
850
851
851
852 def loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs=None):
852 def loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs=None):
853 """Load hgrc files/content into a ui instance.
853 """Load hgrc files/content into a ui instance.
854
854
855 This is called during repository opening to load any additional
855 This is called during repository opening to load any additional
856 config files or settings relevant to the current repository.
856 config files or settings relevant to the current repository.
857
857
858 Returns a bool indicating whether any additional configs were loaded.
858 Returns a bool indicating whether any additional configs were loaded.
859
859
860 Extensions should monkeypatch this function to modify how per-repo
860 Extensions should monkeypatch this function to modify how per-repo
861 configs are loaded. For example, an extension may wish to pull in
861 configs are loaded. For example, an extension may wish to pull in
862 configs from alternate files or sources.
862 configs from alternate files or sources.
863
863
864 sharedvfs is vfs object pointing to source repo if the current one is a
864 sharedvfs is vfs object pointing to source repo if the current one is a
865 shared one
865 shared one
866 """
866 """
867 if not rcutil.use_repo_hgrc():
867 if not rcutil.use_repo_hgrc():
868 return False
868 return False
869
869
870 ret = False
870 ret = False
871 # first load config from shared source if we has to
871 # first load config from shared source if we has to
872 if requirementsmod.SHARESAFE_REQUIREMENT in requirements and sharedvfs:
872 if requirementsmod.SHARESAFE_REQUIREMENT in requirements and sharedvfs:
873 try:
873 try:
874 ui.readconfig(sharedvfs.join(b'hgrc'), root=sharedvfs.base)
874 ui.readconfig(sharedvfs.join(b'hgrc'), root=sharedvfs.base)
875 ret = True
875 ret = True
876 except IOError:
876 except IOError:
877 pass
877 pass
878
878
879 try:
879 try:
880 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
880 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
881 ret = True
881 ret = True
882 except IOError:
882 except IOError:
883 pass
883 pass
884
884
885 try:
885 try:
886 ui.readconfig(hgvfs.join(b'hgrc-not-shared'), root=wdirvfs.base)
886 ui.readconfig(hgvfs.join(b'hgrc-not-shared'), root=wdirvfs.base)
887 ret = True
887 ret = True
888 except IOError:
888 except IOError:
889 pass
889 pass
890
890
891 return ret
891 return ret
892
892
893
893
894 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
894 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
895 """Perform additional actions after .hg/hgrc is loaded.
895 """Perform additional actions after .hg/hgrc is loaded.
896
896
897 This function is called during repository loading immediately after
897 This function is called during repository loading immediately after
898 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
898 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
899
899
900 The function can be used to validate configs, automatically add
900 The function can be used to validate configs, automatically add
901 options (including extensions) based on requirements, etc.
901 options (including extensions) based on requirements, etc.
902 """
902 """
903
903
904 # Map of requirements to list of extensions to load automatically when
904 # Map of requirements to list of extensions to load automatically when
905 # requirement is present.
905 # requirement is present.
906 autoextensions = {
906 autoextensions = {
907 b'git': [b'git'],
907 b'git': [b'git'],
908 b'largefiles': [b'largefiles'],
908 b'largefiles': [b'largefiles'],
909 b'lfs': [b'lfs'],
909 b'lfs': [b'lfs'],
910 }
910 }
911
911
912 for requirement, names in sorted(autoextensions.items()):
912 for requirement, names in sorted(autoextensions.items()):
913 if requirement not in requirements:
913 if requirement not in requirements:
914 continue
914 continue
915
915
916 for name in names:
916 for name in names:
917 if not ui.hasconfig(b'extensions', name):
917 if not ui.hasconfig(b'extensions', name):
918 ui.setconfig(b'extensions', name, b'', source=b'autoload')
918 ui.setconfig(b'extensions', name, b'', source=b'autoload')
919
919
920
920
921 def gathersupportedrequirements(ui):
921 def gathersupportedrequirements(ui):
922 """Determine the complete set of recognized requirements."""
922 """Determine the complete set of recognized requirements."""
923 # Start with all requirements supported by this file.
923 # Start with all requirements supported by this file.
924 supported = set(localrepository._basesupported)
924 supported = set(localrepository._basesupported)
925
925
926 # Execute ``featuresetupfuncs`` entries if they belong to an extension
926 # Execute ``featuresetupfuncs`` entries if they belong to an extension
927 # relevant to this ui instance.
927 # relevant to this ui instance.
928 modules = {m.__name__ for n, m in extensions.extensions(ui)}
928 modules = {m.__name__ for n, m in extensions.extensions(ui)}
929
929
930 for fn in featuresetupfuncs:
930 for fn in featuresetupfuncs:
931 if fn.__module__ in modules:
931 if fn.__module__ in modules:
932 fn(ui, supported)
932 fn(ui, supported)
933
933
934 # Add derived requirements from registered compression engines.
934 # Add derived requirements from registered compression engines.
935 for name in util.compengines:
935 for name in util.compengines:
936 engine = util.compengines[name]
936 engine = util.compengines[name]
937 if engine.available() and engine.revlogheader():
937 if engine.available() and engine.revlogheader():
938 supported.add(b'exp-compression-%s' % name)
938 supported.add(b'exp-compression-%s' % name)
939 if engine.name() == b'zstd':
939 if engine.name() == b'zstd':
940 supported.add(requirementsmod.REVLOG_COMPRESSION_ZSTD)
940 supported.add(requirementsmod.REVLOG_COMPRESSION_ZSTD)
941
941
942 return supported
942 return supported
943
943
944
944
945 def ensurerequirementsrecognized(requirements, supported):
945 def ensurerequirementsrecognized(requirements, supported):
946 """Validate that a set of local requirements is recognized.
946 """Validate that a set of local requirements is recognized.
947
947
948 Receives a set of requirements. Raises an ``error.RepoError`` if there
948 Receives a set of requirements. Raises an ``error.RepoError`` if there
949 exists any requirement in that set that currently loaded code doesn't
949 exists any requirement in that set that currently loaded code doesn't
950 recognize.
950 recognize.
951
951
952 Returns a set of supported requirements.
952 Returns a set of supported requirements.
953 """
953 """
954 missing = set()
954 missing = set()
955
955
956 for requirement in requirements:
956 for requirement in requirements:
957 if requirement in supported:
957 if requirement in supported:
958 continue
958 continue
959
959
960 if not requirement or not requirement[0:1].isalnum():
960 if not requirement or not requirement[0:1].isalnum():
961 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
961 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
962
962
963 missing.add(requirement)
963 missing.add(requirement)
964
964
965 if missing:
965 if missing:
966 raise error.RequirementError(
966 raise error.RequirementError(
967 _(b'repository requires features unknown to this Mercurial: %s')
967 _(b'repository requires features unknown to this Mercurial: %s')
968 % b' '.join(sorted(missing)),
968 % b' '.join(sorted(missing)),
969 hint=_(
969 hint=_(
970 b'see https://mercurial-scm.org/wiki/MissingRequirement '
970 b'see https://mercurial-scm.org/wiki/MissingRequirement '
971 b'for more information'
971 b'for more information'
972 ),
972 ),
973 )
973 )
974
974
975
975
976 def ensurerequirementscompatible(ui, requirements):
976 def ensurerequirementscompatible(ui, requirements):
977 """Validates that a set of recognized requirements is mutually compatible.
977 """Validates that a set of recognized requirements is mutually compatible.
978
978
979 Some requirements may not be compatible with others or require
979 Some requirements may not be compatible with others or require
980 config options that aren't enabled. This function is called during
980 config options that aren't enabled. This function is called during
981 repository opening to ensure that the set of requirements needed
981 repository opening to ensure that the set of requirements needed
982 to open a repository is sane and compatible with config options.
982 to open a repository is sane and compatible with config options.
983
983
984 Extensions can monkeypatch this function to perform additional
984 Extensions can monkeypatch this function to perform additional
985 checking.
985 checking.
986
986
987 ``error.RepoError`` should be raised on failure.
987 ``error.RepoError`` should be raised on failure.
988 """
988 """
989 if (
989 if (
990 requirementsmod.SPARSE_REQUIREMENT in requirements
990 requirementsmod.SPARSE_REQUIREMENT in requirements
991 and not sparse.enabled
991 and not sparse.enabled
992 ):
992 ):
993 raise error.RepoError(
993 raise error.RepoError(
994 _(
994 _(
995 b'repository is using sparse feature but '
995 b'repository is using sparse feature but '
996 b'sparse is not enabled; enable the '
996 b'sparse is not enabled; enable the '
997 b'"sparse" extensions to access'
997 b'"sparse" extensions to access'
998 )
998 )
999 )
999 )
1000
1000
1001
1001
1002 def makestore(requirements, path, vfstype):
1002 def makestore(requirements, path, vfstype):
1003 """Construct a storage object for a repository."""
1003 """Construct a storage object for a repository."""
1004 if requirementsmod.STORE_REQUIREMENT in requirements:
1004 if requirementsmod.STORE_REQUIREMENT in requirements:
1005 if requirementsmod.FNCACHE_REQUIREMENT in requirements:
1005 if requirementsmod.FNCACHE_REQUIREMENT in requirements:
1006 dotencode = requirementsmod.DOTENCODE_REQUIREMENT in requirements
1006 dotencode = requirementsmod.DOTENCODE_REQUIREMENT in requirements
1007 return storemod.fncachestore(path, vfstype, dotencode)
1007 return storemod.fncachestore(path, vfstype, dotencode)
1008
1008
1009 return storemod.encodedstore(path, vfstype)
1009 return storemod.encodedstore(path, vfstype)
1010
1010
1011 return storemod.basicstore(path, vfstype)
1011 return storemod.basicstore(path, vfstype)
1012
1012
1013
1013
1014 def resolvestorevfsoptions(ui, requirements, features):
1014 def resolvestorevfsoptions(ui, requirements, features):
1015 """Resolve the options to pass to the store vfs opener.
1015 """Resolve the options to pass to the store vfs opener.
1016
1016
1017 The returned dict is used to influence behavior of the storage layer.
1017 The returned dict is used to influence behavior of the storage layer.
1018 """
1018 """
1019 options = {}
1019 options = {}
1020
1020
1021 if requirementsmod.TREEMANIFEST_REQUIREMENT in requirements:
1021 if requirementsmod.TREEMANIFEST_REQUIREMENT in requirements:
1022 options[b'treemanifest'] = True
1022 options[b'treemanifest'] = True
1023
1023
1024 # experimental config: format.manifestcachesize
1024 # experimental config: format.manifestcachesize
1025 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
1025 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
1026 if manifestcachesize is not None:
1026 if manifestcachesize is not None:
1027 options[b'manifestcachesize'] = manifestcachesize
1027 options[b'manifestcachesize'] = manifestcachesize
1028
1028
1029 # In the absence of another requirement superseding a revlog-related
1029 # In the absence of another requirement superseding a revlog-related
1030 # requirement, we have to assume the repo is using revlog version 0.
1030 # requirement, we have to assume the repo is using revlog version 0.
1031 # This revlog format is super old and we don't bother trying to parse
1031 # This revlog format is super old and we don't bother trying to parse
1032 # opener options for it because those options wouldn't do anything
1032 # opener options for it because those options wouldn't do anything
1033 # meaningful on such old repos.
1033 # meaningful on such old repos.
1034 if (
1034 if (
1035 requirementsmod.REVLOGV1_REQUIREMENT in requirements
1035 requirementsmod.REVLOGV1_REQUIREMENT in requirements
1036 or requirementsmod.REVLOGV2_REQUIREMENT in requirements
1036 or requirementsmod.REVLOGV2_REQUIREMENT in requirements
1037 ):
1037 ):
1038 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
1038 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
1039 else: # explicitly mark repo as using revlogv0
1039 else: # explicitly mark repo as using revlogv0
1040 options[b'revlogv0'] = True
1040 options[b'revlogv0'] = True
1041
1041
1042 if requirementsmod.COPIESSDC_REQUIREMENT in requirements:
1042 if requirementsmod.COPIESSDC_REQUIREMENT in requirements:
1043 options[b'copies-storage'] = b'changeset-sidedata'
1043 options[b'copies-storage'] = b'changeset-sidedata'
1044 else:
1044 else:
1045 writecopiesto = ui.config(b'experimental', b'copies.write-to')
1045 writecopiesto = ui.config(b'experimental', b'copies.write-to')
1046 copiesextramode = (b'changeset-only', b'compatibility')
1046 copiesextramode = (b'changeset-only', b'compatibility')
1047 if writecopiesto in copiesextramode:
1047 if writecopiesto in copiesextramode:
1048 options[b'copies-storage'] = b'extra'
1048 options[b'copies-storage'] = b'extra'
1049
1049
1050 return options
1050 return options
1051
1051
1052
1052
1053 def resolverevlogstorevfsoptions(ui, requirements, features):
1053 def resolverevlogstorevfsoptions(ui, requirements, features):
1054 """Resolve opener options specific to revlogs."""
1054 """Resolve opener options specific to revlogs."""
1055
1055
1056 options = {}
1056 options = {}
1057 options[b'flagprocessors'] = {}
1057 options[b'flagprocessors'] = {}
1058
1058
1059 if requirementsmod.REVLOGV1_REQUIREMENT in requirements:
1059 if requirementsmod.REVLOGV1_REQUIREMENT in requirements:
1060 options[b'revlogv1'] = True
1060 options[b'revlogv1'] = True
1061 if requirementsmod.REVLOGV2_REQUIREMENT in requirements:
1061 if requirementsmod.REVLOGV2_REQUIREMENT in requirements:
1062 options[b'revlogv2'] = True
1062 options[b'revlogv2'] = True
1063 if requirementsmod.CHANGELOGV2_REQUIREMENT in requirements:
1063 if requirementsmod.CHANGELOGV2_REQUIREMENT in requirements:
1064 options[b'changelogv2'] = True
1064 options[b'changelogv2'] = True
1065
1065
1066 if requirementsmod.GENERALDELTA_REQUIREMENT in requirements:
1066 if requirementsmod.GENERALDELTA_REQUIREMENT in requirements:
1067 options[b'generaldelta'] = True
1067 options[b'generaldelta'] = True
1068
1068
1069 # experimental config: format.chunkcachesize
1069 # experimental config: format.chunkcachesize
1070 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
1070 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
1071 if chunkcachesize is not None:
1071 if chunkcachesize is not None:
1072 options[b'chunkcachesize'] = chunkcachesize
1072 options[b'chunkcachesize'] = chunkcachesize
1073
1073
1074 deltabothparents = ui.configbool(
1074 deltabothparents = ui.configbool(
1075 b'storage', b'revlog.optimize-delta-parent-choice'
1075 b'storage', b'revlog.optimize-delta-parent-choice'
1076 )
1076 )
1077 options[b'deltabothparents'] = deltabothparents
1077 options[b'deltabothparents'] = deltabothparents
1078 options[b'debug-delta'] = ui.configbool(b'debug', b'revlog.debug-delta')
1078 options[b'debug-delta'] = ui.configbool(b'debug', b'revlog.debug-delta')
1079
1079
1080 issue6528 = ui.configbool(b'storage', b'revlog.issue6528.fix-incoming')
1080 issue6528 = ui.configbool(b'storage', b'revlog.issue6528.fix-incoming')
1081 options[b'issue6528.fix-incoming'] = issue6528
1081 options[b'issue6528.fix-incoming'] = issue6528
1082
1082
1083 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
1083 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
1084 lazydeltabase = False
1084 lazydeltabase = False
1085 if lazydelta:
1085 if lazydelta:
1086 lazydeltabase = ui.configbool(
1086 lazydeltabase = ui.configbool(
1087 b'storage', b'revlog.reuse-external-delta-parent'
1087 b'storage', b'revlog.reuse-external-delta-parent'
1088 )
1088 )
1089 if lazydeltabase is None:
1089 if lazydeltabase is None:
1090 lazydeltabase = not scmutil.gddeltaconfig(ui)
1090 lazydeltabase = not scmutil.gddeltaconfig(ui)
1091 options[b'lazydelta'] = lazydelta
1091 options[b'lazydelta'] = lazydelta
1092 options[b'lazydeltabase'] = lazydeltabase
1092 options[b'lazydeltabase'] = lazydeltabase
1093
1093
1094 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
1094 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
1095 if 0 <= chainspan:
1095 if 0 <= chainspan:
1096 options[b'maxdeltachainspan'] = chainspan
1096 options[b'maxdeltachainspan'] = chainspan
1097
1097
1098 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
1098 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
1099 if mmapindexthreshold is not None:
1099 if mmapindexthreshold is not None:
1100 options[b'mmapindexthreshold'] = mmapindexthreshold
1100 options[b'mmapindexthreshold'] = mmapindexthreshold
1101
1101
1102 withsparseread = ui.configbool(b'experimental', b'sparse-read')
1102 withsparseread = ui.configbool(b'experimental', b'sparse-read')
1103 srdensitythres = float(
1103 srdensitythres = float(
1104 ui.config(b'experimental', b'sparse-read.density-threshold')
1104 ui.config(b'experimental', b'sparse-read.density-threshold')
1105 )
1105 )
1106 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
1106 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
1107 options[b'with-sparse-read'] = withsparseread
1107 options[b'with-sparse-read'] = withsparseread
1108 options[b'sparse-read-density-threshold'] = srdensitythres
1108 options[b'sparse-read-density-threshold'] = srdensitythres
1109 options[b'sparse-read-min-gap-size'] = srmingapsize
1109 options[b'sparse-read-min-gap-size'] = srmingapsize
1110
1110
1111 sparserevlog = requirementsmod.SPARSEREVLOG_REQUIREMENT in requirements
1111 sparserevlog = requirementsmod.SPARSEREVLOG_REQUIREMENT in requirements
1112 options[b'sparse-revlog'] = sparserevlog
1112 options[b'sparse-revlog'] = sparserevlog
1113 if sparserevlog:
1113 if sparserevlog:
1114 options[b'generaldelta'] = True
1114 options[b'generaldelta'] = True
1115
1115
1116 maxchainlen = None
1116 maxchainlen = None
1117 if sparserevlog:
1117 if sparserevlog:
1118 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
1118 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
1119 # experimental config: format.maxchainlen
1119 # experimental config: format.maxchainlen
1120 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
1120 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
1121 if maxchainlen is not None:
1121 if maxchainlen is not None:
1122 options[b'maxchainlen'] = maxchainlen
1122 options[b'maxchainlen'] = maxchainlen
1123
1123
1124 for r in requirements:
1124 for r in requirements:
1125 # we allow multiple compression engine requirement to co-exist because
1125 # we allow multiple compression engine requirement to co-exist because
1126 # strickly speaking, revlog seems to support mixed compression style.
1126 # strickly speaking, revlog seems to support mixed compression style.
1127 #
1127 #
1128 # The compression used for new entries will be "the last one"
1128 # The compression used for new entries will be "the last one"
1129 prefix = r.startswith
1129 prefix = r.startswith
1130 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
1130 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
1131 options[b'compengine'] = r.split(b'-', 2)[2]
1131 options[b'compengine'] = r.split(b'-', 2)[2]
1132
1132
1133 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
1133 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
1134 if options[b'zlib.level'] is not None:
1134 if options[b'zlib.level'] is not None:
1135 if not (0 <= options[b'zlib.level'] <= 9):
1135 if not (0 <= options[b'zlib.level'] <= 9):
1136 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
1136 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
1137 raise error.Abort(msg % options[b'zlib.level'])
1137 raise error.Abort(msg % options[b'zlib.level'])
1138 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
1138 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
1139 if options[b'zstd.level'] is not None:
1139 if options[b'zstd.level'] is not None:
1140 if not (0 <= options[b'zstd.level'] <= 22):
1140 if not (0 <= options[b'zstd.level'] <= 22):
1141 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
1141 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
1142 raise error.Abort(msg % options[b'zstd.level'])
1142 raise error.Abort(msg % options[b'zstd.level'])
1143
1143
1144 if requirementsmod.NARROW_REQUIREMENT in requirements:
1144 if requirementsmod.NARROW_REQUIREMENT in requirements:
1145 options[b'enableellipsis'] = True
1145 options[b'enableellipsis'] = True
1146
1146
1147 if ui.configbool(b'experimental', b'rust.index'):
1147 if ui.configbool(b'experimental', b'rust.index'):
1148 options[b'rust.index'] = True
1148 options[b'rust.index'] = True
1149 if requirementsmod.NODEMAP_REQUIREMENT in requirements:
1149 if requirementsmod.NODEMAP_REQUIREMENT in requirements:
1150 slow_path = ui.config(
1150 slow_path = ui.config(
1151 b'storage', b'revlog.persistent-nodemap.slow-path'
1151 b'storage', b'revlog.persistent-nodemap.slow-path'
1152 )
1152 )
1153 if slow_path not in (b'allow', b'warn', b'abort'):
1153 if slow_path not in (b'allow', b'warn', b'abort'):
1154 default = ui.config_default(
1154 default = ui.config_default(
1155 b'storage', b'revlog.persistent-nodemap.slow-path'
1155 b'storage', b'revlog.persistent-nodemap.slow-path'
1156 )
1156 )
1157 msg = _(
1157 msg = _(
1158 b'unknown value for config '
1158 b'unknown value for config '
1159 b'"storage.revlog.persistent-nodemap.slow-path": "%s"\n'
1159 b'"storage.revlog.persistent-nodemap.slow-path": "%s"\n'
1160 )
1160 )
1161 ui.warn(msg % slow_path)
1161 ui.warn(msg % slow_path)
1162 if not ui.quiet:
1162 if not ui.quiet:
1163 ui.warn(_(b'falling back to default value: %s\n') % default)
1163 ui.warn(_(b'falling back to default value: %s\n') % default)
1164 slow_path = default
1164 slow_path = default
1165
1165
1166 msg = _(
1166 msg = _(
1167 b"accessing `persistent-nodemap` repository without associated "
1167 b"accessing `persistent-nodemap` repository without associated "
1168 b"fast implementation."
1168 b"fast implementation."
1169 )
1169 )
1170 hint = _(
1170 hint = _(
1171 b"check `hg help config.format.use-persistent-nodemap` "
1171 b"check `hg help config.format.use-persistent-nodemap` "
1172 b"for details"
1172 b"for details"
1173 )
1173 )
1174 if not revlog.HAS_FAST_PERSISTENT_NODEMAP:
1174 if not revlog.HAS_FAST_PERSISTENT_NODEMAP:
1175 if slow_path == b'warn':
1175 if slow_path == b'warn':
1176 msg = b"warning: " + msg + b'\n'
1176 msg = b"warning: " + msg + b'\n'
1177 ui.warn(msg)
1177 ui.warn(msg)
1178 if not ui.quiet:
1178 if not ui.quiet:
1179 hint = b'(' + hint + b')\n'
1179 hint = b'(' + hint + b')\n'
1180 ui.warn(hint)
1180 ui.warn(hint)
1181 if slow_path == b'abort':
1181 if slow_path == b'abort':
1182 raise error.Abort(msg, hint=hint)
1182 raise error.Abort(msg, hint=hint)
1183 options[b'persistent-nodemap'] = True
1183 options[b'persistent-nodemap'] = True
1184 if requirementsmod.DIRSTATE_V2_REQUIREMENT in requirements:
1184 if requirementsmod.DIRSTATE_V2_REQUIREMENT in requirements:
1185 slow_path = ui.config(b'storage', b'dirstate-v2.slow-path')
1185 slow_path = ui.config(b'storage', b'dirstate-v2.slow-path')
1186 if slow_path not in (b'allow', b'warn', b'abort'):
1186 if slow_path not in (b'allow', b'warn', b'abort'):
1187 default = ui.config_default(b'storage', b'dirstate-v2.slow-path')
1187 default = ui.config_default(b'storage', b'dirstate-v2.slow-path')
1188 msg = _(b'unknown value for config "dirstate-v2.slow-path": "%s"\n')
1188 msg = _(b'unknown value for config "dirstate-v2.slow-path": "%s"\n')
1189 ui.warn(msg % slow_path)
1189 ui.warn(msg % slow_path)
1190 if not ui.quiet:
1190 if not ui.quiet:
1191 ui.warn(_(b'falling back to default value: %s\n') % default)
1191 ui.warn(_(b'falling back to default value: %s\n') % default)
1192 slow_path = default
1192 slow_path = default
1193
1193
1194 msg = _(
1194 msg = _(
1195 b"accessing `dirstate-v2` repository without associated "
1195 b"accessing `dirstate-v2` repository without associated "
1196 b"fast implementation."
1196 b"fast implementation."
1197 )
1197 )
1198 hint = _(
1198 hint = _(
1199 b"check `hg help config.format.use-dirstate-v2` " b"for details"
1199 b"check `hg help config.format.use-dirstate-v2` " b"for details"
1200 )
1200 )
1201 if not dirstate.HAS_FAST_DIRSTATE_V2:
1201 if not dirstate.HAS_FAST_DIRSTATE_V2:
1202 if slow_path == b'warn':
1202 if slow_path == b'warn':
1203 msg = b"warning: " + msg + b'\n'
1203 msg = b"warning: " + msg + b'\n'
1204 ui.warn(msg)
1204 ui.warn(msg)
1205 if not ui.quiet:
1205 if not ui.quiet:
1206 hint = b'(' + hint + b')\n'
1206 hint = b'(' + hint + b')\n'
1207 ui.warn(hint)
1207 ui.warn(hint)
1208 if slow_path == b'abort':
1208 if slow_path == b'abort':
1209 raise error.Abort(msg, hint=hint)
1209 raise error.Abort(msg, hint=hint)
1210 if ui.configbool(b'storage', b'revlog.persistent-nodemap.mmap'):
1210 if ui.configbool(b'storage', b'revlog.persistent-nodemap.mmap'):
1211 options[b'persistent-nodemap.mmap'] = True
1211 options[b'persistent-nodemap.mmap'] = True
1212 if ui.configbool(b'devel', b'persistent-nodemap'):
1212 if ui.configbool(b'devel', b'persistent-nodemap'):
1213 options[b'devel-force-nodemap'] = True
1213 options[b'devel-force-nodemap'] = True
1214
1214
1215 return options
1215 return options
1216
1216
1217
1217
1218 def makemain(**kwargs):
1218 def makemain(**kwargs):
1219 """Produce a type conforming to ``ilocalrepositorymain``."""
1219 """Produce a type conforming to ``ilocalrepositorymain``."""
1220 return localrepository
1220 return localrepository
1221
1221
1222
1222
1223 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1223 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1224 class revlogfilestorage:
1224 class revlogfilestorage:
1225 """File storage when using revlogs."""
1225 """File storage when using revlogs."""
1226
1226
1227 def file(self, path):
1227 def file(self, path):
1228 if path.startswith(b'/'):
1228 if path.startswith(b'/'):
1229 path = path[1:]
1229 path = path[1:]
1230
1230
1231 return filelog.filelog(self.svfs, path)
1231 return filelog.filelog(self.svfs, path)
1232
1232
1233
1233
1234 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1234 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1235 class revlognarrowfilestorage:
1235 class revlognarrowfilestorage:
1236 """File storage when using revlogs and narrow files."""
1236 """File storage when using revlogs and narrow files."""
1237
1237
1238 def file(self, path):
1238 def file(self, path):
1239 if path.startswith(b'/'):
1239 if path.startswith(b'/'):
1240 path = path[1:]
1240 path = path[1:]
1241
1241
1242 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
1242 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
1243
1243
1244
1244
1245 def makefilestorage(requirements, features, **kwargs):
1245 def makefilestorage(requirements, features, **kwargs):
1246 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
1246 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
1247 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
1247 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
1248 features.add(repository.REPO_FEATURE_STREAM_CLONE)
1248 features.add(repository.REPO_FEATURE_STREAM_CLONE)
1249
1249
1250 if requirementsmod.NARROW_REQUIREMENT in requirements:
1250 if requirementsmod.NARROW_REQUIREMENT in requirements:
1251 return revlognarrowfilestorage
1251 return revlognarrowfilestorage
1252 else:
1252 else:
1253 return revlogfilestorage
1253 return revlogfilestorage
1254
1254
1255
1255
1256 # List of repository interfaces and factory functions for them. Each
1256 # List of repository interfaces and factory functions for them. Each
1257 # will be called in order during ``makelocalrepository()`` to iteratively
1257 # will be called in order during ``makelocalrepository()`` to iteratively
1258 # derive the final type for a local repository instance. We capture the
1258 # derive the final type for a local repository instance. We capture the
1259 # function as a lambda so we don't hold a reference and the module-level
1259 # function as a lambda so we don't hold a reference and the module-level
1260 # functions can be wrapped.
1260 # functions can be wrapped.
1261 REPO_INTERFACES = [
1261 REPO_INTERFACES = [
1262 (repository.ilocalrepositorymain, lambda: makemain),
1262 (repository.ilocalrepositorymain, lambda: makemain),
1263 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
1263 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
1264 ]
1264 ]
1265
1265
1266
1266
1267 @interfaceutil.implementer(repository.ilocalrepositorymain)
1267 @interfaceutil.implementer(repository.ilocalrepositorymain)
1268 class localrepository:
1268 class localrepository:
1269 """Main class for representing local repositories.
1269 """Main class for representing local repositories.
1270
1270
1271 All local repositories are instances of this class.
1271 All local repositories are instances of this class.
1272
1272
1273 Constructed on its own, instances of this class are not usable as
1273 Constructed on its own, instances of this class are not usable as
1274 repository objects. To obtain a usable repository object, call
1274 repository objects. To obtain a usable repository object, call
1275 ``hg.repository()``, ``localrepo.instance()``, or
1275 ``hg.repository()``, ``localrepo.instance()``, or
1276 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
1276 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
1277 ``instance()`` adds support for creating new repositories.
1277 ``instance()`` adds support for creating new repositories.
1278 ``hg.repository()`` adds more extension integration, including calling
1278 ``hg.repository()`` adds more extension integration, including calling
1279 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
1279 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
1280 used.
1280 used.
1281 """
1281 """
1282
1282
1283 _basesupported = {
1283 _basesupported = {
1284 requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT,
1284 requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT,
1285 requirementsmod.CHANGELOGV2_REQUIREMENT,
1285 requirementsmod.CHANGELOGV2_REQUIREMENT,
1286 requirementsmod.COPIESSDC_REQUIREMENT,
1286 requirementsmod.COPIESSDC_REQUIREMENT,
1287 requirementsmod.DIRSTATE_TRACKED_HINT_V1,
1287 requirementsmod.DIRSTATE_TRACKED_HINT_V1,
1288 requirementsmod.DIRSTATE_V2_REQUIREMENT,
1288 requirementsmod.DIRSTATE_V2_REQUIREMENT,
1289 requirementsmod.DOTENCODE_REQUIREMENT,
1289 requirementsmod.DOTENCODE_REQUIREMENT,
1290 requirementsmod.FNCACHE_REQUIREMENT,
1290 requirementsmod.FNCACHE_REQUIREMENT,
1291 requirementsmod.GENERALDELTA_REQUIREMENT,
1291 requirementsmod.GENERALDELTA_REQUIREMENT,
1292 requirementsmod.INTERNAL_PHASE_REQUIREMENT,
1292 requirementsmod.INTERNAL_PHASE_REQUIREMENT,
1293 requirementsmod.NODEMAP_REQUIREMENT,
1293 requirementsmod.NODEMAP_REQUIREMENT,
1294 requirementsmod.RELATIVE_SHARED_REQUIREMENT,
1294 requirementsmod.RELATIVE_SHARED_REQUIREMENT,
1295 requirementsmod.REVLOGV1_REQUIREMENT,
1295 requirementsmod.REVLOGV1_REQUIREMENT,
1296 requirementsmod.REVLOGV2_REQUIREMENT,
1296 requirementsmod.REVLOGV2_REQUIREMENT,
1297 requirementsmod.SHARED_REQUIREMENT,
1297 requirementsmod.SHARED_REQUIREMENT,
1298 requirementsmod.SHARESAFE_REQUIREMENT,
1298 requirementsmod.SHARESAFE_REQUIREMENT,
1299 requirementsmod.SPARSE_REQUIREMENT,
1299 requirementsmod.SPARSE_REQUIREMENT,
1300 requirementsmod.SPARSEREVLOG_REQUIREMENT,
1300 requirementsmod.SPARSEREVLOG_REQUIREMENT,
1301 requirementsmod.STORE_REQUIREMENT,
1301 requirementsmod.STORE_REQUIREMENT,
1302 requirementsmod.TREEMANIFEST_REQUIREMENT,
1302 requirementsmod.TREEMANIFEST_REQUIREMENT,
1303 }
1303 }
1304
1304
1305 # list of prefix for file which can be written without 'wlock'
1305 # list of prefix for file which can be written without 'wlock'
1306 # Extensions should extend this list when needed
1306 # Extensions should extend this list when needed
1307 _wlockfreeprefix = {
1307 _wlockfreeprefix = {
1308 # We migh consider requiring 'wlock' for the next
1308 # We migh consider requiring 'wlock' for the next
1309 # two, but pretty much all the existing code assume
1309 # two, but pretty much all the existing code assume
1310 # wlock is not needed so we keep them excluded for
1310 # wlock is not needed so we keep them excluded for
1311 # now.
1311 # now.
1312 b'hgrc',
1312 b'hgrc',
1313 b'requires',
1313 b'requires',
1314 # XXX cache is a complicatged business someone
1314 # XXX cache is a complicatged business someone
1315 # should investigate this in depth at some point
1315 # should investigate this in depth at some point
1316 b'cache/',
1316 b'cache/',
1317 # XXX shouldn't be dirstate covered by the wlock?
1317 # XXX shouldn't be dirstate covered by the wlock?
1318 b'dirstate',
1318 b'dirstate',
1319 # XXX bisect was still a bit too messy at the time
1319 # XXX bisect was still a bit too messy at the time
1320 # this changeset was introduced. Someone should fix
1320 # this changeset was introduced. Someone should fix
1321 # the remainig bit and drop this line
1321 # the remainig bit and drop this line
1322 b'bisect.state',
1322 b'bisect.state',
1323 }
1323 }
1324
1324
1325 def __init__(
1325 def __init__(
1326 self,
1326 self,
1327 baseui,
1327 baseui,
1328 ui,
1328 ui,
1329 origroot,
1329 origroot,
1330 wdirvfs,
1330 wdirvfs,
1331 hgvfs,
1331 hgvfs,
1332 requirements,
1332 requirements,
1333 supportedrequirements,
1333 supportedrequirements,
1334 sharedpath,
1334 sharedpath,
1335 store,
1335 store,
1336 cachevfs,
1336 cachevfs,
1337 wcachevfs,
1337 wcachevfs,
1338 features,
1338 features,
1339 intents=None,
1339 intents=None,
1340 ):
1340 ):
1341 """Create a new local repository instance.
1341 """Create a new local repository instance.
1342
1342
1343 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1343 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1344 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1344 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1345 object.
1345 object.
1346
1346
1347 Arguments:
1347 Arguments:
1348
1348
1349 baseui
1349 baseui
1350 ``ui.ui`` instance that ``ui`` argument was based off of.
1350 ``ui.ui`` instance that ``ui`` argument was based off of.
1351
1351
1352 ui
1352 ui
1353 ``ui.ui`` instance for use by the repository.
1353 ``ui.ui`` instance for use by the repository.
1354
1354
1355 origroot
1355 origroot
1356 ``bytes`` path to working directory root of this repository.
1356 ``bytes`` path to working directory root of this repository.
1357
1357
1358 wdirvfs
1358 wdirvfs
1359 ``vfs.vfs`` rooted at the working directory.
1359 ``vfs.vfs`` rooted at the working directory.
1360
1360
1361 hgvfs
1361 hgvfs
1362 ``vfs.vfs`` rooted at .hg/
1362 ``vfs.vfs`` rooted at .hg/
1363
1363
1364 requirements
1364 requirements
1365 ``set`` of bytestrings representing repository opening requirements.
1365 ``set`` of bytestrings representing repository opening requirements.
1366
1366
1367 supportedrequirements
1367 supportedrequirements
1368 ``set`` of bytestrings representing repository requirements that we
1368 ``set`` of bytestrings representing repository requirements that we
1369 know how to open. May be a supetset of ``requirements``.
1369 know how to open. May be a supetset of ``requirements``.
1370
1370
1371 sharedpath
1371 sharedpath
1372 ``bytes`` Defining path to storage base directory. Points to a
1372 ``bytes`` Defining path to storage base directory. Points to a
1373 ``.hg/`` directory somewhere.
1373 ``.hg/`` directory somewhere.
1374
1374
1375 store
1375 store
1376 ``store.basicstore`` (or derived) instance providing access to
1376 ``store.basicstore`` (or derived) instance providing access to
1377 versioned storage.
1377 versioned storage.
1378
1378
1379 cachevfs
1379 cachevfs
1380 ``vfs.vfs`` used for cache files.
1380 ``vfs.vfs`` used for cache files.
1381
1381
1382 wcachevfs
1382 wcachevfs
1383 ``vfs.vfs`` used for cache files related to the working copy.
1383 ``vfs.vfs`` used for cache files related to the working copy.
1384
1384
1385 features
1385 features
1386 ``set`` of bytestrings defining features/capabilities of this
1386 ``set`` of bytestrings defining features/capabilities of this
1387 instance.
1387 instance.
1388
1388
1389 intents
1389 intents
1390 ``set`` of system strings indicating what this repo will be used
1390 ``set`` of system strings indicating what this repo will be used
1391 for.
1391 for.
1392 """
1392 """
1393 self.baseui = baseui
1393 self.baseui = baseui
1394 self.ui = ui
1394 self.ui = ui
1395 self.origroot = origroot
1395 self.origroot = origroot
1396 # vfs rooted at working directory.
1396 # vfs rooted at working directory.
1397 self.wvfs = wdirvfs
1397 self.wvfs = wdirvfs
1398 self.root = wdirvfs.base
1398 self.root = wdirvfs.base
1399 # vfs rooted at .hg/. Used to access most non-store paths.
1399 # vfs rooted at .hg/. Used to access most non-store paths.
1400 self.vfs = hgvfs
1400 self.vfs = hgvfs
1401 self.path = hgvfs.base
1401 self.path = hgvfs.base
1402 self.requirements = requirements
1402 self.requirements = requirements
1403 self.nodeconstants = sha1nodeconstants
1403 self.nodeconstants = sha1nodeconstants
1404 self.nullid = self.nodeconstants.nullid
1404 self.nullid = self.nodeconstants.nullid
1405 self.supported = supportedrequirements
1405 self.supported = supportedrequirements
1406 self.sharedpath = sharedpath
1406 self.sharedpath = sharedpath
1407 self.store = store
1407 self.store = store
1408 self.cachevfs = cachevfs
1408 self.cachevfs = cachevfs
1409 self.wcachevfs = wcachevfs
1409 self.wcachevfs = wcachevfs
1410 self.features = features
1410 self.features = features
1411
1411
1412 self.filtername = None
1412 self.filtername = None
1413
1413
1414 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1414 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1415 b'devel', b'check-locks'
1415 b'devel', b'check-locks'
1416 ):
1416 ):
1417 self.vfs.audit = self._getvfsward(self.vfs.audit)
1417 self.vfs.audit = self._getvfsward(self.vfs.audit)
1418 # A list of callback to shape the phase if no data were found.
1418 # A list of callback to shape the phase if no data were found.
1419 # Callback are in the form: func(repo, roots) --> processed root.
1419 # Callback are in the form: func(repo, roots) --> processed root.
1420 # This list it to be filled by extension during repo setup
1420 # This list it to be filled by extension during repo setup
1421 self._phasedefaults = []
1421 self._phasedefaults = []
1422
1422
1423 color.setup(self.ui)
1423 color.setup(self.ui)
1424
1424
1425 self.spath = self.store.path
1425 self.spath = self.store.path
1426 self.svfs = self.store.vfs
1426 self.svfs = self.store.vfs
1427 self.sjoin = self.store.join
1427 self.sjoin = self.store.join
1428 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1428 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1429 b'devel', b'check-locks'
1429 b'devel', b'check-locks'
1430 ):
1430 ):
1431 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1431 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1432 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1432 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1433 else: # standard vfs
1433 else: # standard vfs
1434 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1434 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1435
1435
1436 self._dirstatevalidatewarned = False
1436 self._dirstatevalidatewarned = False
1437
1437
1438 self._branchcaches = branchmap.BranchMapCache()
1438 self._branchcaches = branchmap.BranchMapCache()
1439 self._revbranchcache = None
1439 self._revbranchcache = None
1440 self._filterpats = {}
1440 self._filterpats = {}
1441 self._datafilters = {}
1441 self._datafilters = {}
1442 self._transref = self._lockref = self._wlockref = None
1442 self._transref = self._lockref = self._wlockref = None
1443
1443
1444 # A cache for various files under .hg/ that tracks file changes,
1444 # A cache for various files under .hg/ that tracks file changes,
1445 # (used by the filecache decorator)
1445 # (used by the filecache decorator)
1446 #
1446 #
1447 # Maps a property name to its util.filecacheentry
1447 # Maps a property name to its util.filecacheentry
1448 self._filecache = {}
1448 self._filecache = {}
1449
1449
1450 # hold sets of revision to be filtered
1450 # hold sets of revision to be filtered
1451 # should be cleared when something might have changed the filter value:
1451 # should be cleared when something might have changed the filter value:
1452 # - new changesets,
1452 # - new changesets,
1453 # - phase change,
1453 # - phase change,
1454 # - new obsolescence marker,
1454 # - new obsolescence marker,
1455 # - working directory parent change,
1455 # - working directory parent change,
1456 # - bookmark changes
1456 # - bookmark changes
1457 self.filteredrevcache = {}
1457 self.filteredrevcache = {}
1458
1458
1459 # post-dirstate-status hooks
1459 # post-dirstate-status hooks
1460 self._postdsstatus = []
1460 self._postdsstatus = []
1461
1461
1462 # generic mapping between names and nodes
1462 # generic mapping between names and nodes
1463 self.names = namespaces.namespaces()
1463 self.names = namespaces.namespaces()
1464
1464
1465 # Key to signature value.
1465 # Key to signature value.
1466 self._sparsesignaturecache = {}
1466 self._sparsesignaturecache = {}
1467 # Signature to cached matcher instance.
1467 # Signature to cached matcher instance.
1468 self._sparsematchercache = {}
1468 self._sparsematchercache = {}
1469
1469
1470 self._extrafilterid = repoview.extrafilter(ui)
1470 self._extrafilterid = repoview.extrafilter(ui)
1471
1471
1472 self.filecopiesmode = None
1472 self.filecopiesmode = None
1473 if requirementsmod.COPIESSDC_REQUIREMENT in self.requirements:
1473 if requirementsmod.COPIESSDC_REQUIREMENT in self.requirements:
1474 self.filecopiesmode = b'changeset-sidedata'
1474 self.filecopiesmode = b'changeset-sidedata'
1475
1475
1476 self._wanted_sidedata = set()
1476 self._wanted_sidedata = set()
1477 self._sidedata_computers = {}
1477 self._sidedata_computers = {}
1478 sidedatamod.set_sidedata_spec_for_repo(self)
1478 sidedatamod.set_sidedata_spec_for_repo(self)
1479
1479
1480 def _getvfsward(self, origfunc):
1480 def _getvfsward(self, origfunc):
1481 """build a ward for self.vfs"""
1481 """build a ward for self.vfs"""
1482 rref = weakref.ref(self)
1482 rref = weakref.ref(self)
1483
1483
1484 def checkvfs(path, mode=None):
1484 def checkvfs(path, mode=None):
1485 ret = origfunc(path, mode=mode)
1485 ret = origfunc(path, mode=mode)
1486 repo = rref()
1486 repo = rref()
1487 if (
1487 if (
1488 repo is None
1488 repo is None
1489 or not util.safehasattr(repo, b'_wlockref')
1489 or not util.safehasattr(repo, b'_wlockref')
1490 or not util.safehasattr(repo, b'_lockref')
1490 or not util.safehasattr(repo, b'_lockref')
1491 ):
1491 ):
1492 return
1492 return
1493 if mode in (None, b'r', b'rb'):
1493 if mode in (None, b'r', b'rb'):
1494 return
1494 return
1495 if path.startswith(repo.path):
1495 if path.startswith(repo.path):
1496 # truncate name relative to the repository (.hg)
1496 # truncate name relative to the repository (.hg)
1497 path = path[len(repo.path) + 1 :]
1497 path = path[len(repo.path) + 1 :]
1498 if path.startswith(b'cache/'):
1498 if path.startswith(b'cache/'):
1499 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1499 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1500 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1500 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1501 # path prefixes covered by 'lock'
1501 # path prefixes covered by 'lock'
1502 vfs_path_prefixes = (
1502 vfs_path_prefixes = (
1503 b'journal.',
1503 b'journal.',
1504 b'undo.',
1504 b'undo.',
1505 b'strip-backup/',
1505 b'strip-backup/',
1506 b'cache/',
1506 b'cache/',
1507 )
1507 )
1508 if any(path.startswith(prefix) for prefix in vfs_path_prefixes):
1508 if any(path.startswith(prefix) for prefix in vfs_path_prefixes):
1509 if repo._currentlock(repo._lockref) is None:
1509 if repo._currentlock(repo._lockref) is None:
1510 repo.ui.develwarn(
1510 repo.ui.develwarn(
1511 b'write with no lock: "%s"' % path,
1511 b'write with no lock: "%s"' % path,
1512 stacklevel=3,
1512 stacklevel=3,
1513 config=b'check-locks',
1513 config=b'check-locks',
1514 )
1514 )
1515 elif repo._currentlock(repo._wlockref) is None:
1515 elif repo._currentlock(repo._wlockref) is None:
1516 # rest of vfs files are covered by 'wlock'
1516 # rest of vfs files are covered by 'wlock'
1517 #
1517 #
1518 # exclude special files
1518 # exclude special files
1519 for prefix in self._wlockfreeprefix:
1519 for prefix in self._wlockfreeprefix:
1520 if path.startswith(prefix):
1520 if path.startswith(prefix):
1521 return
1521 return
1522 repo.ui.develwarn(
1522 repo.ui.develwarn(
1523 b'write with no wlock: "%s"' % path,
1523 b'write with no wlock: "%s"' % path,
1524 stacklevel=3,
1524 stacklevel=3,
1525 config=b'check-locks',
1525 config=b'check-locks',
1526 )
1526 )
1527 return ret
1527 return ret
1528
1528
1529 return checkvfs
1529 return checkvfs
1530
1530
1531 def _getsvfsward(self, origfunc):
1531 def _getsvfsward(self, origfunc):
1532 """build a ward for self.svfs"""
1532 """build a ward for self.svfs"""
1533 rref = weakref.ref(self)
1533 rref = weakref.ref(self)
1534
1534
1535 def checksvfs(path, mode=None):
1535 def checksvfs(path, mode=None):
1536 ret = origfunc(path, mode=mode)
1536 ret = origfunc(path, mode=mode)
1537 repo = rref()
1537 repo = rref()
1538 if repo is None or not util.safehasattr(repo, b'_lockref'):
1538 if repo is None or not util.safehasattr(repo, b'_lockref'):
1539 return
1539 return
1540 if mode in (None, b'r', b'rb'):
1540 if mode in (None, b'r', b'rb'):
1541 return
1541 return
1542 if path.startswith(repo.sharedpath):
1542 if path.startswith(repo.sharedpath):
1543 # truncate name relative to the repository (.hg)
1543 # truncate name relative to the repository (.hg)
1544 path = path[len(repo.sharedpath) + 1 :]
1544 path = path[len(repo.sharedpath) + 1 :]
1545 if repo._currentlock(repo._lockref) is None:
1545 if repo._currentlock(repo._lockref) is None:
1546 repo.ui.develwarn(
1546 repo.ui.develwarn(
1547 b'write with no lock: "%s"' % path, stacklevel=4
1547 b'write with no lock: "%s"' % path, stacklevel=4
1548 )
1548 )
1549 return ret
1549 return ret
1550
1550
1551 return checksvfs
1551 return checksvfs
1552
1552
1553 def close(self):
1553 def close(self):
1554 self._writecaches()
1554 self._writecaches()
1555
1555
1556 def _writecaches(self):
1556 def _writecaches(self):
1557 if self._revbranchcache:
1557 if self._revbranchcache:
1558 self._revbranchcache.write()
1558 self._revbranchcache.write()
1559
1559
1560 def _restrictcapabilities(self, caps):
1560 def _restrictcapabilities(self, caps):
1561 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1561 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1562 caps = set(caps)
1562 caps = set(caps)
1563 capsblob = bundle2.encodecaps(
1563 capsblob = bundle2.encodecaps(
1564 bundle2.getrepocaps(self, role=b'client')
1564 bundle2.getrepocaps(self, role=b'client')
1565 )
1565 )
1566 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1566 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1567 if self.ui.configbool(b'experimental', b'narrow'):
1567 if self.ui.configbool(b'experimental', b'narrow'):
1568 caps.add(wireprototypes.NARROWCAP)
1568 caps.add(wireprototypes.NARROWCAP)
1569 return caps
1569 return caps
1570
1570
1571 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1571 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1572 # self -> auditor -> self._checknested -> self
1572 # self -> auditor -> self._checknested -> self
1573
1573
1574 @property
1574 @property
1575 def auditor(self):
1575 def auditor(self):
1576 # This is only used by context.workingctx.match in order to
1576 # This is only used by context.workingctx.match in order to
1577 # detect files in subrepos.
1577 # detect files in subrepos.
1578 return pathutil.pathauditor(self.root, callback=self._checknested)
1578 return pathutil.pathauditor(self.root, callback=self._checknested)
1579
1579
1580 @property
1580 @property
1581 def nofsauditor(self):
1581 def nofsauditor(self):
1582 # This is only used by context.basectx.match in order to detect
1582 # This is only used by context.basectx.match in order to detect
1583 # files in subrepos.
1583 # files in subrepos.
1584 return pathutil.pathauditor(
1584 return pathutil.pathauditor(
1585 self.root, callback=self._checknested, realfs=False, cached=True
1585 self.root, callback=self._checknested, realfs=False, cached=True
1586 )
1586 )
1587
1587
1588 def _checknested(self, path):
1588 def _checknested(self, path):
1589 """Determine if path is a legal nested repository."""
1589 """Determine if path is a legal nested repository."""
1590 if not path.startswith(self.root):
1590 if not path.startswith(self.root):
1591 return False
1591 return False
1592 subpath = path[len(self.root) + 1 :]
1592 subpath = path[len(self.root) + 1 :]
1593 normsubpath = util.pconvert(subpath)
1593 normsubpath = util.pconvert(subpath)
1594
1594
1595 # XXX: Checking against the current working copy is wrong in
1595 # XXX: Checking against the current working copy is wrong in
1596 # the sense that it can reject things like
1596 # the sense that it can reject things like
1597 #
1597 #
1598 # $ hg cat -r 10 sub/x.txt
1598 # $ hg cat -r 10 sub/x.txt
1599 #
1599 #
1600 # if sub/ is no longer a subrepository in the working copy
1600 # if sub/ is no longer a subrepository in the working copy
1601 # parent revision.
1601 # parent revision.
1602 #
1602 #
1603 # However, it can of course also allow things that would have
1603 # However, it can of course also allow things that would have
1604 # been rejected before, such as the above cat command if sub/
1604 # been rejected before, such as the above cat command if sub/
1605 # is a subrepository now, but was a normal directory before.
1605 # is a subrepository now, but was a normal directory before.
1606 # The old path auditor would have rejected by mistake since it
1606 # The old path auditor would have rejected by mistake since it
1607 # panics when it sees sub/.hg/.
1607 # panics when it sees sub/.hg/.
1608 #
1608 #
1609 # All in all, checking against the working copy seems sensible
1609 # All in all, checking against the working copy seems sensible
1610 # since we want to prevent access to nested repositories on
1610 # since we want to prevent access to nested repositories on
1611 # the filesystem *now*.
1611 # the filesystem *now*.
1612 ctx = self[None]
1612 ctx = self[None]
1613 parts = util.splitpath(subpath)
1613 parts = util.splitpath(subpath)
1614 while parts:
1614 while parts:
1615 prefix = b'/'.join(parts)
1615 prefix = b'/'.join(parts)
1616 if prefix in ctx.substate:
1616 if prefix in ctx.substate:
1617 if prefix == normsubpath:
1617 if prefix == normsubpath:
1618 return True
1618 return True
1619 else:
1619 else:
1620 sub = ctx.sub(prefix)
1620 sub = ctx.sub(prefix)
1621 return sub.checknested(subpath[len(prefix) + 1 :])
1621 return sub.checknested(subpath[len(prefix) + 1 :])
1622 else:
1622 else:
1623 parts.pop()
1623 parts.pop()
1624 return False
1624 return False
1625
1625
1626 def peer(self):
1626 def peer(self):
1627 return localpeer(self) # not cached to avoid reference cycle
1627 return localpeer(self) # not cached to avoid reference cycle
1628
1628
1629 def unfiltered(self):
1629 def unfiltered(self):
1630 """Return unfiltered version of the repository
1630 """Return unfiltered version of the repository
1631
1631
1632 Intended to be overwritten by filtered repo."""
1632 Intended to be overwritten by filtered repo."""
1633 return self
1633 return self
1634
1634
1635 def filtered(self, name, visibilityexceptions=None):
1635 def filtered(self, name, visibilityexceptions=None):
1636 """Return a filtered version of a repository
1636 """Return a filtered version of a repository
1637
1637
1638 The `name` parameter is the identifier of the requested view. This
1638 The `name` parameter is the identifier of the requested view. This
1639 will return a repoview object set "exactly" to the specified view.
1639 will return a repoview object set "exactly" to the specified view.
1640
1640
1641 This function does not apply recursive filtering to a repository. For
1641 This function does not apply recursive filtering to a repository. For
1642 example calling `repo.filtered("served")` will return a repoview using
1642 example calling `repo.filtered("served")` will return a repoview using
1643 the "served" view, regardless of the initial view used by `repo`.
1643 the "served" view, regardless of the initial view used by `repo`.
1644
1644
1645 In other word, there is always only one level of `repoview` "filtering".
1645 In other word, there is always only one level of `repoview` "filtering".
1646 """
1646 """
1647 if self._extrafilterid is not None and b'%' not in name:
1647 if self._extrafilterid is not None and b'%' not in name:
1648 name = name + b'%' + self._extrafilterid
1648 name = name + b'%' + self._extrafilterid
1649
1649
1650 cls = repoview.newtype(self.unfiltered().__class__)
1650 cls = repoview.newtype(self.unfiltered().__class__)
1651 return cls(self, name, visibilityexceptions)
1651 return cls(self, name, visibilityexceptions)
1652
1652
1653 @mixedrepostorecache(
1653 @mixedrepostorecache(
1654 (b'bookmarks', b'plain'),
1654 (b'bookmarks', b'plain'),
1655 (b'bookmarks.current', b'plain'),
1655 (b'bookmarks.current', b'plain'),
1656 (b'bookmarks', b''),
1656 (b'bookmarks', b''),
1657 (b'00changelog.i', b''),
1657 (b'00changelog.i', b''),
1658 )
1658 )
1659 def _bookmarks(self):
1659 def _bookmarks(self):
1660 # Since the multiple files involved in the transaction cannot be
1660 # Since the multiple files involved in the transaction cannot be
1661 # written atomically (with current repository format), there is a race
1661 # written atomically (with current repository format), there is a race
1662 # condition here.
1662 # condition here.
1663 #
1663 #
1664 # 1) changelog content A is read
1664 # 1) changelog content A is read
1665 # 2) outside transaction update changelog to content B
1665 # 2) outside transaction update changelog to content B
1666 # 3) outside transaction update bookmark file referring to content B
1666 # 3) outside transaction update bookmark file referring to content B
1667 # 4) bookmarks file content is read and filtered against changelog-A
1667 # 4) bookmarks file content is read and filtered against changelog-A
1668 #
1668 #
1669 # When this happens, bookmarks against nodes missing from A are dropped.
1669 # When this happens, bookmarks against nodes missing from A are dropped.
1670 #
1670 #
1671 # Having this happening during read is not great, but it become worse
1671 # Having this happening during read is not great, but it become worse
1672 # when this happen during write because the bookmarks to the "unknown"
1672 # when this happen during write because the bookmarks to the "unknown"
1673 # nodes will be dropped for good. However, writes happen within locks.
1673 # nodes will be dropped for good. However, writes happen within locks.
1674 # This locking makes it possible to have a race free consistent read.
1674 # This locking makes it possible to have a race free consistent read.
1675 # For this purpose data read from disc before locking are
1675 # For this purpose data read from disc before locking are
1676 # "invalidated" right after the locks are taken. This invalidations are
1676 # "invalidated" right after the locks are taken. This invalidations are
1677 # "light", the `filecache` mechanism keep the data in memory and will
1677 # "light", the `filecache` mechanism keep the data in memory and will
1678 # reuse them if the underlying files did not changed. Not parsing the
1678 # reuse them if the underlying files did not changed. Not parsing the
1679 # same data multiple times helps performances.
1679 # same data multiple times helps performances.
1680 #
1680 #
1681 # Unfortunately in the case describe above, the files tracked by the
1681 # Unfortunately in the case describe above, the files tracked by the
1682 # bookmarks file cache might not have changed, but the in-memory
1682 # bookmarks file cache might not have changed, but the in-memory
1683 # content is still "wrong" because we used an older changelog content
1683 # content is still "wrong" because we used an older changelog content
1684 # to process the on-disk data. So after locking, the changelog would be
1684 # to process the on-disk data. So after locking, the changelog would be
1685 # refreshed but `_bookmarks` would be preserved.
1685 # refreshed but `_bookmarks` would be preserved.
1686 # Adding `00changelog.i` to the list of tracked file is not
1686 # Adding `00changelog.i` to the list of tracked file is not
1687 # enough, because at the time we build the content for `_bookmarks` in
1687 # enough, because at the time we build the content for `_bookmarks` in
1688 # (4), the changelog file has already diverged from the content used
1688 # (4), the changelog file has already diverged from the content used
1689 # for loading `changelog` in (1)
1689 # for loading `changelog` in (1)
1690 #
1690 #
1691 # To prevent the issue, we force the changelog to be explicitly
1691 # To prevent the issue, we force the changelog to be explicitly
1692 # reloaded while computing `_bookmarks`. The data race can still happen
1692 # reloaded while computing `_bookmarks`. The data race can still happen
1693 # without the lock (with a narrower window), but it would no longer go
1693 # without the lock (with a narrower window), but it would no longer go
1694 # undetected during the lock time refresh.
1694 # undetected during the lock time refresh.
1695 #
1695 #
1696 # The new schedule is as follow
1696 # The new schedule is as follow
1697 #
1697 #
1698 # 1) filecache logic detect that `_bookmarks` needs to be computed
1698 # 1) filecache logic detect that `_bookmarks` needs to be computed
1699 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1699 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1700 # 3) We force `changelog` filecache to be tested
1700 # 3) We force `changelog` filecache to be tested
1701 # 4) cachestat for `changelog` are captured (for changelog)
1701 # 4) cachestat for `changelog` are captured (for changelog)
1702 # 5) `_bookmarks` is computed and cached
1702 # 5) `_bookmarks` is computed and cached
1703 #
1703 #
1704 # The step in (3) ensure we have a changelog at least as recent as the
1704 # The step in (3) ensure we have a changelog at least as recent as the
1705 # cache stat computed in (1). As a result at locking time:
1705 # cache stat computed in (1). As a result at locking time:
1706 # * if the changelog did not changed since (1) -> we can reuse the data
1706 # * if the changelog did not changed since (1) -> we can reuse the data
1707 # * otherwise -> the bookmarks get refreshed.
1707 # * otherwise -> the bookmarks get refreshed.
1708 self._refreshchangelog()
1708 self._refreshchangelog()
1709 return bookmarks.bmstore(self)
1709 return bookmarks.bmstore(self)
1710
1710
1711 def _refreshchangelog(self):
1711 def _refreshchangelog(self):
1712 """make sure the in memory changelog match the on-disk one"""
1712 """make sure the in memory changelog match the on-disk one"""
1713 if 'changelog' in vars(self) and self.currenttransaction() is None:
1713 if 'changelog' in vars(self) and self.currenttransaction() is None:
1714 del self.changelog
1714 del self.changelog
1715
1715
1716 @property
1716 @property
1717 def _activebookmark(self):
1717 def _activebookmark(self):
1718 return self._bookmarks.active
1718 return self._bookmarks.active
1719
1719
1720 # _phasesets depend on changelog. what we need is to call
1720 # _phasesets depend on changelog. what we need is to call
1721 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1721 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1722 # can't be easily expressed in filecache mechanism.
1722 # can't be easily expressed in filecache mechanism.
1723 @storecache(b'phaseroots', b'00changelog.i')
1723 @storecache(b'phaseroots', b'00changelog.i')
1724 def _phasecache(self):
1724 def _phasecache(self):
1725 return phases.phasecache(self, self._phasedefaults)
1725 return phases.phasecache(self, self._phasedefaults)
1726
1726
1727 @storecache(b'obsstore')
1727 @storecache(b'obsstore')
1728 def obsstore(self):
1728 def obsstore(self):
1729 return obsolete.makestore(self.ui, self)
1729 return obsolete.makestore(self.ui, self)
1730
1730
1731 @changelogcache()
1731 @changelogcache()
1732 def changelog(repo):
1732 def changelog(repo):
1733 # load dirstate before changelog to avoid race see issue6303
1733 # load dirstate before changelog to avoid race see issue6303
1734 repo.dirstate.prefetch_parents()
1734 repo.dirstate.prefetch_parents()
1735 return repo.store.changelog(
1735 return repo.store.changelog(
1736 txnutil.mayhavepending(repo.root),
1736 txnutil.mayhavepending(repo.root),
1737 concurrencychecker=revlogchecker.get_checker(repo.ui, b'changelog'),
1737 concurrencychecker=revlogchecker.get_checker(repo.ui, b'changelog'),
1738 )
1738 )
1739
1739
1740 @manifestlogcache()
1740 @manifestlogcache()
1741 def manifestlog(self):
1741 def manifestlog(self):
1742 return self.store.manifestlog(self, self._storenarrowmatch)
1742 return self.store.manifestlog(self, self._storenarrowmatch)
1743
1743
1744 @repofilecache(b'dirstate')
1744 @repofilecache(b'dirstate')
1745 def dirstate(self):
1745 def dirstate(self):
1746 return self._makedirstate()
1746 return self._makedirstate()
1747
1747
1748 def _makedirstate(self):
1748 def _makedirstate(self):
1749 """Extension point for wrapping the dirstate per-repo."""
1749 """Extension point for wrapping the dirstate per-repo."""
1750 sparsematchfn = None
1750 sparsematchfn = None
1751 if sparse.use_sparse(self):
1751 if sparse.use_sparse(self):
1752 sparsematchfn = lambda: sparse.matcher(self)
1752 sparsematchfn = lambda: sparse.matcher(self)
1753 v2_req = requirementsmod.DIRSTATE_V2_REQUIREMENT
1753 v2_req = requirementsmod.DIRSTATE_V2_REQUIREMENT
1754 th = requirementsmod.DIRSTATE_TRACKED_HINT_V1
1754 th = requirementsmod.DIRSTATE_TRACKED_HINT_V1
1755 use_dirstate_v2 = v2_req in self.requirements
1755 use_dirstate_v2 = v2_req in self.requirements
1756 use_tracked_hint = th in self.requirements
1756 use_tracked_hint = th in self.requirements
1757
1757
1758 return dirstate.dirstate(
1758 return dirstate.dirstate(
1759 self.vfs,
1759 self.vfs,
1760 self.ui,
1760 self.ui,
1761 self.root,
1761 self.root,
1762 self._dirstatevalidate,
1762 self._dirstatevalidate,
1763 sparsematchfn,
1763 sparsematchfn,
1764 self.nodeconstants,
1764 self.nodeconstants,
1765 use_dirstate_v2,
1765 use_dirstate_v2,
1766 use_tracked_hint=use_tracked_hint,
1766 use_tracked_hint=use_tracked_hint,
1767 )
1767 )
1768
1768
1769 def _dirstatevalidate(self, node):
1769 def _dirstatevalidate(self, node):
1770 try:
1770 try:
1771 self.changelog.rev(node)
1771 self.changelog.rev(node)
1772 return node
1772 return node
1773 except error.LookupError:
1773 except error.LookupError:
1774 if not self._dirstatevalidatewarned:
1774 if not self._dirstatevalidatewarned:
1775 self._dirstatevalidatewarned = True
1775 self._dirstatevalidatewarned = True
1776 self.ui.warn(
1776 self.ui.warn(
1777 _(b"warning: ignoring unknown working parent %s!\n")
1777 _(b"warning: ignoring unknown working parent %s!\n")
1778 % short(node)
1778 % short(node)
1779 )
1779 )
1780 return self.nullid
1780 return self.nullid
1781
1781
1782 @storecache(narrowspec.FILENAME)
1782 @storecache(narrowspec.FILENAME)
1783 def narrowpats(self):
1783 def narrowpats(self):
1784 """matcher patterns for this repository's narrowspec
1784 """matcher patterns for this repository's narrowspec
1785
1785
1786 A tuple of (includes, excludes).
1786 A tuple of (includes, excludes).
1787 """
1787 """
1788 return narrowspec.load(self)
1788 return narrowspec.load(self)
1789
1789
1790 @storecache(narrowspec.FILENAME)
1790 @storecache(narrowspec.FILENAME)
1791 def _storenarrowmatch(self):
1791 def _storenarrowmatch(self):
1792 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1792 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1793 return matchmod.always()
1793 return matchmod.always()
1794 include, exclude = self.narrowpats
1794 include, exclude = self.narrowpats
1795 return narrowspec.match(self.root, include=include, exclude=exclude)
1795 return narrowspec.match(self.root, include=include, exclude=exclude)
1796
1796
1797 @storecache(narrowspec.FILENAME)
1797 @storecache(narrowspec.FILENAME)
1798 def _narrowmatch(self):
1798 def _narrowmatch(self):
1799 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1799 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1800 return matchmod.always()
1800 return matchmod.always()
1801 narrowspec.checkworkingcopynarrowspec(self)
1801 narrowspec.checkworkingcopynarrowspec(self)
1802 include, exclude = self.narrowpats
1802 include, exclude = self.narrowpats
1803 return narrowspec.match(self.root, include=include, exclude=exclude)
1803 return narrowspec.match(self.root, include=include, exclude=exclude)
1804
1804
1805 def narrowmatch(self, match=None, includeexact=False):
1805 def narrowmatch(self, match=None, includeexact=False):
1806 """matcher corresponding the the repo's narrowspec
1806 """matcher corresponding the the repo's narrowspec
1807
1807
1808 If `match` is given, then that will be intersected with the narrow
1808 If `match` is given, then that will be intersected with the narrow
1809 matcher.
1809 matcher.
1810
1810
1811 If `includeexact` is True, then any exact matches from `match` will
1811 If `includeexact` is True, then any exact matches from `match` will
1812 be included even if they're outside the narrowspec.
1812 be included even if they're outside the narrowspec.
1813 """
1813 """
1814 if match:
1814 if match:
1815 if includeexact and not self._narrowmatch.always():
1815 if includeexact and not self._narrowmatch.always():
1816 # do not exclude explicitly-specified paths so that they can
1816 # do not exclude explicitly-specified paths so that they can
1817 # be warned later on
1817 # be warned later on
1818 em = matchmod.exact(match.files())
1818 em = matchmod.exact(match.files())
1819 nm = matchmod.unionmatcher([self._narrowmatch, em])
1819 nm = matchmod.unionmatcher([self._narrowmatch, em])
1820 return matchmod.intersectmatchers(match, nm)
1820 return matchmod.intersectmatchers(match, nm)
1821 return matchmod.intersectmatchers(match, self._narrowmatch)
1821 return matchmod.intersectmatchers(match, self._narrowmatch)
1822 return self._narrowmatch
1822 return self._narrowmatch
1823
1823
1824 def setnarrowpats(self, newincludes, newexcludes):
1824 def setnarrowpats(self, newincludes, newexcludes):
1825 narrowspec.save(self, newincludes, newexcludes)
1825 narrowspec.save(self, newincludes, newexcludes)
1826 self.invalidate(clearfilecache=True)
1826 self.invalidate(clearfilecache=True)
1827
1827
1828 @unfilteredpropertycache
1828 @unfilteredpropertycache
1829 def _quick_access_changeid_null(self):
1829 def _quick_access_changeid_null(self):
1830 return {
1830 return {
1831 b'null': (nullrev, self.nodeconstants.nullid),
1831 b'null': (nullrev, self.nodeconstants.nullid),
1832 nullrev: (nullrev, self.nodeconstants.nullid),
1832 nullrev: (nullrev, self.nodeconstants.nullid),
1833 self.nullid: (nullrev, self.nullid),
1833 self.nullid: (nullrev, self.nullid),
1834 }
1834 }
1835
1835
1836 @unfilteredpropertycache
1836 @unfilteredpropertycache
1837 def _quick_access_changeid_wc(self):
1837 def _quick_access_changeid_wc(self):
1838 # also fast path access to the working copy parents
1838 # also fast path access to the working copy parents
1839 # however, only do it for filter that ensure wc is visible.
1839 # however, only do it for filter that ensure wc is visible.
1840 quick = self._quick_access_changeid_null.copy()
1840 quick = self._quick_access_changeid_null.copy()
1841 cl = self.unfiltered().changelog
1841 cl = self.unfiltered().changelog
1842 for node in self.dirstate.parents():
1842 for node in self.dirstate.parents():
1843 if node == self.nullid:
1843 if node == self.nullid:
1844 continue
1844 continue
1845 rev = cl.index.get_rev(node)
1845 rev = cl.index.get_rev(node)
1846 if rev is None:
1846 if rev is None:
1847 # unknown working copy parent case:
1847 # unknown working copy parent case:
1848 #
1848 #
1849 # skip the fast path and let higher code deal with it
1849 # skip the fast path and let higher code deal with it
1850 continue
1850 continue
1851 pair = (rev, node)
1851 pair = (rev, node)
1852 quick[rev] = pair
1852 quick[rev] = pair
1853 quick[node] = pair
1853 quick[node] = pair
1854 # also add the parents of the parents
1854 # also add the parents of the parents
1855 for r in cl.parentrevs(rev):
1855 for r in cl.parentrevs(rev):
1856 if r == nullrev:
1856 if r == nullrev:
1857 continue
1857 continue
1858 n = cl.node(r)
1858 n = cl.node(r)
1859 pair = (r, n)
1859 pair = (r, n)
1860 quick[r] = pair
1860 quick[r] = pair
1861 quick[n] = pair
1861 quick[n] = pair
1862 p1node = self.dirstate.p1()
1862 p1node = self.dirstate.p1()
1863 if p1node != self.nullid:
1863 if p1node != self.nullid:
1864 quick[b'.'] = quick[p1node]
1864 quick[b'.'] = quick[p1node]
1865 return quick
1865 return quick
1866
1866
1867 @unfilteredmethod
1867 @unfilteredmethod
1868 def _quick_access_changeid_invalidate(self):
1868 def _quick_access_changeid_invalidate(self):
1869 if '_quick_access_changeid_wc' in vars(self):
1869 if '_quick_access_changeid_wc' in vars(self):
1870 del self.__dict__['_quick_access_changeid_wc']
1870 del self.__dict__['_quick_access_changeid_wc']
1871
1871
1872 @property
1872 @property
1873 def _quick_access_changeid(self):
1873 def _quick_access_changeid(self):
1874 """an helper dictionnary for __getitem__ calls
1874 """an helper dictionnary for __getitem__ calls
1875
1875
1876 This contains a list of symbol we can recognise right away without
1876 This contains a list of symbol we can recognise right away without
1877 further processing.
1877 further processing.
1878 """
1878 """
1879 if self.filtername in repoview.filter_has_wc:
1879 if self.filtername in repoview.filter_has_wc:
1880 return self._quick_access_changeid_wc
1880 return self._quick_access_changeid_wc
1881 return self._quick_access_changeid_null
1881 return self._quick_access_changeid_null
1882
1882
1883 def __getitem__(self, changeid):
1883 def __getitem__(self, changeid):
1884 # dealing with special cases
1884 # dealing with special cases
1885 if changeid is None:
1885 if changeid is None:
1886 return context.workingctx(self)
1886 return context.workingctx(self)
1887 if isinstance(changeid, context.basectx):
1887 if isinstance(changeid, context.basectx):
1888 return changeid
1888 return changeid
1889
1889
1890 # dealing with multiple revisions
1890 # dealing with multiple revisions
1891 if isinstance(changeid, slice):
1891 if isinstance(changeid, slice):
1892 # wdirrev isn't contiguous so the slice shouldn't include it
1892 # wdirrev isn't contiguous so the slice shouldn't include it
1893 return [
1893 return [
1894 self[i]
1894 self[i]
1895 for i in range(*changeid.indices(len(self)))
1895 for i in range(*changeid.indices(len(self)))
1896 if i not in self.changelog.filteredrevs
1896 if i not in self.changelog.filteredrevs
1897 ]
1897 ]
1898
1898
1899 # dealing with some special values
1899 # dealing with some special values
1900 quick_access = self._quick_access_changeid.get(changeid)
1900 quick_access = self._quick_access_changeid.get(changeid)
1901 if quick_access is not None:
1901 if quick_access is not None:
1902 rev, node = quick_access
1902 rev, node = quick_access
1903 return context.changectx(self, rev, node, maybe_filtered=False)
1903 return context.changectx(self, rev, node, maybe_filtered=False)
1904 if changeid == b'tip':
1904 if changeid == b'tip':
1905 node = self.changelog.tip()
1905 node = self.changelog.tip()
1906 rev = self.changelog.rev(node)
1906 rev = self.changelog.rev(node)
1907 return context.changectx(self, rev, node)
1907 return context.changectx(self, rev, node)
1908
1908
1909 # dealing with arbitrary values
1909 # dealing with arbitrary values
1910 try:
1910 try:
1911 if isinstance(changeid, int):
1911 if isinstance(changeid, int):
1912 node = self.changelog.node(changeid)
1912 node = self.changelog.node(changeid)
1913 rev = changeid
1913 rev = changeid
1914 elif changeid == b'.':
1914 elif changeid == b'.':
1915 # this is a hack to delay/avoid loading obsmarkers
1915 # this is a hack to delay/avoid loading obsmarkers
1916 # when we know that '.' won't be hidden
1916 # when we know that '.' won't be hidden
1917 node = self.dirstate.p1()
1917 node = self.dirstate.p1()
1918 rev = self.unfiltered().changelog.rev(node)
1918 rev = self.unfiltered().changelog.rev(node)
1919 elif len(changeid) == self.nodeconstants.nodelen:
1919 elif len(changeid) == self.nodeconstants.nodelen:
1920 try:
1920 try:
1921 node = changeid
1921 node = changeid
1922 rev = self.changelog.rev(changeid)
1922 rev = self.changelog.rev(changeid)
1923 except error.FilteredLookupError:
1923 except error.FilteredLookupError:
1924 changeid = hex(changeid) # for the error message
1924 changeid = hex(changeid) # for the error message
1925 raise
1925 raise
1926 except LookupError:
1926 except LookupError:
1927 # check if it might have come from damaged dirstate
1927 # check if it might have come from damaged dirstate
1928 #
1928 #
1929 # XXX we could avoid the unfiltered if we had a recognizable
1929 # XXX we could avoid the unfiltered if we had a recognizable
1930 # exception for filtered changeset access
1930 # exception for filtered changeset access
1931 if (
1931 if (
1932 self.local()
1932 self.local()
1933 and changeid in self.unfiltered().dirstate.parents()
1933 and changeid in self.unfiltered().dirstate.parents()
1934 ):
1934 ):
1935 msg = _(b"working directory has unknown parent '%s'!")
1935 msg = _(b"working directory has unknown parent '%s'!")
1936 raise error.Abort(msg % short(changeid))
1936 raise error.Abort(msg % short(changeid))
1937 changeid = hex(changeid) # for the error message
1937 changeid = hex(changeid) # for the error message
1938 raise
1938 raise
1939
1939
1940 elif len(changeid) == 2 * self.nodeconstants.nodelen:
1940 elif len(changeid) == 2 * self.nodeconstants.nodelen:
1941 node = bin(changeid)
1941 node = bin(changeid)
1942 rev = self.changelog.rev(node)
1942 rev = self.changelog.rev(node)
1943 else:
1943 else:
1944 raise error.ProgrammingError(
1944 raise error.ProgrammingError(
1945 b"unsupported changeid '%s' of type %s"
1945 b"unsupported changeid '%s' of type %s"
1946 % (changeid, pycompat.bytestr(type(changeid)))
1946 % (changeid, pycompat.bytestr(type(changeid)))
1947 )
1947 )
1948
1948
1949 return context.changectx(self, rev, node)
1949 return context.changectx(self, rev, node)
1950
1950
1951 except (error.FilteredIndexError, error.FilteredLookupError):
1951 except (error.FilteredIndexError, error.FilteredLookupError):
1952 raise error.FilteredRepoLookupError(
1952 raise error.FilteredRepoLookupError(
1953 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1953 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1954 )
1954 )
1955 except (IndexError, LookupError):
1955 except (IndexError, LookupError):
1956 raise error.RepoLookupError(
1956 raise error.RepoLookupError(
1957 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1957 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1958 )
1958 )
1959 except error.WdirUnsupported:
1959 except error.WdirUnsupported:
1960 return context.workingctx(self)
1960 return context.workingctx(self)
1961
1961
1962 def __contains__(self, changeid):
1962 def __contains__(self, changeid):
1963 """True if the given changeid exists"""
1963 """True if the given changeid exists"""
1964 try:
1964 try:
1965 self[changeid]
1965 self[changeid]
1966 return True
1966 return True
1967 except error.RepoLookupError:
1967 except error.RepoLookupError:
1968 return False
1968 return False
1969
1969
1970 def __nonzero__(self):
1970 def __nonzero__(self):
1971 return True
1971 return True
1972
1972
1973 __bool__ = __nonzero__
1973 __bool__ = __nonzero__
1974
1974
1975 def __len__(self):
1975 def __len__(self):
1976 # no need to pay the cost of repoview.changelog
1976 # no need to pay the cost of repoview.changelog
1977 unfi = self.unfiltered()
1977 unfi = self.unfiltered()
1978 return len(unfi.changelog)
1978 return len(unfi.changelog)
1979
1979
1980 def __iter__(self):
1980 def __iter__(self):
1981 return iter(self.changelog)
1981 return iter(self.changelog)
1982
1982
1983 def revs(self, expr, *args):
1983 def revs(self, expr, *args):
1984 """Find revisions matching a revset.
1984 """Find revisions matching a revset.
1985
1985
1986 The revset is specified as a string ``expr`` that may contain
1986 The revset is specified as a string ``expr`` that may contain
1987 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1987 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1988
1988
1989 Revset aliases from the configuration are not expanded. To expand
1989 Revset aliases from the configuration are not expanded. To expand
1990 user aliases, consider calling ``scmutil.revrange()`` or
1990 user aliases, consider calling ``scmutil.revrange()`` or
1991 ``repo.anyrevs([expr], user=True)``.
1991 ``repo.anyrevs([expr], user=True)``.
1992
1992
1993 Returns a smartset.abstractsmartset, which is a list-like interface
1993 Returns a smartset.abstractsmartset, which is a list-like interface
1994 that contains integer revisions.
1994 that contains integer revisions.
1995 """
1995 """
1996 tree = revsetlang.spectree(expr, *args)
1996 tree = revsetlang.spectree(expr, *args)
1997 return revset.makematcher(tree)(self)
1997 return revset.makematcher(tree)(self)
1998
1998
1999 def set(self, expr, *args):
1999 def set(self, expr, *args):
2000 """Find revisions matching a revset and emit changectx instances.
2000 """Find revisions matching a revset and emit changectx instances.
2001
2001
2002 This is a convenience wrapper around ``revs()`` that iterates the
2002 This is a convenience wrapper around ``revs()`` that iterates the
2003 result and is a generator of changectx instances.
2003 result and is a generator of changectx instances.
2004
2004
2005 Revset aliases from the configuration are not expanded. To expand
2005 Revset aliases from the configuration are not expanded. To expand
2006 user aliases, consider calling ``scmutil.revrange()``.
2006 user aliases, consider calling ``scmutil.revrange()``.
2007 """
2007 """
2008 for r in self.revs(expr, *args):
2008 for r in self.revs(expr, *args):
2009 yield self[r]
2009 yield self[r]
2010
2010
2011 def anyrevs(self, specs, user=False, localalias=None):
2011 def anyrevs(self, specs, user=False, localalias=None):
2012 """Find revisions matching one of the given revsets.
2012 """Find revisions matching one of the given revsets.
2013
2013
2014 Revset aliases from the configuration are not expanded by default. To
2014 Revset aliases from the configuration are not expanded by default. To
2015 expand user aliases, specify ``user=True``. To provide some local
2015 expand user aliases, specify ``user=True``. To provide some local
2016 definitions overriding user aliases, set ``localalias`` to
2016 definitions overriding user aliases, set ``localalias`` to
2017 ``{name: definitionstring}``.
2017 ``{name: definitionstring}``.
2018 """
2018 """
2019 if specs == [b'null']:
2019 if specs == [b'null']:
2020 return revset.baseset([nullrev])
2020 return revset.baseset([nullrev])
2021 if specs == [b'.']:
2021 if specs == [b'.']:
2022 quick_data = self._quick_access_changeid.get(b'.')
2022 quick_data = self._quick_access_changeid.get(b'.')
2023 if quick_data is not None:
2023 if quick_data is not None:
2024 return revset.baseset([quick_data[0]])
2024 return revset.baseset([quick_data[0]])
2025 if user:
2025 if user:
2026 m = revset.matchany(
2026 m = revset.matchany(
2027 self.ui,
2027 self.ui,
2028 specs,
2028 specs,
2029 lookup=revset.lookupfn(self),
2029 lookup=revset.lookupfn(self),
2030 localalias=localalias,
2030 localalias=localalias,
2031 )
2031 )
2032 else:
2032 else:
2033 m = revset.matchany(None, specs, localalias=localalias)
2033 m = revset.matchany(None, specs, localalias=localalias)
2034 return m(self)
2034 return m(self)
2035
2035
2036 def url(self):
2036 def url(self):
2037 return b'file:' + self.root
2037 return b'file:' + self.root
2038
2038
2039 def hook(self, name, throw=False, **args):
2039 def hook(self, name, throw=False, **args):
2040 """Call a hook, passing this repo instance.
2040 """Call a hook, passing this repo instance.
2041
2041
2042 This a convenience method to aid invoking hooks. Extensions likely
2042 This a convenience method to aid invoking hooks. Extensions likely
2043 won't call this unless they have registered a custom hook or are
2043 won't call this unless they have registered a custom hook or are
2044 replacing code that is expected to call a hook.
2044 replacing code that is expected to call a hook.
2045 """
2045 """
2046 return hook.hook(self.ui, self, name, throw, **args)
2046 return hook.hook(self.ui, self, name, throw, **args)
2047
2047
2048 @filteredpropertycache
2048 @filteredpropertycache
2049 def _tagscache(self):
2049 def _tagscache(self):
2050 """Returns a tagscache object that contains various tags related
2050 """Returns a tagscache object that contains various tags related
2051 caches."""
2051 caches."""
2052
2052
2053 # This simplifies its cache management by having one decorated
2053 # This simplifies its cache management by having one decorated
2054 # function (this one) and the rest simply fetch things from it.
2054 # function (this one) and the rest simply fetch things from it.
2055 class tagscache:
2055 class tagscache:
2056 def __init__(self):
2056 def __init__(self):
2057 # These two define the set of tags for this repository. tags
2057 # These two define the set of tags for this repository. tags
2058 # maps tag name to node; tagtypes maps tag name to 'global' or
2058 # maps tag name to node; tagtypes maps tag name to 'global' or
2059 # 'local'. (Global tags are defined by .hgtags across all
2059 # 'local'. (Global tags are defined by .hgtags across all
2060 # heads, and local tags are defined in .hg/localtags.)
2060 # heads, and local tags are defined in .hg/localtags.)
2061 # They constitute the in-memory cache of tags.
2061 # They constitute the in-memory cache of tags.
2062 self.tags = self.tagtypes = None
2062 self.tags = self.tagtypes = None
2063
2063
2064 self.nodetagscache = self.tagslist = None
2064 self.nodetagscache = self.tagslist = None
2065
2065
2066 cache = tagscache()
2066 cache = tagscache()
2067 cache.tags, cache.tagtypes = self._findtags()
2067 cache.tags, cache.tagtypes = self._findtags()
2068
2068
2069 return cache
2069 return cache
2070
2070
2071 def tags(self):
2071 def tags(self):
2072 '''return a mapping of tag to node'''
2072 '''return a mapping of tag to node'''
2073 t = {}
2073 t = {}
2074 if self.changelog.filteredrevs:
2074 if self.changelog.filteredrevs:
2075 tags, tt = self._findtags()
2075 tags, tt = self._findtags()
2076 else:
2076 else:
2077 tags = self._tagscache.tags
2077 tags = self._tagscache.tags
2078 rev = self.changelog.rev
2078 rev = self.changelog.rev
2079 for k, v in tags.items():
2079 for k, v in tags.items():
2080 try:
2080 try:
2081 # ignore tags to unknown nodes
2081 # ignore tags to unknown nodes
2082 rev(v)
2082 rev(v)
2083 t[k] = v
2083 t[k] = v
2084 except (error.LookupError, ValueError):
2084 except (error.LookupError, ValueError):
2085 pass
2085 pass
2086 return t
2086 return t
2087
2087
2088 def _findtags(self):
2088 def _findtags(self):
2089 """Do the hard work of finding tags. Return a pair of dicts
2089 """Do the hard work of finding tags. Return a pair of dicts
2090 (tags, tagtypes) where tags maps tag name to node, and tagtypes
2090 (tags, tagtypes) where tags maps tag name to node, and tagtypes
2091 maps tag name to a string like \'global\' or \'local\'.
2091 maps tag name to a string like \'global\' or \'local\'.
2092 Subclasses or extensions are free to add their own tags, but
2092 Subclasses or extensions are free to add their own tags, but
2093 should be aware that the returned dicts will be retained for the
2093 should be aware that the returned dicts will be retained for the
2094 duration of the localrepo object."""
2094 duration of the localrepo object."""
2095
2095
2096 # XXX what tagtype should subclasses/extensions use? Currently
2096 # XXX what tagtype should subclasses/extensions use? Currently
2097 # mq and bookmarks add tags, but do not set the tagtype at all.
2097 # mq and bookmarks add tags, but do not set the tagtype at all.
2098 # Should each extension invent its own tag type? Should there
2098 # Should each extension invent its own tag type? Should there
2099 # be one tagtype for all such "virtual" tags? Or is the status
2099 # be one tagtype for all such "virtual" tags? Or is the status
2100 # quo fine?
2100 # quo fine?
2101
2101
2102 # map tag name to (node, hist)
2102 # map tag name to (node, hist)
2103 alltags = tagsmod.findglobaltags(self.ui, self)
2103 alltags = tagsmod.findglobaltags(self.ui, self)
2104 # map tag name to tag type
2104 # map tag name to tag type
2105 tagtypes = {tag: b'global' for tag in alltags}
2105 tagtypes = {tag: b'global' for tag in alltags}
2106
2106
2107 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
2107 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
2108
2108
2109 # Build the return dicts. Have to re-encode tag names because
2109 # Build the return dicts. Have to re-encode tag names because
2110 # the tags module always uses UTF-8 (in order not to lose info
2110 # the tags module always uses UTF-8 (in order not to lose info
2111 # writing to the cache), but the rest of Mercurial wants them in
2111 # writing to the cache), but the rest of Mercurial wants them in
2112 # local encoding.
2112 # local encoding.
2113 tags = {}
2113 tags = {}
2114 for (name, (node, hist)) in alltags.items():
2114 for (name, (node, hist)) in alltags.items():
2115 if node != self.nullid:
2115 if node != self.nullid:
2116 tags[encoding.tolocal(name)] = node
2116 tags[encoding.tolocal(name)] = node
2117 tags[b'tip'] = self.changelog.tip()
2117 tags[b'tip'] = self.changelog.tip()
2118 tagtypes = {
2118 tagtypes = {
2119 encoding.tolocal(name): value for (name, value) in tagtypes.items()
2119 encoding.tolocal(name): value for (name, value) in tagtypes.items()
2120 }
2120 }
2121 return (tags, tagtypes)
2121 return (tags, tagtypes)
2122
2122
2123 def tagtype(self, tagname):
2123 def tagtype(self, tagname):
2124 """
2124 """
2125 return the type of the given tag. result can be:
2125 return the type of the given tag. result can be:
2126
2126
2127 'local' : a local tag
2127 'local' : a local tag
2128 'global' : a global tag
2128 'global' : a global tag
2129 None : tag does not exist
2129 None : tag does not exist
2130 """
2130 """
2131
2131
2132 return self._tagscache.tagtypes.get(tagname)
2132 return self._tagscache.tagtypes.get(tagname)
2133
2133
2134 def tagslist(self):
2134 def tagslist(self):
2135 '''return a list of tags ordered by revision'''
2135 '''return a list of tags ordered by revision'''
2136 if not self._tagscache.tagslist:
2136 if not self._tagscache.tagslist:
2137 l = []
2137 l = []
2138 for t, n in self.tags().items():
2138 for t, n in self.tags().items():
2139 l.append((self.changelog.rev(n), t, n))
2139 l.append((self.changelog.rev(n), t, n))
2140 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
2140 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
2141
2141
2142 return self._tagscache.tagslist
2142 return self._tagscache.tagslist
2143
2143
2144 def nodetags(self, node):
2144 def nodetags(self, node):
2145 '''return the tags associated with a node'''
2145 '''return the tags associated with a node'''
2146 if not self._tagscache.nodetagscache:
2146 if not self._tagscache.nodetagscache:
2147 nodetagscache = {}
2147 nodetagscache = {}
2148 for t, n in self._tagscache.tags.items():
2148 for t, n in self._tagscache.tags.items():
2149 nodetagscache.setdefault(n, []).append(t)
2149 nodetagscache.setdefault(n, []).append(t)
2150 for tags in nodetagscache.values():
2150 for tags in nodetagscache.values():
2151 tags.sort()
2151 tags.sort()
2152 self._tagscache.nodetagscache = nodetagscache
2152 self._tagscache.nodetagscache = nodetagscache
2153 return self._tagscache.nodetagscache.get(node, [])
2153 return self._tagscache.nodetagscache.get(node, [])
2154
2154
2155 def nodebookmarks(self, node):
2155 def nodebookmarks(self, node):
2156 """return the list of bookmarks pointing to the specified node"""
2156 """return the list of bookmarks pointing to the specified node"""
2157 return self._bookmarks.names(node)
2157 return self._bookmarks.names(node)
2158
2158
2159 def branchmap(self):
2159 def branchmap(self):
2160 """returns a dictionary {branch: [branchheads]} with branchheads
2160 """returns a dictionary {branch: [branchheads]} with branchheads
2161 ordered by increasing revision number"""
2161 ordered by increasing revision number"""
2162 return self._branchcaches[self]
2162 return self._branchcaches[self]
2163
2163
2164 @unfilteredmethod
2164 @unfilteredmethod
2165 def revbranchcache(self):
2165 def revbranchcache(self):
2166 if not self._revbranchcache:
2166 if not self._revbranchcache:
2167 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
2167 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
2168 return self._revbranchcache
2168 return self._revbranchcache
2169
2169
2170 def register_changeset(self, rev, changelogrevision):
2170 def register_changeset(self, rev, changelogrevision):
2171 self.revbranchcache().setdata(rev, changelogrevision)
2171 self.revbranchcache().setdata(rev, changelogrevision)
2172
2172
2173 def branchtip(self, branch, ignoremissing=False):
2173 def branchtip(self, branch, ignoremissing=False):
2174 """return the tip node for a given branch
2174 """return the tip node for a given branch
2175
2175
2176 If ignoremissing is True, then this method will not raise an error.
2176 If ignoremissing is True, then this method will not raise an error.
2177 This is helpful for callers that only expect None for a missing branch
2177 This is helpful for callers that only expect None for a missing branch
2178 (e.g. namespace).
2178 (e.g. namespace).
2179
2179
2180 """
2180 """
2181 try:
2181 try:
2182 return self.branchmap().branchtip(branch)
2182 return self.branchmap().branchtip(branch)
2183 except KeyError:
2183 except KeyError:
2184 if not ignoremissing:
2184 if not ignoremissing:
2185 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
2185 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
2186 else:
2186 else:
2187 pass
2187 pass
2188
2188
2189 def lookup(self, key):
2189 def lookup(self, key):
2190 node = scmutil.revsymbol(self, key).node()
2190 node = scmutil.revsymbol(self, key).node()
2191 if node is None:
2191 if node is None:
2192 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
2192 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
2193 return node
2193 return node
2194
2194
2195 def lookupbranch(self, key):
2195 def lookupbranch(self, key):
2196 if self.branchmap().hasbranch(key):
2196 if self.branchmap().hasbranch(key):
2197 return key
2197 return key
2198
2198
2199 return scmutil.revsymbol(self, key).branch()
2199 return scmutil.revsymbol(self, key).branch()
2200
2200
2201 def known(self, nodes):
2201 def known(self, nodes):
2202 cl = self.changelog
2202 cl = self.changelog
2203 get_rev = cl.index.get_rev
2203 get_rev = cl.index.get_rev
2204 filtered = cl.filteredrevs
2204 filtered = cl.filteredrevs
2205 result = []
2205 result = []
2206 for n in nodes:
2206 for n in nodes:
2207 r = get_rev(n)
2207 r = get_rev(n)
2208 resp = not (r is None or r in filtered)
2208 resp = not (r is None or r in filtered)
2209 result.append(resp)
2209 result.append(resp)
2210 return result
2210 return result
2211
2211
2212 def local(self):
2212 def local(self):
2213 return self
2213 return self
2214
2214
2215 def publishing(self):
2215 def publishing(self):
2216 # it's safe (and desirable) to trust the publish flag unconditionally
2216 # it's safe (and desirable) to trust the publish flag unconditionally
2217 # so that we don't finalize changes shared between users via ssh or nfs
2217 # so that we don't finalize changes shared between users via ssh or nfs
2218 return self.ui.configbool(b'phases', b'publish', untrusted=True)
2218 return self.ui.configbool(b'phases', b'publish', untrusted=True)
2219
2219
2220 def cancopy(self):
2220 def cancopy(self):
2221 # so statichttprepo's override of local() works
2221 # so statichttprepo's override of local() works
2222 if not self.local():
2222 if not self.local():
2223 return False
2223 return False
2224 if not self.publishing():
2224 if not self.publishing():
2225 return True
2225 return True
2226 # if publishing we can't copy if there is filtered content
2226 # if publishing we can't copy if there is filtered content
2227 return not self.filtered(b'visible').changelog.filteredrevs
2227 return not self.filtered(b'visible').changelog.filteredrevs
2228
2228
2229 def shared(self):
2229 def shared(self):
2230 '''the type of shared repository (None if not shared)'''
2230 '''the type of shared repository (None if not shared)'''
2231 if self.sharedpath != self.path:
2231 if self.sharedpath != self.path:
2232 return b'store'
2232 return b'store'
2233 return None
2233 return None
2234
2234
2235 def wjoin(self, f, *insidef):
2235 def wjoin(self, f, *insidef):
2236 return self.vfs.reljoin(self.root, f, *insidef)
2236 return self.vfs.reljoin(self.root, f, *insidef)
2237
2237
2238 def setparents(self, p1, p2=None):
2238 def setparents(self, p1, p2=None):
2239 if p2 is None:
2239 if p2 is None:
2240 p2 = self.nullid
2240 p2 = self.nullid
2241 self[None].setparents(p1, p2)
2241 self[None].setparents(p1, p2)
2242 self._quick_access_changeid_invalidate()
2242 self._quick_access_changeid_invalidate()
2243
2243
2244 def filectx(self, path, changeid=None, fileid=None, changectx=None):
2244 def filectx(self, path, changeid=None, fileid=None, changectx=None):
2245 """changeid must be a changeset revision, if specified.
2245 """changeid must be a changeset revision, if specified.
2246 fileid can be a file revision or node."""
2246 fileid can be a file revision or node."""
2247 return context.filectx(
2247 return context.filectx(
2248 self, path, changeid, fileid, changectx=changectx
2248 self, path, changeid, fileid, changectx=changectx
2249 )
2249 )
2250
2250
2251 def getcwd(self):
2251 def getcwd(self):
2252 return self.dirstate.getcwd()
2252 return self.dirstate.getcwd()
2253
2253
2254 def pathto(self, f, cwd=None):
2254 def pathto(self, f, cwd=None):
2255 return self.dirstate.pathto(f, cwd)
2255 return self.dirstate.pathto(f, cwd)
2256
2256
2257 def _loadfilter(self, filter):
2257 def _loadfilter(self, filter):
2258 if filter not in self._filterpats:
2258 if filter not in self._filterpats:
2259 l = []
2259 l = []
2260 for pat, cmd in self.ui.configitems(filter):
2260 for pat, cmd in self.ui.configitems(filter):
2261 if cmd == b'!':
2261 if cmd == b'!':
2262 continue
2262 continue
2263 mf = matchmod.match(self.root, b'', [pat])
2263 mf = matchmod.match(self.root, b'', [pat])
2264 fn = None
2264 fn = None
2265 params = cmd
2265 params = cmd
2266 for name, filterfn in self._datafilters.items():
2266 for name, filterfn in self._datafilters.items():
2267 if cmd.startswith(name):
2267 if cmd.startswith(name):
2268 fn = filterfn
2268 fn = filterfn
2269 params = cmd[len(name) :].lstrip()
2269 params = cmd[len(name) :].lstrip()
2270 break
2270 break
2271 if not fn:
2271 if not fn:
2272 fn = lambda s, c, **kwargs: procutil.filter(s, c)
2272 fn = lambda s, c, **kwargs: procutil.filter(s, c)
2273 fn.__name__ = 'commandfilter'
2273 fn.__name__ = 'commandfilter'
2274 # Wrap old filters not supporting keyword arguments
2274 # Wrap old filters not supporting keyword arguments
2275 if not pycompat.getargspec(fn)[2]:
2275 if not pycompat.getargspec(fn)[2]:
2276 oldfn = fn
2276 oldfn = fn
2277 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
2277 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
2278 fn.__name__ = 'compat-' + oldfn.__name__
2278 fn.__name__ = 'compat-' + oldfn.__name__
2279 l.append((mf, fn, params))
2279 l.append((mf, fn, params))
2280 self._filterpats[filter] = l
2280 self._filterpats[filter] = l
2281 return self._filterpats[filter]
2281 return self._filterpats[filter]
2282
2282
2283 def _filter(self, filterpats, filename, data):
2283 def _filter(self, filterpats, filename, data):
2284 for mf, fn, cmd in filterpats:
2284 for mf, fn, cmd in filterpats:
2285 if mf(filename):
2285 if mf(filename):
2286 self.ui.debug(
2286 self.ui.debug(
2287 b"filtering %s through %s\n"
2287 b"filtering %s through %s\n"
2288 % (filename, cmd or pycompat.sysbytes(fn.__name__))
2288 % (filename, cmd or pycompat.sysbytes(fn.__name__))
2289 )
2289 )
2290 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
2290 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
2291 break
2291 break
2292
2292
2293 return data
2293 return data
2294
2294
2295 @unfilteredpropertycache
2295 @unfilteredpropertycache
2296 def _encodefilterpats(self):
2296 def _encodefilterpats(self):
2297 return self._loadfilter(b'encode')
2297 return self._loadfilter(b'encode')
2298
2298
2299 @unfilteredpropertycache
2299 @unfilteredpropertycache
2300 def _decodefilterpats(self):
2300 def _decodefilterpats(self):
2301 return self._loadfilter(b'decode')
2301 return self._loadfilter(b'decode')
2302
2302
2303 def adddatafilter(self, name, filter):
2303 def adddatafilter(self, name, filter):
2304 self._datafilters[name] = filter
2304 self._datafilters[name] = filter
2305
2305
2306 def wread(self, filename):
2306 def wread(self, filename):
2307 if self.wvfs.islink(filename):
2307 if self.wvfs.islink(filename):
2308 data = self.wvfs.readlink(filename)
2308 data = self.wvfs.readlink(filename)
2309 else:
2309 else:
2310 data = self.wvfs.read(filename)
2310 data = self.wvfs.read(filename)
2311 return self._filter(self._encodefilterpats, filename, data)
2311 return self._filter(self._encodefilterpats, filename, data)
2312
2312
2313 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
2313 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
2314 """write ``data`` into ``filename`` in the working directory
2314 """write ``data`` into ``filename`` in the working directory
2315
2315
2316 This returns length of written (maybe decoded) data.
2316 This returns length of written (maybe decoded) data.
2317 """
2317 """
2318 data = self._filter(self._decodefilterpats, filename, data)
2318 data = self._filter(self._decodefilterpats, filename, data)
2319 if b'l' in flags:
2319 if b'l' in flags:
2320 self.wvfs.symlink(data, filename)
2320 self.wvfs.symlink(data, filename)
2321 else:
2321 else:
2322 self.wvfs.write(
2322 self.wvfs.write(
2323 filename, data, backgroundclose=backgroundclose, **kwargs
2323 filename, data, backgroundclose=backgroundclose, **kwargs
2324 )
2324 )
2325 if b'x' in flags:
2325 if b'x' in flags:
2326 self.wvfs.setflags(filename, False, True)
2326 self.wvfs.setflags(filename, False, True)
2327 else:
2327 else:
2328 self.wvfs.setflags(filename, False, False)
2328 self.wvfs.setflags(filename, False, False)
2329 return len(data)
2329 return len(data)
2330
2330
2331 def wwritedata(self, filename, data):
2331 def wwritedata(self, filename, data):
2332 return self._filter(self._decodefilterpats, filename, data)
2332 return self._filter(self._decodefilterpats, filename, data)
2333
2333
2334 def currenttransaction(self):
2334 def currenttransaction(self):
2335 """return the current transaction or None if non exists"""
2335 """return the current transaction or None if non exists"""
2336 if self._transref:
2336 if self._transref:
2337 tr = self._transref()
2337 tr = self._transref()
2338 else:
2338 else:
2339 tr = None
2339 tr = None
2340
2340
2341 if tr and tr.running():
2341 if tr and tr.running():
2342 return tr
2342 return tr
2343 return None
2343 return None
2344
2344
2345 def transaction(self, desc, report=None):
2345 def transaction(self, desc, report=None):
2346 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
2346 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
2347 b'devel', b'check-locks'
2347 b'devel', b'check-locks'
2348 ):
2348 ):
2349 if self._currentlock(self._lockref) is None:
2349 if self._currentlock(self._lockref) is None:
2350 raise error.ProgrammingError(b'transaction requires locking')
2350 raise error.ProgrammingError(b'transaction requires locking')
2351 tr = self.currenttransaction()
2351 tr = self.currenttransaction()
2352 if tr is not None:
2352 if tr is not None:
2353 return tr.nest(name=desc)
2353 return tr.nest(name=desc)
2354
2354
2355 # abort here if the journal already exists
2355 # abort here if the journal already exists
2356 if self.svfs.exists(b"journal"):
2356 if self.svfs.exists(b"journal"):
2357 raise error.RepoError(
2357 raise error.RepoError(
2358 _(b"abandoned transaction found"),
2358 _(b"abandoned transaction found"),
2359 hint=_(b"run 'hg recover' to clean up transaction"),
2359 hint=_(b"run 'hg recover' to clean up transaction"),
2360 )
2360 )
2361
2361
2362 idbase = b"%.40f#%f" % (random.random(), time.time())
2362 idbase = b"%.40f#%f" % (random.random(), time.time())
2363 ha = hex(hashutil.sha1(idbase).digest())
2363 ha = hex(hashutil.sha1(idbase).digest())
2364 txnid = b'TXN:' + ha
2364 txnid = b'TXN:' + ha
2365 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2365 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2366
2366
2367 self._writejournal(desc)
2367 self._writejournal(desc)
2368 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2368 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2369 if report:
2369 if report:
2370 rp = report
2370 rp = report
2371 else:
2371 else:
2372 rp = self.ui.warn
2372 rp = self.ui.warn
2373 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2373 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2374 # we must avoid cyclic reference between repo and transaction.
2374 # we must avoid cyclic reference between repo and transaction.
2375 reporef = weakref.ref(self)
2375 reporef = weakref.ref(self)
2376 # Code to track tag movement
2376 # Code to track tag movement
2377 #
2377 #
2378 # Since tags are all handled as file content, it is actually quite hard
2378 # Since tags are all handled as file content, it is actually quite hard
2379 # to track these movement from a code perspective. So we fallback to a
2379 # to track these movement from a code perspective. So we fallback to a
2380 # tracking at the repository level. One could envision to track changes
2380 # tracking at the repository level. One could envision to track changes
2381 # to the '.hgtags' file through changegroup apply but that fails to
2381 # to the '.hgtags' file through changegroup apply but that fails to
2382 # cope with case where transaction expose new heads without changegroup
2382 # cope with case where transaction expose new heads without changegroup
2383 # being involved (eg: phase movement).
2383 # being involved (eg: phase movement).
2384 #
2384 #
2385 # For now, We gate the feature behind a flag since this likely comes
2385 # For now, We gate the feature behind a flag since this likely comes
2386 # with performance impacts. The current code run more often than needed
2386 # with performance impacts. The current code run more often than needed
2387 # and do not use caches as much as it could. The current focus is on
2387 # and do not use caches as much as it could. The current focus is on
2388 # the behavior of the feature so we disable it by default. The flag
2388 # the behavior of the feature so we disable it by default. The flag
2389 # will be removed when we are happy with the performance impact.
2389 # will be removed when we are happy with the performance impact.
2390 #
2390 #
2391 # Once this feature is no longer experimental move the following
2391 # Once this feature is no longer experimental move the following
2392 # documentation to the appropriate help section:
2392 # documentation to the appropriate help section:
2393 #
2393 #
2394 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2394 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2395 # tags (new or changed or deleted tags). In addition the details of
2395 # tags (new or changed or deleted tags). In addition the details of
2396 # these changes are made available in a file at:
2396 # these changes are made available in a file at:
2397 # ``REPOROOT/.hg/changes/tags.changes``.
2397 # ``REPOROOT/.hg/changes/tags.changes``.
2398 # Make sure you check for HG_TAG_MOVED before reading that file as it
2398 # Make sure you check for HG_TAG_MOVED before reading that file as it
2399 # might exist from a previous transaction even if no tag were touched
2399 # might exist from a previous transaction even if no tag were touched
2400 # in this one. Changes are recorded in a line base format::
2400 # in this one. Changes are recorded in a line base format::
2401 #
2401 #
2402 # <action> <hex-node> <tag-name>\n
2402 # <action> <hex-node> <tag-name>\n
2403 #
2403 #
2404 # Actions are defined as follow:
2404 # Actions are defined as follow:
2405 # "-R": tag is removed,
2405 # "-R": tag is removed,
2406 # "+A": tag is added,
2406 # "+A": tag is added,
2407 # "-M": tag is moved (old value),
2407 # "-M": tag is moved (old value),
2408 # "+M": tag is moved (new value),
2408 # "+M": tag is moved (new value),
2409 tracktags = lambda x: None
2409 tracktags = lambda x: None
2410 # experimental config: experimental.hook-track-tags
2410 # experimental config: experimental.hook-track-tags
2411 shouldtracktags = self.ui.configbool(
2411 shouldtracktags = self.ui.configbool(
2412 b'experimental', b'hook-track-tags'
2412 b'experimental', b'hook-track-tags'
2413 )
2413 )
2414 if desc != b'strip' and shouldtracktags:
2414 if desc != b'strip' and shouldtracktags:
2415 oldheads = self.changelog.headrevs()
2415 oldheads = self.changelog.headrevs()
2416
2416
2417 def tracktags(tr2):
2417 def tracktags(tr2):
2418 repo = reporef()
2418 repo = reporef()
2419 assert repo is not None # help pytype
2419 assert repo is not None # help pytype
2420 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2420 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2421 newheads = repo.changelog.headrevs()
2421 newheads = repo.changelog.headrevs()
2422 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2422 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2423 # notes: we compare lists here.
2423 # notes: we compare lists here.
2424 # As we do it only once buiding set would not be cheaper
2424 # As we do it only once buiding set would not be cheaper
2425 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2425 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2426 if changes:
2426 if changes:
2427 tr2.hookargs[b'tag_moved'] = b'1'
2427 tr2.hookargs[b'tag_moved'] = b'1'
2428 with repo.vfs(
2428 with repo.vfs(
2429 b'changes/tags.changes', b'w', atomictemp=True
2429 b'changes/tags.changes', b'w', atomictemp=True
2430 ) as changesfile:
2430 ) as changesfile:
2431 # note: we do not register the file to the transaction
2431 # note: we do not register the file to the transaction
2432 # because we needs it to still exist on the transaction
2432 # because we needs it to still exist on the transaction
2433 # is close (for txnclose hooks)
2433 # is close (for txnclose hooks)
2434 tagsmod.writediff(changesfile, changes)
2434 tagsmod.writediff(changesfile, changes)
2435
2435
2436 def validate(tr2):
2436 def validate(tr2):
2437 """will run pre-closing hooks"""
2437 """will run pre-closing hooks"""
2438 # XXX the transaction API is a bit lacking here so we take a hacky
2438 # XXX the transaction API is a bit lacking here so we take a hacky
2439 # path for now
2439 # path for now
2440 #
2440 #
2441 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2441 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2442 # dict is copied before these run. In addition we needs the data
2442 # dict is copied before these run. In addition we needs the data
2443 # available to in memory hooks too.
2443 # available to in memory hooks too.
2444 #
2444 #
2445 # Moreover, we also need to make sure this runs before txnclose
2445 # Moreover, we also need to make sure this runs before txnclose
2446 # hooks and there is no "pending" mechanism that would execute
2446 # hooks and there is no "pending" mechanism that would execute
2447 # logic only if hooks are about to run.
2447 # logic only if hooks are about to run.
2448 #
2448 #
2449 # Fixing this limitation of the transaction is also needed to track
2449 # Fixing this limitation of the transaction is also needed to track
2450 # other families of changes (bookmarks, phases, obsolescence).
2450 # other families of changes (bookmarks, phases, obsolescence).
2451 #
2451 #
2452 # This will have to be fixed before we remove the experimental
2452 # This will have to be fixed before we remove the experimental
2453 # gating.
2453 # gating.
2454 tracktags(tr2)
2454 tracktags(tr2)
2455 repo = reporef()
2455 repo = reporef()
2456 assert repo is not None # help pytype
2456 assert repo is not None # help pytype
2457
2457
2458 singleheadopt = (b'experimental', b'single-head-per-branch')
2458 singleheadopt = (b'experimental', b'single-head-per-branch')
2459 singlehead = repo.ui.configbool(*singleheadopt)
2459 singlehead = repo.ui.configbool(*singleheadopt)
2460 if singlehead:
2460 if singlehead:
2461 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2461 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2462 accountclosed = singleheadsub.get(
2462 accountclosed = singleheadsub.get(
2463 b"account-closed-heads", False
2463 b"account-closed-heads", False
2464 )
2464 )
2465 if singleheadsub.get(b"public-changes-only", False):
2465 if singleheadsub.get(b"public-changes-only", False):
2466 filtername = b"immutable"
2466 filtername = b"immutable"
2467 else:
2467 else:
2468 filtername = b"visible"
2468 filtername = b"visible"
2469 scmutil.enforcesinglehead(
2469 scmutil.enforcesinglehead(
2470 repo, tr2, desc, accountclosed, filtername
2470 repo, tr2, desc, accountclosed, filtername
2471 )
2471 )
2472 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2472 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2473 for name, (old, new) in sorted(
2473 for name, (old, new) in sorted(
2474 tr.changes[b'bookmarks'].items()
2474 tr.changes[b'bookmarks'].items()
2475 ):
2475 ):
2476 args = tr.hookargs.copy()
2476 args = tr.hookargs.copy()
2477 args.update(bookmarks.preparehookargs(name, old, new))
2477 args.update(bookmarks.preparehookargs(name, old, new))
2478 repo.hook(
2478 repo.hook(
2479 b'pretxnclose-bookmark',
2479 b'pretxnclose-bookmark',
2480 throw=True,
2480 throw=True,
2481 **pycompat.strkwargs(args)
2481 **pycompat.strkwargs(args)
2482 )
2482 )
2483 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2483 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2484 cl = repo.unfiltered().changelog
2484 cl = repo.unfiltered().changelog
2485 for revs, (old, new) in tr.changes[b'phases']:
2485 for revs, (old, new) in tr.changes[b'phases']:
2486 for rev in revs:
2486 for rev in revs:
2487 args = tr.hookargs.copy()
2487 args = tr.hookargs.copy()
2488 node = hex(cl.node(rev))
2488 node = hex(cl.node(rev))
2489 args.update(phases.preparehookargs(node, old, new))
2489 args.update(phases.preparehookargs(node, old, new))
2490 repo.hook(
2490 repo.hook(
2491 b'pretxnclose-phase',
2491 b'pretxnclose-phase',
2492 throw=True,
2492 throw=True,
2493 **pycompat.strkwargs(args)
2493 **pycompat.strkwargs(args)
2494 )
2494 )
2495
2495
2496 repo.hook(
2496 repo.hook(
2497 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2497 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2498 )
2498 )
2499
2499
2500 def releasefn(tr, success):
2500 def releasefn(tr, success):
2501 repo = reporef()
2501 repo = reporef()
2502 if repo is None:
2502 if repo is None:
2503 # If the repo has been GC'd (and this release function is being
2503 # If the repo has been GC'd (and this release function is being
2504 # called from transaction.__del__), there's not much we can do,
2504 # called from transaction.__del__), there's not much we can do,
2505 # so just leave the unfinished transaction there and let the
2505 # so just leave the unfinished transaction there and let the
2506 # user run `hg recover`.
2506 # user run `hg recover`.
2507 return
2507 return
2508 if success:
2508 if success:
2509 # this should be explicitly invoked here, because
2509 # this should be explicitly invoked here, because
2510 # in-memory changes aren't written out at closing
2510 # in-memory changes aren't written out at closing
2511 # transaction, if tr.addfilegenerator (via
2511 # transaction, if tr.addfilegenerator (via
2512 # dirstate.write or so) isn't invoked while
2512 # dirstate.write or so) isn't invoked while
2513 # transaction running
2513 # transaction running
2514 repo.dirstate.write(None)
2514 repo.dirstate.write(None)
2515 else:
2515 else:
2516 # discard all changes (including ones already written
2516 # discard all changes (including ones already written
2517 # out) in this transaction
2517 # out) in this transaction
2518 narrowspec.restorebackup(self, b'journal.narrowspec')
2518 narrowspec.restorebackup(self, b'journal.narrowspec')
2519 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2519 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2520 repo.dirstate.restorebackup(None, b'journal.dirstate')
2520 repo.dirstate.restorebackup(None, b'journal.dirstate')
2521
2521
2522 repo.invalidate(clearfilecache=True)
2522 repo.invalidate(clearfilecache=True)
2523
2523
2524 tr = transaction.transaction(
2524 tr = transaction.transaction(
2525 rp,
2525 rp,
2526 self.svfs,
2526 self.svfs,
2527 vfsmap,
2527 vfsmap,
2528 b"journal",
2528 b"journal",
2529 b"undo",
2529 b"undo",
2530 aftertrans(renames),
2530 aftertrans(renames),
2531 self.store.createmode,
2531 self.store.createmode,
2532 validator=validate,
2532 validator=validate,
2533 releasefn=releasefn,
2533 releasefn=releasefn,
2534 checkambigfiles=_cachedfiles,
2534 checkambigfiles=_cachedfiles,
2535 name=desc,
2535 name=desc,
2536 )
2536 )
2537 tr.changes[b'origrepolen'] = len(self)
2537 tr.changes[b'origrepolen'] = len(self)
2538 tr.changes[b'obsmarkers'] = set()
2538 tr.changes[b'obsmarkers'] = set()
2539 tr.changes[b'phases'] = []
2539 tr.changes[b'phases'] = []
2540 tr.changes[b'bookmarks'] = {}
2540 tr.changes[b'bookmarks'] = {}
2541
2541
2542 tr.hookargs[b'txnid'] = txnid
2542 tr.hookargs[b'txnid'] = txnid
2543 tr.hookargs[b'txnname'] = desc
2543 tr.hookargs[b'txnname'] = desc
2544 tr.hookargs[b'changes'] = tr.changes
2544 tr.hookargs[b'changes'] = tr.changes
2545 # note: writing the fncache only during finalize mean that the file is
2545 # note: writing the fncache only during finalize mean that the file is
2546 # outdated when running hooks. As fncache is used for streaming clone,
2546 # outdated when running hooks. As fncache is used for streaming clone,
2547 # this is not expected to break anything that happen during the hooks.
2547 # this is not expected to break anything that happen during the hooks.
2548 tr.addfinalize(b'flush-fncache', self.store.write)
2548 tr.addfinalize(b'flush-fncache', self.store.write)
2549
2549
2550 def txnclosehook(tr2):
2550 def txnclosehook(tr2):
2551 """To be run if transaction is successful, will schedule a hook run"""
2551 """To be run if transaction is successful, will schedule a hook run"""
2552 # Don't reference tr2 in hook() so we don't hold a reference.
2552 # Don't reference tr2 in hook() so we don't hold a reference.
2553 # This reduces memory consumption when there are multiple
2553 # This reduces memory consumption when there are multiple
2554 # transactions per lock. This can likely go away if issue5045
2554 # transactions per lock. This can likely go away if issue5045
2555 # fixes the function accumulation.
2555 # fixes the function accumulation.
2556 hookargs = tr2.hookargs
2556 hookargs = tr2.hookargs
2557
2557
2558 def hookfunc(unused_success):
2558 def hookfunc(unused_success):
2559 repo = reporef()
2559 repo = reporef()
2560 assert repo is not None # help pytype
2560 assert repo is not None # help pytype
2561
2561
2562 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2562 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2563 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2563 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2564 for name, (old, new) in bmchanges:
2564 for name, (old, new) in bmchanges:
2565 args = tr.hookargs.copy()
2565 args = tr.hookargs.copy()
2566 args.update(bookmarks.preparehookargs(name, old, new))
2566 args.update(bookmarks.preparehookargs(name, old, new))
2567 repo.hook(
2567 repo.hook(
2568 b'txnclose-bookmark',
2568 b'txnclose-bookmark',
2569 throw=False,
2569 throw=False,
2570 **pycompat.strkwargs(args)
2570 **pycompat.strkwargs(args)
2571 )
2571 )
2572
2572
2573 if hook.hashook(repo.ui, b'txnclose-phase'):
2573 if hook.hashook(repo.ui, b'txnclose-phase'):
2574 cl = repo.unfiltered().changelog
2574 cl = repo.unfiltered().changelog
2575 phasemv = sorted(
2575 phasemv = sorted(
2576 tr.changes[b'phases'], key=lambda r: r[0][0]
2576 tr.changes[b'phases'], key=lambda r: r[0][0]
2577 )
2577 )
2578 for revs, (old, new) in phasemv:
2578 for revs, (old, new) in phasemv:
2579 for rev in revs:
2579 for rev in revs:
2580 args = tr.hookargs.copy()
2580 args = tr.hookargs.copy()
2581 node = hex(cl.node(rev))
2581 node = hex(cl.node(rev))
2582 args.update(phases.preparehookargs(node, old, new))
2582 args.update(phases.preparehookargs(node, old, new))
2583 repo.hook(
2583 repo.hook(
2584 b'txnclose-phase',
2584 b'txnclose-phase',
2585 throw=False,
2585 throw=False,
2586 **pycompat.strkwargs(args)
2586 **pycompat.strkwargs(args)
2587 )
2587 )
2588
2588
2589 repo.hook(
2589 repo.hook(
2590 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2590 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2591 )
2591 )
2592
2592
2593 repo = reporef()
2593 repo = reporef()
2594 assert repo is not None # help pytype
2594 assert repo is not None # help pytype
2595 repo._afterlock(hookfunc)
2595 repo._afterlock(hookfunc)
2596
2596
2597 tr.addfinalize(b'txnclose-hook', txnclosehook)
2597 tr.addfinalize(b'txnclose-hook', txnclosehook)
2598 # Include a leading "-" to make it happen before the transaction summary
2598 # Include a leading "-" to make it happen before the transaction summary
2599 # reports registered via scmutil.registersummarycallback() whose names
2599 # reports registered via scmutil.registersummarycallback() whose names
2600 # are 00-txnreport etc. That way, the caches will be warm when the
2600 # are 00-txnreport etc. That way, the caches will be warm when the
2601 # callbacks run.
2601 # callbacks run.
2602 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2602 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2603
2603
2604 def txnaborthook(tr2):
2604 def txnaborthook(tr2):
2605 """To be run if transaction is aborted"""
2605 """To be run if transaction is aborted"""
2606 repo = reporef()
2606 repo = reporef()
2607 assert repo is not None # help pytype
2607 assert repo is not None # help pytype
2608 repo.hook(
2608 repo.hook(
2609 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2609 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2610 )
2610 )
2611
2611
2612 tr.addabort(b'txnabort-hook', txnaborthook)
2612 tr.addabort(b'txnabort-hook', txnaborthook)
2613 # avoid eager cache invalidation. in-memory data should be identical
2613 # avoid eager cache invalidation. in-memory data should be identical
2614 # to stored data if transaction has no error.
2614 # to stored data if transaction has no error.
2615 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2615 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2616 self._transref = weakref.ref(tr)
2616 self._transref = weakref.ref(tr)
2617 scmutil.registersummarycallback(self, tr, desc)
2617 scmutil.registersummarycallback(self, tr, desc)
2618 return tr
2618 return tr
2619
2619
2620 def _journalfiles(self):
2620 def _journalfiles(self):
2621 return (
2621 first = (
2622 (self.svfs, b'journal'),
2622 (self.svfs, b'journal'),
2623 (self.svfs, b'journal.narrowspec'),
2623 (self.svfs, b'journal.narrowspec'),
2624 (self.vfs, b'journal.narrowspec.dirstate'),
2624 (self.vfs, b'journal.narrowspec.dirstate'),
2625 (self.vfs, b'journal.dirstate'),
2625 (self.vfs, b'journal.dirstate'),
2626 )
2627 middle = []
2628 dirstate_data = self.dirstate.data_backup_filename(b'journal.dirstate')
2629 if dirstate_data is not None:
2630 middle.append((self.vfs, dirstate_data))
2631 end = (
2626 (self.vfs, b'journal.branch'),
2632 (self.vfs, b'journal.branch'),
2627 (self.vfs, b'journal.desc'),
2633 (self.vfs, b'journal.desc'),
2628 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2634 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2629 (self.svfs, b'journal.phaseroots'),
2635 (self.svfs, b'journal.phaseroots'),
2630 )
2636 )
2637 return first + tuple(middle) + end
2631
2638
2632 def undofiles(self):
2639 def undofiles(self):
2633 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2640 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2634
2641
2635 @unfilteredmethod
2642 @unfilteredmethod
2636 def _writejournal(self, desc):
2643 def _writejournal(self, desc):
2637 self.dirstate.savebackup(None, b'journal.dirstate')
2644 self.dirstate.savebackup(None, b'journal.dirstate')
2638 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2645 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2639 narrowspec.savebackup(self, b'journal.narrowspec')
2646 narrowspec.savebackup(self, b'journal.narrowspec')
2640 self.vfs.write(
2647 self.vfs.write(
2641 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2648 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2642 )
2649 )
2643 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2650 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2644 bookmarksvfs = bookmarks.bookmarksvfs(self)
2651 bookmarksvfs = bookmarks.bookmarksvfs(self)
2645 bookmarksvfs.write(
2652 bookmarksvfs.write(
2646 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2653 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2647 )
2654 )
2648 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2655 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2649
2656
2650 def recover(self):
2657 def recover(self):
2651 with self.lock():
2658 with self.lock():
2652 if self.svfs.exists(b"journal"):
2659 if self.svfs.exists(b"journal"):
2653 self.ui.status(_(b"rolling back interrupted transaction\n"))
2660 self.ui.status(_(b"rolling back interrupted transaction\n"))
2654 vfsmap = {
2661 vfsmap = {
2655 b'': self.svfs,
2662 b'': self.svfs,
2656 b'plain': self.vfs,
2663 b'plain': self.vfs,
2657 }
2664 }
2658 transaction.rollback(
2665 transaction.rollback(
2659 self.svfs,
2666 self.svfs,
2660 vfsmap,
2667 vfsmap,
2661 b"journal",
2668 b"journal",
2662 self.ui.warn,
2669 self.ui.warn,
2663 checkambigfiles=_cachedfiles,
2670 checkambigfiles=_cachedfiles,
2664 )
2671 )
2665 self.invalidate()
2672 self.invalidate()
2666 return True
2673 return True
2667 else:
2674 else:
2668 self.ui.warn(_(b"no interrupted transaction available\n"))
2675 self.ui.warn(_(b"no interrupted transaction available\n"))
2669 return False
2676 return False
2670
2677
2671 def rollback(self, dryrun=False, force=False):
2678 def rollback(self, dryrun=False, force=False):
2672 wlock = lock = dsguard = None
2679 wlock = lock = dsguard = None
2673 try:
2680 try:
2674 wlock = self.wlock()
2681 wlock = self.wlock()
2675 lock = self.lock()
2682 lock = self.lock()
2676 if self.svfs.exists(b"undo"):
2683 if self.svfs.exists(b"undo"):
2677 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2684 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2678
2685
2679 return self._rollback(dryrun, force, dsguard)
2686 return self._rollback(dryrun, force, dsguard)
2680 else:
2687 else:
2681 self.ui.warn(_(b"no rollback information available\n"))
2688 self.ui.warn(_(b"no rollback information available\n"))
2682 return 1
2689 return 1
2683 finally:
2690 finally:
2684 release(dsguard, lock, wlock)
2691 release(dsguard, lock, wlock)
2685
2692
2686 @unfilteredmethod # Until we get smarter cache management
2693 @unfilteredmethod # Until we get smarter cache management
2687 def _rollback(self, dryrun, force, dsguard):
2694 def _rollback(self, dryrun, force, dsguard):
2688 ui = self.ui
2695 ui = self.ui
2689 try:
2696 try:
2690 args = self.vfs.read(b'undo.desc').splitlines()
2697 args = self.vfs.read(b'undo.desc').splitlines()
2691 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2698 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2692 if len(args) >= 3:
2699 if len(args) >= 3:
2693 detail = args[2]
2700 detail = args[2]
2694 oldtip = oldlen - 1
2701 oldtip = oldlen - 1
2695
2702
2696 if detail and ui.verbose:
2703 if detail and ui.verbose:
2697 msg = _(
2704 msg = _(
2698 b'repository tip rolled back to revision %d'
2705 b'repository tip rolled back to revision %d'
2699 b' (undo %s: %s)\n'
2706 b' (undo %s: %s)\n'
2700 ) % (oldtip, desc, detail)
2707 ) % (oldtip, desc, detail)
2701 else:
2708 else:
2702 msg = _(
2709 msg = _(
2703 b'repository tip rolled back to revision %d (undo %s)\n'
2710 b'repository tip rolled back to revision %d (undo %s)\n'
2704 ) % (oldtip, desc)
2711 ) % (oldtip, desc)
2705 except IOError:
2712 except IOError:
2706 msg = _(b'rolling back unknown transaction\n')
2713 msg = _(b'rolling back unknown transaction\n')
2707 desc = None
2714 desc = None
2708
2715
2709 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2716 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2710 raise error.Abort(
2717 raise error.Abort(
2711 _(
2718 _(
2712 b'rollback of last commit while not checked out '
2719 b'rollback of last commit while not checked out '
2713 b'may lose data'
2720 b'may lose data'
2714 ),
2721 ),
2715 hint=_(b'use -f to force'),
2722 hint=_(b'use -f to force'),
2716 )
2723 )
2717
2724
2718 ui.status(msg)
2725 ui.status(msg)
2719 if dryrun:
2726 if dryrun:
2720 return 0
2727 return 0
2721
2728
2722 parents = self.dirstate.parents()
2729 parents = self.dirstate.parents()
2723 self.destroying()
2730 self.destroying()
2724 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2731 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2725 transaction.rollback(
2732 transaction.rollback(
2726 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2733 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2727 )
2734 )
2728 bookmarksvfs = bookmarks.bookmarksvfs(self)
2735 bookmarksvfs = bookmarks.bookmarksvfs(self)
2729 if bookmarksvfs.exists(b'undo.bookmarks'):
2736 if bookmarksvfs.exists(b'undo.bookmarks'):
2730 bookmarksvfs.rename(
2737 bookmarksvfs.rename(
2731 b'undo.bookmarks', b'bookmarks', checkambig=True
2738 b'undo.bookmarks', b'bookmarks', checkambig=True
2732 )
2739 )
2733 if self.svfs.exists(b'undo.phaseroots'):
2740 if self.svfs.exists(b'undo.phaseroots'):
2734 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2741 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2735 self.invalidate()
2742 self.invalidate()
2736
2743
2737 has_node = self.changelog.index.has_node
2744 has_node = self.changelog.index.has_node
2738 parentgone = any(not has_node(p) for p in parents)
2745 parentgone = any(not has_node(p) for p in parents)
2739 if parentgone:
2746 if parentgone:
2740 # prevent dirstateguard from overwriting already restored one
2747 # prevent dirstateguard from overwriting already restored one
2741 dsguard.close()
2748 dsguard.close()
2742
2749
2743 narrowspec.restorebackup(self, b'undo.narrowspec')
2750 narrowspec.restorebackup(self, b'undo.narrowspec')
2744 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2751 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2745 self.dirstate.restorebackup(None, b'undo.dirstate')
2752 self.dirstate.restorebackup(None, b'undo.dirstate')
2746 try:
2753 try:
2747 branch = self.vfs.read(b'undo.branch')
2754 branch = self.vfs.read(b'undo.branch')
2748 self.dirstate.setbranch(encoding.tolocal(branch))
2755 self.dirstate.setbranch(encoding.tolocal(branch))
2749 except IOError:
2756 except IOError:
2750 ui.warn(
2757 ui.warn(
2751 _(
2758 _(
2752 b'named branch could not be reset: '
2759 b'named branch could not be reset: '
2753 b'current branch is still \'%s\'\n'
2760 b'current branch is still \'%s\'\n'
2754 )
2761 )
2755 % self.dirstate.branch()
2762 % self.dirstate.branch()
2756 )
2763 )
2757
2764
2758 parents = tuple([p.rev() for p in self[None].parents()])
2765 parents = tuple([p.rev() for p in self[None].parents()])
2759 if len(parents) > 1:
2766 if len(parents) > 1:
2760 ui.status(
2767 ui.status(
2761 _(
2768 _(
2762 b'working directory now based on '
2769 b'working directory now based on '
2763 b'revisions %d and %d\n'
2770 b'revisions %d and %d\n'
2764 )
2771 )
2765 % parents
2772 % parents
2766 )
2773 )
2767 else:
2774 else:
2768 ui.status(
2775 ui.status(
2769 _(b'working directory now based on revision %d\n') % parents
2776 _(b'working directory now based on revision %d\n') % parents
2770 )
2777 )
2771 mergestatemod.mergestate.clean(self)
2778 mergestatemod.mergestate.clean(self)
2772
2779
2773 # TODO: if we know which new heads may result from this rollback, pass
2780 # TODO: if we know which new heads may result from this rollback, pass
2774 # them to destroy(), which will prevent the branchhead cache from being
2781 # them to destroy(), which will prevent the branchhead cache from being
2775 # invalidated.
2782 # invalidated.
2776 self.destroyed()
2783 self.destroyed()
2777 return 0
2784 return 0
2778
2785
2779 def _buildcacheupdater(self, newtransaction):
2786 def _buildcacheupdater(self, newtransaction):
2780 """called during transaction to build the callback updating cache
2787 """called during transaction to build the callback updating cache
2781
2788
2782 Lives on the repository to help extension who might want to augment
2789 Lives on the repository to help extension who might want to augment
2783 this logic. For this purpose, the created transaction is passed to the
2790 this logic. For this purpose, the created transaction is passed to the
2784 method.
2791 method.
2785 """
2792 """
2786 # we must avoid cyclic reference between repo and transaction.
2793 # we must avoid cyclic reference between repo and transaction.
2787 reporef = weakref.ref(self)
2794 reporef = weakref.ref(self)
2788
2795
2789 def updater(tr):
2796 def updater(tr):
2790 repo = reporef()
2797 repo = reporef()
2791 assert repo is not None # help pytype
2798 assert repo is not None # help pytype
2792 repo.updatecaches(tr)
2799 repo.updatecaches(tr)
2793
2800
2794 return updater
2801 return updater
2795
2802
2796 @unfilteredmethod
2803 @unfilteredmethod
2797 def updatecaches(self, tr=None, full=False, caches=None):
2804 def updatecaches(self, tr=None, full=False, caches=None):
2798 """warm appropriate caches
2805 """warm appropriate caches
2799
2806
2800 If this function is called after a transaction closed. The transaction
2807 If this function is called after a transaction closed. The transaction
2801 will be available in the 'tr' argument. This can be used to selectively
2808 will be available in the 'tr' argument. This can be used to selectively
2802 update caches relevant to the changes in that transaction.
2809 update caches relevant to the changes in that transaction.
2803
2810
2804 If 'full' is set, make sure all caches the function knows about have
2811 If 'full' is set, make sure all caches the function knows about have
2805 up-to-date data. Even the ones usually loaded more lazily.
2812 up-to-date data. Even the ones usually loaded more lazily.
2806
2813
2807 The `full` argument can take a special "post-clone" value. In this case
2814 The `full` argument can take a special "post-clone" value. In this case
2808 the cache warming is made after a clone and of the slower cache might
2815 the cache warming is made after a clone and of the slower cache might
2809 be skipped, namely the `.fnodetags` one. This argument is 5.8 specific
2816 be skipped, namely the `.fnodetags` one. This argument is 5.8 specific
2810 as we plan for a cleaner way to deal with this for 5.9.
2817 as we plan for a cleaner way to deal with this for 5.9.
2811 """
2818 """
2812 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2819 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2813 # During strip, many caches are invalid but
2820 # During strip, many caches are invalid but
2814 # later call to `destroyed` will refresh them.
2821 # later call to `destroyed` will refresh them.
2815 return
2822 return
2816
2823
2817 unfi = self.unfiltered()
2824 unfi = self.unfiltered()
2818
2825
2819 if full:
2826 if full:
2820 msg = (
2827 msg = (
2821 "`full` argument for `repo.updatecaches` is deprecated\n"
2828 "`full` argument for `repo.updatecaches` is deprecated\n"
2822 "(use `caches=repository.CACHE_ALL` instead)"
2829 "(use `caches=repository.CACHE_ALL` instead)"
2823 )
2830 )
2824 self.ui.deprecwarn(msg, b"5.9")
2831 self.ui.deprecwarn(msg, b"5.9")
2825 caches = repository.CACHES_ALL
2832 caches = repository.CACHES_ALL
2826 if full == b"post-clone":
2833 if full == b"post-clone":
2827 caches = repository.CACHES_POST_CLONE
2834 caches = repository.CACHES_POST_CLONE
2828 caches = repository.CACHES_ALL
2835 caches = repository.CACHES_ALL
2829 elif caches is None:
2836 elif caches is None:
2830 caches = repository.CACHES_DEFAULT
2837 caches = repository.CACHES_DEFAULT
2831
2838
2832 if repository.CACHE_BRANCHMAP_SERVED in caches:
2839 if repository.CACHE_BRANCHMAP_SERVED in caches:
2833 if tr is None or tr.changes[b'origrepolen'] < len(self):
2840 if tr is None or tr.changes[b'origrepolen'] < len(self):
2834 # accessing the 'served' branchmap should refresh all the others,
2841 # accessing the 'served' branchmap should refresh all the others,
2835 self.ui.debug(b'updating the branch cache\n')
2842 self.ui.debug(b'updating the branch cache\n')
2836 self.filtered(b'served').branchmap()
2843 self.filtered(b'served').branchmap()
2837 self.filtered(b'served.hidden').branchmap()
2844 self.filtered(b'served.hidden').branchmap()
2838 # flush all possibly delayed write.
2845 # flush all possibly delayed write.
2839 self._branchcaches.write_delayed(self)
2846 self._branchcaches.write_delayed(self)
2840
2847
2841 if repository.CACHE_CHANGELOG_CACHE in caches:
2848 if repository.CACHE_CHANGELOG_CACHE in caches:
2842 self.changelog.update_caches(transaction=tr)
2849 self.changelog.update_caches(transaction=tr)
2843
2850
2844 if repository.CACHE_MANIFESTLOG_CACHE in caches:
2851 if repository.CACHE_MANIFESTLOG_CACHE in caches:
2845 self.manifestlog.update_caches(transaction=tr)
2852 self.manifestlog.update_caches(transaction=tr)
2846
2853
2847 if repository.CACHE_REV_BRANCH in caches:
2854 if repository.CACHE_REV_BRANCH in caches:
2848 rbc = unfi.revbranchcache()
2855 rbc = unfi.revbranchcache()
2849 for r in unfi.changelog:
2856 for r in unfi.changelog:
2850 rbc.branchinfo(r)
2857 rbc.branchinfo(r)
2851 rbc.write()
2858 rbc.write()
2852
2859
2853 if repository.CACHE_FULL_MANIFEST in caches:
2860 if repository.CACHE_FULL_MANIFEST in caches:
2854 # ensure the working copy parents are in the manifestfulltextcache
2861 # ensure the working copy parents are in the manifestfulltextcache
2855 for ctx in self[b'.'].parents():
2862 for ctx in self[b'.'].parents():
2856 ctx.manifest() # accessing the manifest is enough
2863 ctx.manifest() # accessing the manifest is enough
2857
2864
2858 if repository.CACHE_FILE_NODE_TAGS in caches:
2865 if repository.CACHE_FILE_NODE_TAGS in caches:
2859 # accessing fnode cache warms the cache
2866 # accessing fnode cache warms the cache
2860 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2867 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2861
2868
2862 if repository.CACHE_TAGS_DEFAULT in caches:
2869 if repository.CACHE_TAGS_DEFAULT in caches:
2863 # accessing tags warm the cache
2870 # accessing tags warm the cache
2864 self.tags()
2871 self.tags()
2865 if repository.CACHE_TAGS_SERVED in caches:
2872 if repository.CACHE_TAGS_SERVED in caches:
2866 self.filtered(b'served').tags()
2873 self.filtered(b'served').tags()
2867
2874
2868 if repository.CACHE_BRANCHMAP_ALL in caches:
2875 if repository.CACHE_BRANCHMAP_ALL in caches:
2869 # The CACHE_BRANCHMAP_ALL updates lazily-loaded caches immediately,
2876 # The CACHE_BRANCHMAP_ALL updates lazily-loaded caches immediately,
2870 # so we're forcing a write to cause these caches to be warmed up
2877 # so we're forcing a write to cause these caches to be warmed up
2871 # even if they haven't explicitly been requested yet (if they've
2878 # even if they haven't explicitly been requested yet (if they've
2872 # never been used by hg, they won't ever have been written, even if
2879 # never been used by hg, they won't ever have been written, even if
2873 # they're a subset of another kind of cache that *has* been used).
2880 # they're a subset of another kind of cache that *has* been used).
2874 for filt in repoview.filtertable.keys():
2881 for filt in repoview.filtertable.keys():
2875 filtered = self.filtered(filt)
2882 filtered = self.filtered(filt)
2876 filtered.branchmap().write(filtered)
2883 filtered.branchmap().write(filtered)
2877
2884
2878 def invalidatecaches(self):
2885 def invalidatecaches(self):
2879
2886
2880 if '_tagscache' in vars(self):
2887 if '_tagscache' in vars(self):
2881 # can't use delattr on proxy
2888 # can't use delattr on proxy
2882 del self.__dict__['_tagscache']
2889 del self.__dict__['_tagscache']
2883
2890
2884 self._branchcaches.clear()
2891 self._branchcaches.clear()
2885 self.invalidatevolatilesets()
2892 self.invalidatevolatilesets()
2886 self._sparsesignaturecache.clear()
2893 self._sparsesignaturecache.clear()
2887
2894
2888 def invalidatevolatilesets(self):
2895 def invalidatevolatilesets(self):
2889 self.filteredrevcache.clear()
2896 self.filteredrevcache.clear()
2890 obsolete.clearobscaches(self)
2897 obsolete.clearobscaches(self)
2891 self._quick_access_changeid_invalidate()
2898 self._quick_access_changeid_invalidate()
2892
2899
2893 def invalidatedirstate(self):
2900 def invalidatedirstate(self):
2894 """Invalidates the dirstate, causing the next call to dirstate
2901 """Invalidates the dirstate, causing the next call to dirstate
2895 to check if it was modified since the last time it was read,
2902 to check if it was modified since the last time it was read,
2896 rereading it if it has.
2903 rereading it if it has.
2897
2904
2898 This is different to dirstate.invalidate() that it doesn't always
2905 This is different to dirstate.invalidate() that it doesn't always
2899 rereads the dirstate. Use dirstate.invalidate() if you want to
2906 rereads the dirstate. Use dirstate.invalidate() if you want to
2900 explicitly read the dirstate again (i.e. restoring it to a previous
2907 explicitly read the dirstate again (i.e. restoring it to a previous
2901 known good state)."""
2908 known good state)."""
2902 if hasunfilteredcache(self, 'dirstate'):
2909 if hasunfilteredcache(self, 'dirstate'):
2903 for k in self.dirstate._filecache:
2910 for k in self.dirstate._filecache:
2904 try:
2911 try:
2905 delattr(self.dirstate, k)
2912 delattr(self.dirstate, k)
2906 except AttributeError:
2913 except AttributeError:
2907 pass
2914 pass
2908 delattr(self.unfiltered(), 'dirstate')
2915 delattr(self.unfiltered(), 'dirstate')
2909
2916
2910 def invalidate(self, clearfilecache=False):
2917 def invalidate(self, clearfilecache=False):
2911 """Invalidates both store and non-store parts other than dirstate
2918 """Invalidates both store and non-store parts other than dirstate
2912
2919
2913 If a transaction is running, invalidation of store is omitted,
2920 If a transaction is running, invalidation of store is omitted,
2914 because discarding in-memory changes might cause inconsistency
2921 because discarding in-memory changes might cause inconsistency
2915 (e.g. incomplete fncache causes unintentional failure, but
2922 (e.g. incomplete fncache causes unintentional failure, but
2916 redundant one doesn't).
2923 redundant one doesn't).
2917 """
2924 """
2918 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2925 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2919 for k in list(self._filecache.keys()):
2926 for k in list(self._filecache.keys()):
2920 # dirstate is invalidated separately in invalidatedirstate()
2927 # dirstate is invalidated separately in invalidatedirstate()
2921 if k == b'dirstate':
2928 if k == b'dirstate':
2922 continue
2929 continue
2923 if (
2930 if (
2924 k == b'changelog'
2931 k == b'changelog'
2925 and self.currenttransaction()
2932 and self.currenttransaction()
2926 and self.changelog._delayed
2933 and self.changelog._delayed
2927 ):
2934 ):
2928 # The changelog object may store unwritten revisions. We don't
2935 # The changelog object may store unwritten revisions. We don't
2929 # want to lose them.
2936 # want to lose them.
2930 # TODO: Solve the problem instead of working around it.
2937 # TODO: Solve the problem instead of working around it.
2931 continue
2938 continue
2932
2939
2933 if clearfilecache:
2940 if clearfilecache:
2934 del self._filecache[k]
2941 del self._filecache[k]
2935 try:
2942 try:
2936 delattr(unfiltered, k)
2943 delattr(unfiltered, k)
2937 except AttributeError:
2944 except AttributeError:
2938 pass
2945 pass
2939 self.invalidatecaches()
2946 self.invalidatecaches()
2940 if not self.currenttransaction():
2947 if not self.currenttransaction():
2941 # TODO: Changing contents of store outside transaction
2948 # TODO: Changing contents of store outside transaction
2942 # causes inconsistency. We should make in-memory store
2949 # causes inconsistency. We should make in-memory store
2943 # changes detectable, and abort if changed.
2950 # changes detectable, and abort if changed.
2944 self.store.invalidatecaches()
2951 self.store.invalidatecaches()
2945
2952
2946 def invalidateall(self):
2953 def invalidateall(self):
2947 """Fully invalidates both store and non-store parts, causing the
2954 """Fully invalidates both store and non-store parts, causing the
2948 subsequent operation to reread any outside changes."""
2955 subsequent operation to reread any outside changes."""
2949 # extension should hook this to invalidate its caches
2956 # extension should hook this to invalidate its caches
2950 self.invalidate()
2957 self.invalidate()
2951 self.invalidatedirstate()
2958 self.invalidatedirstate()
2952
2959
2953 @unfilteredmethod
2960 @unfilteredmethod
2954 def _refreshfilecachestats(self, tr):
2961 def _refreshfilecachestats(self, tr):
2955 """Reload stats of cached files so that they are flagged as valid"""
2962 """Reload stats of cached files so that they are flagged as valid"""
2956 for k, ce in self._filecache.items():
2963 for k, ce in self._filecache.items():
2957 k = pycompat.sysstr(k)
2964 k = pycompat.sysstr(k)
2958 if k == 'dirstate' or k not in self.__dict__:
2965 if k == 'dirstate' or k not in self.__dict__:
2959 continue
2966 continue
2960 ce.refresh()
2967 ce.refresh()
2961
2968
2962 def _lock(
2969 def _lock(
2963 self,
2970 self,
2964 vfs,
2971 vfs,
2965 lockname,
2972 lockname,
2966 wait,
2973 wait,
2967 releasefn,
2974 releasefn,
2968 acquirefn,
2975 acquirefn,
2969 desc,
2976 desc,
2970 ):
2977 ):
2971 timeout = 0
2978 timeout = 0
2972 warntimeout = 0
2979 warntimeout = 0
2973 if wait:
2980 if wait:
2974 timeout = self.ui.configint(b"ui", b"timeout")
2981 timeout = self.ui.configint(b"ui", b"timeout")
2975 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2982 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2976 # internal config: ui.signal-safe-lock
2983 # internal config: ui.signal-safe-lock
2977 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2984 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2978
2985
2979 l = lockmod.trylock(
2986 l = lockmod.trylock(
2980 self.ui,
2987 self.ui,
2981 vfs,
2988 vfs,
2982 lockname,
2989 lockname,
2983 timeout,
2990 timeout,
2984 warntimeout,
2991 warntimeout,
2985 releasefn=releasefn,
2992 releasefn=releasefn,
2986 acquirefn=acquirefn,
2993 acquirefn=acquirefn,
2987 desc=desc,
2994 desc=desc,
2988 signalsafe=signalsafe,
2995 signalsafe=signalsafe,
2989 )
2996 )
2990 return l
2997 return l
2991
2998
2992 def _afterlock(self, callback):
2999 def _afterlock(self, callback):
2993 """add a callback to be run when the repository is fully unlocked
3000 """add a callback to be run when the repository is fully unlocked
2994
3001
2995 The callback will be executed when the outermost lock is released
3002 The callback will be executed when the outermost lock is released
2996 (with wlock being higher level than 'lock')."""
3003 (with wlock being higher level than 'lock')."""
2997 for ref in (self._wlockref, self._lockref):
3004 for ref in (self._wlockref, self._lockref):
2998 l = ref and ref()
3005 l = ref and ref()
2999 if l and l.held:
3006 if l and l.held:
3000 l.postrelease.append(callback)
3007 l.postrelease.append(callback)
3001 break
3008 break
3002 else: # no lock have been found.
3009 else: # no lock have been found.
3003 callback(True)
3010 callback(True)
3004
3011
3005 def lock(self, wait=True):
3012 def lock(self, wait=True):
3006 """Lock the repository store (.hg/store) and return a weak reference
3013 """Lock the repository store (.hg/store) and return a weak reference
3007 to the lock. Use this before modifying the store (e.g. committing or
3014 to the lock. Use this before modifying the store (e.g. committing or
3008 stripping). If you are opening a transaction, get a lock as well.)
3015 stripping). If you are opening a transaction, get a lock as well.)
3009
3016
3010 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
3017 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
3011 'wlock' first to avoid a dead-lock hazard."""
3018 'wlock' first to avoid a dead-lock hazard."""
3012 l = self._currentlock(self._lockref)
3019 l = self._currentlock(self._lockref)
3013 if l is not None:
3020 if l is not None:
3014 l.lock()
3021 l.lock()
3015 return l
3022 return l
3016
3023
3017 l = self._lock(
3024 l = self._lock(
3018 vfs=self.svfs,
3025 vfs=self.svfs,
3019 lockname=b"lock",
3026 lockname=b"lock",
3020 wait=wait,
3027 wait=wait,
3021 releasefn=None,
3028 releasefn=None,
3022 acquirefn=self.invalidate,
3029 acquirefn=self.invalidate,
3023 desc=_(b'repository %s') % self.origroot,
3030 desc=_(b'repository %s') % self.origroot,
3024 )
3031 )
3025 self._lockref = weakref.ref(l)
3032 self._lockref = weakref.ref(l)
3026 return l
3033 return l
3027
3034
3028 def wlock(self, wait=True):
3035 def wlock(self, wait=True):
3029 """Lock the non-store parts of the repository (everything under
3036 """Lock the non-store parts of the repository (everything under
3030 .hg except .hg/store) and return a weak reference to the lock.
3037 .hg except .hg/store) and return a weak reference to the lock.
3031
3038
3032 Use this before modifying files in .hg.
3039 Use this before modifying files in .hg.
3033
3040
3034 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
3041 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
3035 'wlock' first to avoid a dead-lock hazard."""
3042 'wlock' first to avoid a dead-lock hazard."""
3036 l = self._wlockref() if self._wlockref else None
3043 l = self._wlockref() if self._wlockref else None
3037 if l is not None and l.held:
3044 if l is not None and l.held:
3038 l.lock()
3045 l.lock()
3039 return l
3046 return l
3040
3047
3041 # We do not need to check for non-waiting lock acquisition. Such
3048 # We do not need to check for non-waiting lock acquisition. Such
3042 # acquisition would not cause dead-lock as they would just fail.
3049 # acquisition would not cause dead-lock as they would just fail.
3043 if wait and (
3050 if wait and (
3044 self.ui.configbool(b'devel', b'all-warnings')
3051 self.ui.configbool(b'devel', b'all-warnings')
3045 or self.ui.configbool(b'devel', b'check-locks')
3052 or self.ui.configbool(b'devel', b'check-locks')
3046 ):
3053 ):
3047 if self._currentlock(self._lockref) is not None:
3054 if self._currentlock(self._lockref) is not None:
3048 self.ui.develwarn(b'"wlock" acquired after "lock"')
3055 self.ui.develwarn(b'"wlock" acquired after "lock"')
3049
3056
3050 def unlock():
3057 def unlock():
3051 if self.dirstate.pendingparentchange():
3058 if self.dirstate.pendingparentchange():
3052 self.dirstate.invalidate()
3059 self.dirstate.invalidate()
3053 else:
3060 else:
3054 self.dirstate.write(None)
3061 self.dirstate.write(None)
3055
3062
3056 self._filecache[b'dirstate'].refresh()
3063 self._filecache[b'dirstate'].refresh()
3057
3064
3058 l = self._lock(
3065 l = self._lock(
3059 self.vfs,
3066 self.vfs,
3060 b"wlock",
3067 b"wlock",
3061 wait,
3068 wait,
3062 unlock,
3069 unlock,
3063 self.invalidatedirstate,
3070 self.invalidatedirstate,
3064 _(b'working directory of %s') % self.origroot,
3071 _(b'working directory of %s') % self.origroot,
3065 )
3072 )
3066 self._wlockref = weakref.ref(l)
3073 self._wlockref = weakref.ref(l)
3067 return l
3074 return l
3068
3075
3069 def _currentlock(self, lockref):
3076 def _currentlock(self, lockref):
3070 """Returns the lock if it's held, or None if it's not."""
3077 """Returns the lock if it's held, or None if it's not."""
3071 if lockref is None:
3078 if lockref is None:
3072 return None
3079 return None
3073 l = lockref()
3080 l = lockref()
3074 if l is None or not l.held:
3081 if l is None or not l.held:
3075 return None
3082 return None
3076 return l
3083 return l
3077
3084
3078 def currentwlock(self):
3085 def currentwlock(self):
3079 """Returns the wlock if it's held, or None if it's not."""
3086 """Returns the wlock if it's held, or None if it's not."""
3080 return self._currentlock(self._wlockref)
3087 return self._currentlock(self._wlockref)
3081
3088
3082 def checkcommitpatterns(self, wctx, match, status, fail):
3089 def checkcommitpatterns(self, wctx, match, status, fail):
3083 """check for commit arguments that aren't committable"""
3090 """check for commit arguments that aren't committable"""
3084 if match.isexact() or match.prefix():
3091 if match.isexact() or match.prefix():
3085 matched = set(status.modified + status.added + status.removed)
3092 matched = set(status.modified + status.added + status.removed)
3086
3093
3087 for f in match.files():
3094 for f in match.files():
3088 f = self.dirstate.normalize(f)
3095 f = self.dirstate.normalize(f)
3089 if f == b'.' or f in matched or f in wctx.substate:
3096 if f == b'.' or f in matched or f in wctx.substate:
3090 continue
3097 continue
3091 if f in status.deleted:
3098 if f in status.deleted:
3092 fail(f, _(b'file not found!'))
3099 fail(f, _(b'file not found!'))
3093 # Is it a directory that exists or used to exist?
3100 # Is it a directory that exists or used to exist?
3094 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
3101 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
3095 d = f + b'/'
3102 d = f + b'/'
3096 for mf in matched:
3103 for mf in matched:
3097 if mf.startswith(d):
3104 if mf.startswith(d):
3098 break
3105 break
3099 else:
3106 else:
3100 fail(f, _(b"no match under directory!"))
3107 fail(f, _(b"no match under directory!"))
3101 elif f not in self.dirstate:
3108 elif f not in self.dirstate:
3102 fail(f, _(b"file not tracked!"))
3109 fail(f, _(b"file not tracked!"))
3103
3110
3104 @unfilteredmethod
3111 @unfilteredmethod
3105 def commit(
3112 def commit(
3106 self,
3113 self,
3107 text=b"",
3114 text=b"",
3108 user=None,
3115 user=None,
3109 date=None,
3116 date=None,
3110 match=None,
3117 match=None,
3111 force=False,
3118 force=False,
3112 editor=None,
3119 editor=None,
3113 extra=None,
3120 extra=None,
3114 ):
3121 ):
3115 """Add a new revision to current repository.
3122 """Add a new revision to current repository.
3116
3123
3117 Revision information is gathered from the working directory,
3124 Revision information is gathered from the working directory,
3118 match can be used to filter the committed files. If editor is
3125 match can be used to filter the committed files. If editor is
3119 supplied, it is called to get a commit message.
3126 supplied, it is called to get a commit message.
3120 """
3127 """
3121 if extra is None:
3128 if extra is None:
3122 extra = {}
3129 extra = {}
3123
3130
3124 def fail(f, msg):
3131 def fail(f, msg):
3125 raise error.InputError(b'%s: %s' % (f, msg))
3132 raise error.InputError(b'%s: %s' % (f, msg))
3126
3133
3127 if not match:
3134 if not match:
3128 match = matchmod.always()
3135 match = matchmod.always()
3129
3136
3130 if not force:
3137 if not force:
3131 match.bad = fail
3138 match.bad = fail
3132
3139
3133 # lock() for recent changelog (see issue4368)
3140 # lock() for recent changelog (see issue4368)
3134 with self.wlock(), self.lock():
3141 with self.wlock(), self.lock():
3135 wctx = self[None]
3142 wctx = self[None]
3136 merge = len(wctx.parents()) > 1
3143 merge = len(wctx.parents()) > 1
3137
3144
3138 if not force and merge and not match.always():
3145 if not force and merge and not match.always():
3139 raise error.Abort(
3146 raise error.Abort(
3140 _(
3147 _(
3141 b'cannot partially commit a merge '
3148 b'cannot partially commit a merge '
3142 b'(do not specify files or patterns)'
3149 b'(do not specify files or patterns)'
3143 )
3150 )
3144 )
3151 )
3145
3152
3146 status = self.status(match=match, clean=force)
3153 status = self.status(match=match, clean=force)
3147 if force:
3154 if force:
3148 status.modified.extend(
3155 status.modified.extend(
3149 status.clean
3156 status.clean
3150 ) # mq may commit clean files
3157 ) # mq may commit clean files
3151
3158
3152 # check subrepos
3159 # check subrepos
3153 subs, commitsubs, newstate = subrepoutil.precommit(
3160 subs, commitsubs, newstate = subrepoutil.precommit(
3154 self.ui, wctx, status, match, force=force
3161 self.ui, wctx, status, match, force=force
3155 )
3162 )
3156
3163
3157 # make sure all explicit patterns are matched
3164 # make sure all explicit patterns are matched
3158 if not force:
3165 if not force:
3159 self.checkcommitpatterns(wctx, match, status, fail)
3166 self.checkcommitpatterns(wctx, match, status, fail)
3160
3167
3161 cctx = context.workingcommitctx(
3168 cctx = context.workingcommitctx(
3162 self, status, text, user, date, extra
3169 self, status, text, user, date, extra
3163 )
3170 )
3164
3171
3165 ms = mergestatemod.mergestate.read(self)
3172 ms = mergestatemod.mergestate.read(self)
3166 mergeutil.checkunresolved(ms)
3173 mergeutil.checkunresolved(ms)
3167
3174
3168 # internal config: ui.allowemptycommit
3175 # internal config: ui.allowemptycommit
3169 if cctx.isempty() and not self.ui.configbool(
3176 if cctx.isempty() and not self.ui.configbool(
3170 b'ui', b'allowemptycommit'
3177 b'ui', b'allowemptycommit'
3171 ):
3178 ):
3172 self.ui.debug(b'nothing to commit, clearing merge state\n')
3179 self.ui.debug(b'nothing to commit, clearing merge state\n')
3173 ms.reset()
3180 ms.reset()
3174 return None
3181 return None
3175
3182
3176 if merge and cctx.deleted():
3183 if merge and cctx.deleted():
3177 raise error.Abort(_(b"cannot commit merge with missing files"))
3184 raise error.Abort(_(b"cannot commit merge with missing files"))
3178
3185
3179 if editor:
3186 if editor:
3180 cctx._text = editor(self, cctx, subs)
3187 cctx._text = editor(self, cctx, subs)
3181 edited = text != cctx._text
3188 edited = text != cctx._text
3182
3189
3183 # Save commit message in case this transaction gets rolled back
3190 # Save commit message in case this transaction gets rolled back
3184 # (e.g. by a pretxncommit hook). Leave the content alone on
3191 # (e.g. by a pretxncommit hook). Leave the content alone on
3185 # the assumption that the user will use the same editor again.
3192 # the assumption that the user will use the same editor again.
3186 msg_path = self.savecommitmessage(cctx._text)
3193 msg_path = self.savecommitmessage(cctx._text)
3187
3194
3188 # commit subs and write new state
3195 # commit subs and write new state
3189 if subs:
3196 if subs:
3190 uipathfn = scmutil.getuipathfn(self)
3197 uipathfn = scmutil.getuipathfn(self)
3191 for s in sorted(commitsubs):
3198 for s in sorted(commitsubs):
3192 sub = wctx.sub(s)
3199 sub = wctx.sub(s)
3193 self.ui.status(
3200 self.ui.status(
3194 _(b'committing subrepository %s\n')
3201 _(b'committing subrepository %s\n')
3195 % uipathfn(subrepoutil.subrelpath(sub))
3202 % uipathfn(subrepoutil.subrelpath(sub))
3196 )
3203 )
3197 sr = sub.commit(cctx._text, user, date)
3204 sr = sub.commit(cctx._text, user, date)
3198 newstate[s] = (newstate[s][0], sr)
3205 newstate[s] = (newstate[s][0], sr)
3199 subrepoutil.writestate(self, newstate)
3206 subrepoutil.writestate(self, newstate)
3200
3207
3201 p1, p2 = self.dirstate.parents()
3208 p1, p2 = self.dirstate.parents()
3202 hookp1, hookp2 = hex(p1), (p2 != self.nullid and hex(p2) or b'')
3209 hookp1, hookp2 = hex(p1), (p2 != self.nullid and hex(p2) or b'')
3203 try:
3210 try:
3204 self.hook(
3211 self.hook(
3205 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
3212 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
3206 )
3213 )
3207 with self.transaction(b'commit'):
3214 with self.transaction(b'commit'):
3208 ret = self.commitctx(cctx, True)
3215 ret = self.commitctx(cctx, True)
3209 # update bookmarks, dirstate and mergestate
3216 # update bookmarks, dirstate and mergestate
3210 bookmarks.update(self, [p1, p2], ret)
3217 bookmarks.update(self, [p1, p2], ret)
3211 cctx.markcommitted(ret)
3218 cctx.markcommitted(ret)
3212 ms.reset()
3219 ms.reset()
3213 except: # re-raises
3220 except: # re-raises
3214 if edited:
3221 if edited:
3215 self.ui.write(
3222 self.ui.write(
3216 _(b'note: commit message saved in %s\n') % msg_path
3223 _(b'note: commit message saved in %s\n') % msg_path
3217 )
3224 )
3218 self.ui.write(
3225 self.ui.write(
3219 _(
3226 _(
3220 b"note: use 'hg commit --logfile "
3227 b"note: use 'hg commit --logfile "
3221 b"%s --edit' to reuse it\n"
3228 b"%s --edit' to reuse it\n"
3222 )
3229 )
3223 % msg_path
3230 % msg_path
3224 )
3231 )
3225 raise
3232 raise
3226
3233
3227 def commithook(unused_success):
3234 def commithook(unused_success):
3228 # hack for command that use a temporary commit (eg: histedit)
3235 # hack for command that use a temporary commit (eg: histedit)
3229 # temporary commit got stripped before hook release
3236 # temporary commit got stripped before hook release
3230 if self.changelog.hasnode(ret):
3237 if self.changelog.hasnode(ret):
3231 self.hook(
3238 self.hook(
3232 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
3239 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
3233 )
3240 )
3234
3241
3235 self._afterlock(commithook)
3242 self._afterlock(commithook)
3236 return ret
3243 return ret
3237
3244
3238 @unfilteredmethod
3245 @unfilteredmethod
3239 def commitctx(self, ctx, error=False, origctx=None):
3246 def commitctx(self, ctx, error=False, origctx=None):
3240 return commit.commitctx(self, ctx, error=error, origctx=origctx)
3247 return commit.commitctx(self, ctx, error=error, origctx=origctx)
3241
3248
3242 @unfilteredmethod
3249 @unfilteredmethod
3243 def destroying(self):
3250 def destroying(self):
3244 """Inform the repository that nodes are about to be destroyed.
3251 """Inform the repository that nodes are about to be destroyed.
3245 Intended for use by strip and rollback, so there's a common
3252 Intended for use by strip and rollback, so there's a common
3246 place for anything that has to be done before destroying history.
3253 place for anything that has to be done before destroying history.
3247
3254
3248 This is mostly useful for saving state that is in memory and waiting
3255 This is mostly useful for saving state that is in memory and waiting
3249 to be flushed when the current lock is released. Because a call to
3256 to be flushed when the current lock is released. Because a call to
3250 destroyed is imminent, the repo will be invalidated causing those
3257 destroyed is imminent, the repo will be invalidated causing those
3251 changes to stay in memory (waiting for the next unlock), or vanish
3258 changes to stay in memory (waiting for the next unlock), or vanish
3252 completely.
3259 completely.
3253 """
3260 """
3254 # When using the same lock to commit and strip, the phasecache is left
3261 # When using the same lock to commit and strip, the phasecache is left
3255 # dirty after committing. Then when we strip, the repo is invalidated,
3262 # dirty after committing. Then when we strip, the repo is invalidated,
3256 # causing those changes to disappear.
3263 # causing those changes to disappear.
3257 if '_phasecache' in vars(self):
3264 if '_phasecache' in vars(self):
3258 self._phasecache.write()
3265 self._phasecache.write()
3259
3266
3260 @unfilteredmethod
3267 @unfilteredmethod
3261 def destroyed(self):
3268 def destroyed(self):
3262 """Inform the repository that nodes have been destroyed.
3269 """Inform the repository that nodes have been destroyed.
3263 Intended for use by strip and rollback, so there's a common
3270 Intended for use by strip and rollback, so there's a common
3264 place for anything that has to be done after destroying history.
3271 place for anything that has to be done after destroying history.
3265 """
3272 """
3266 # When one tries to:
3273 # When one tries to:
3267 # 1) destroy nodes thus calling this method (e.g. strip)
3274 # 1) destroy nodes thus calling this method (e.g. strip)
3268 # 2) use phasecache somewhere (e.g. commit)
3275 # 2) use phasecache somewhere (e.g. commit)
3269 #
3276 #
3270 # then 2) will fail because the phasecache contains nodes that were
3277 # then 2) will fail because the phasecache contains nodes that were
3271 # removed. We can either remove phasecache from the filecache,
3278 # removed. We can either remove phasecache from the filecache,
3272 # causing it to reload next time it is accessed, or simply filter
3279 # causing it to reload next time it is accessed, or simply filter
3273 # the removed nodes now and write the updated cache.
3280 # the removed nodes now and write the updated cache.
3274 self._phasecache.filterunknown(self)
3281 self._phasecache.filterunknown(self)
3275 self._phasecache.write()
3282 self._phasecache.write()
3276
3283
3277 # refresh all repository caches
3284 # refresh all repository caches
3278 self.updatecaches()
3285 self.updatecaches()
3279
3286
3280 # Ensure the persistent tag cache is updated. Doing it now
3287 # Ensure the persistent tag cache is updated. Doing it now
3281 # means that the tag cache only has to worry about destroyed
3288 # means that the tag cache only has to worry about destroyed
3282 # heads immediately after a strip/rollback. That in turn
3289 # heads immediately after a strip/rollback. That in turn
3283 # guarantees that "cachetip == currenttip" (comparing both rev
3290 # guarantees that "cachetip == currenttip" (comparing both rev
3284 # and node) always means no nodes have been added or destroyed.
3291 # and node) always means no nodes have been added or destroyed.
3285
3292
3286 # XXX this is suboptimal when qrefresh'ing: we strip the current
3293 # XXX this is suboptimal when qrefresh'ing: we strip the current
3287 # head, refresh the tag cache, then immediately add a new head.
3294 # head, refresh the tag cache, then immediately add a new head.
3288 # But I think doing it this way is necessary for the "instant
3295 # But I think doing it this way is necessary for the "instant
3289 # tag cache retrieval" case to work.
3296 # tag cache retrieval" case to work.
3290 self.invalidate()
3297 self.invalidate()
3291
3298
3292 def status(
3299 def status(
3293 self,
3300 self,
3294 node1=b'.',
3301 node1=b'.',
3295 node2=None,
3302 node2=None,
3296 match=None,
3303 match=None,
3297 ignored=False,
3304 ignored=False,
3298 clean=False,
3305 clean=False,
3299 unknown=False,
3306 unknown=False,
3300 listsubrepos=False,
3307 listsubrepos=False,
3301 ):
3308 ):
3302 '''a convenience method that calls node1.status(node2)'''
3309 '''a convenience method that calls node1.status(node2)'''
3303 return self[node1].status(
3310 return self[node1].status(
3304 node2, match, ignored, clean, unknown, listsubrepos
3311 node2, match, ignored, clean, unknown, listsubrepos
3305 )
3312 )
3306
3313
3307 def addpostdsstatus(self, ps):
3314 def addpostdsstatus(self, ps):
3308 """Add a callback to run within the wlock, at the point at which status
3315 """Add a callback to run within the wlock, at the point at which status
3309 fixups happen.
3316 fixups happen.
3310
3317
3311 On status completion, callback(wctx, status) will be called with the
3318 On status completion, callback(wctx, status) will be called with the
3312 wlock held, unless the dirstate has changed from underneath or the wlock
3319 wlock held, unless the dirstate has changed from underneath or the wlock
3313 couldn't be grabbed.
3320 couldn't be grabbed.
3314
3321
3315 Callbacks should not capture and use a cached copy of the dirstate --
3322 Callbacks should not capture and use a cached copy of the dirstate --
3316 it might change in the meanwhile. Instead, they should access the
3323 it might change in the meanwhile. Instead, they should access the
3317 dirstate via wctx.repo().dirstate.
3324 dirstate via wctx.repo().dirstate.
3318
3325
3319 This list is emptied out after each status run -- extensions should
3326 This list is emptied out after each status run -- extensions should
3320 make sure it adds to this list each time dirstate.status is called.
3327 make sure it adds to this list each time dirstate.status is called.
3321 Extensions should also make sure they don't call this for statuses
3328 Extensions should also make sure they don't call this for statuses
3322 that don't involve the dirstate.
3329 that don't involve the dirstate.
3323 """
3330 """
3324
3331
3325 # The list is located here for uniqueness reasons -- it is actually
3332 # The list is located here for uniqueness reasons -- it is actually
3326 # managed by the workingctx, but that isn't unique per-repo.
3333 # managed by the workingctx, but that isn't unique per-repo.
3327 self._postdsstatus.append(ps)
3334 self._postdsstatus.append(ps)
3328
3335
3329 def postdsstatus(self):
3336 def postdsstatus(self):
3330 """Used by workingctx to get the list of post-dirstate-status hooks."""
3337 """Used by workingctx to get the list of post-dirstate-status hooks."""
3331 return self._postdsstatus
3338 return self._postdsstatus
3332
3339
3333 def clearpostdsstatus(self):
3340 def clearpostdsstatus(self):
3334 """Used by workingctx to clear post-dirstate-status hooks."""
3341 """Used by workingctx to clear post-dirstate-status hooks."""
3335 del self._postdsstatus[:]
3342 del self._postdsstatus[:]
3336
3343
3337 def heads(self, start=None):
3344 def heads(self, start=None):
3338 if start is None:
3345 if start is None:
3339 cl = self.changelog
3346 cl = self.changelog
3340 headrevs = reversed(cl.headrevs())
3347 headrevs = reversed(cl.headrevs())
3341 return [cl.node(rev) for rev in headrevs]
3348 return [cl.node(rev) for rev in headrevs]
3342
3349
3343 heads = self.changelog.heads(start)
3350 heads = self.changelog.heads(start)
3344 # sort the output in rev descending order
3351 # sort the output in rev descending order
3345 return sorted(heads, key=self.changelog.rev, reverse=True)
3352 return sorted(heads, key=self.changelog.rev, reverse=True)
3346
3353
3347 def branchheads(self, branch=None, start=None, closed=False):
3354 def branchheads(self, branch=None, start=None, closed=False):
3348 """return a (possibly filtered) list of heads for the given branch
3355 """return a (possibly filtered) list of heads for the given branch
3349
3356
3350 Heads are returned in topological order, from newest to oldest.
3357 Heads are returned in topological order, from newest to oldest.
3351 If branch is None, use the dirstate branch.
3358 If branch is None, use the dirstate branch.
3352 If start is not None, return only heads reachable from start.
3359 If start is not None, return only heads reachable from start.
3353 If closed is True, return heads that are marked as closed as well.
3360 If closed is True, return heads that are marked as closed as well.
3354 """
3361 """
3355 if branch is None:
3362 if branch is None:
3356 branch = self[None].branch()
3363 branch = self[None].branch()
3357 branches = self.branchmap()
3364 branches = self.branchmap()
3358 if not branches.hasbranch(branch):
3365 if not branches.hasbranch(branch):
3359 return []
3366 return []
3360 # the cache returns heads ordered lowest to highest
3367 # the cache returns heads ordered lowest to highest
3361 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3368 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3362 if start is not None:
3369 if start is not None:
3363 # filter out the heads that cannot be reached from startrev
3370 # filter out the heads that cannot be reached from startrev
3364 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3371 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3365 bheads = [h for h in bheads if h in fbheads]
3372 bheads = [h for h in bheads if h in fbheads]
3366 return bheads
3373 return bheads
3367
3374
3368 def branches(self, nodes):
3375 def branches(self, nodes):
3369 if not nodes:
3376 if not nodes:
3370 nodes = [self.changelog.tip()]
3377 nodes = [self.changelog.tip()]
3371 b = []
3378 b = []
3372 for n in nodes:
3379 for n in nodes:
3373 t = n
3380 t = n
3374 while True:
3381 while True:
3375 p = self.changelog.parents(n)
3382 p = self.changelog.parents(n)
3376 if p[1] != self.nullid or p[0] == self.nullid:
3383 if p[1] != self.nullid or p[0] == self.nullid:
3377 b.append((t, n, p[0], p[1]))
3384 b.append((t, n, p[0], p[1]))
3378 break
3385 break
3379 n = p[0]
3386 n = p[0]
3380 return b
3387 return b
3381
3388
3382 def between(self, pairs):
3389 def between(self, pairs):
3383 r = []
3390 r = []
3384
3391
3385 for top, bottom in pairs:
3392 for top, bottom in pairs:
3386 n, l, i = top, [], 0
3393 n, l, i = top, [], 0
3387 f = 1
3394 f = 1
3388
3395
3389 while n != bottom and n != self.nullid:
3396 while n != bottom and n != self.nullid:
3390 p = self.changelog.parents(n)[0]
3397 p = self.changelog.parents(n)[0]
3391 if i == f:
3398 if i == f:
3392 l.append(n)
3399 l.append(n)
3393 f = f * 2
3400 f = f * 2
3394 n = p
3401 n = p
3395 i += 1
3402 i += 1
3396
3403
3397 r.append(l)
3404 r.append(l)
3398
3405
3399 return r
3406 return r
3400
3407
3401 def checkpush(self, pushop):
3408 def checkpush(self, pushop):
3402 """Extensions can override this function if additional checks have
3409 """Extensions can override this function if additional checks have
3403 to be performed before pushing, or call it if they override push
3410 to be performed before pushing, or call it if they override push
3404 command.
3411 command.
3405 """
3412 """
3406
3413
3407 @unfilteredpropertycache
3414 @unfilteredpropertycache
3408 def prepushoutgoinghooks(self):
3415 def prepushoutgoinghooks(self):
3409 """Return util.hooks consists of a pushop with repo, remote, outgoing
3416 """Return util.hooks consists of a pushop with repo, remote, outgoing
3410 methods, which are called before pushing changesets.
3417 methods, which are called before pushing changesets.
3411 """
3418 """
3412 return util.hooks()
3419 return util.hooks()
3413
3420
3414 def pushkey(self, namespace, key, old, new):
3421 def pushkey(self, namespace, key, old, new):
3415 try:
3422 try:
3416 tr = self.currenttransaction()
3423 tr = self.currenttransaction()
3417 hookargs = {}
3424 hookargs = {}
3418 if tr is not None:
3425 if tr is not None:
3419 hookargs.update(tr.hookargs)
3426 hookargs.update(tr.hookargs)
3420 hookargs = pycompat.strkwargs(hookargs)
3427 hookargs = pycompat.strkwargs(hookargs)
3421 hookargs['namespace'] = namespace
3428 hookargs['namespace'] = namespace
3422 hookargs['key'] = key
3429 hookargs['key'] = key
3423 hookargs['old'] = old
3430 hookargs['old'] = old
3424 hookargs['new'] = new
3431 hookargs['new'] = new
3425 self.hook(b'prepushkey', throw=True, **hookargs)
3432 self.hook(b'prepushkey', throw=True, **hookargs)
3426 except error.HookAbort as exc:
3433 except error.HookAbort as exc:
3427 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3434 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3428 if exc.hint:
3435 if exc.hint:
3429 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3436 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3430 return False
3437 return False
3431 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3438 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3432 ret = pushkey.push(self, namespace, key, old, new)
3439 ret = pushkey.push(self, namespace, key, old, new)
3433
3440
3434 def runhook(unused_success):
3441 def runhook(unused_success):
3435 self.hook(
3442 self.hook(
3436 b'pushkey',
3443 b'pushkey',
3437 namespace=namespace,
3444 namespace=namespace,
3438 key=key,
3445 key=key,
3439 old=old,
3446 old=old,
3440 new=new,
3447 new=new,
3441 ret=ret,
3448 ret=ret,
3442 )
3449 )
3443
3450
3444 self._afterlock(runhook)
3451 self._afterlock(runhook)
3445 return ret
3452 return ret
3446
3453
3447 def listkeys(self, namespace):
3454 def listkeys(self, namespace):
3448 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3455 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3449 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3456 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3450 values = pushkey.list(self, namespace)
3457 values = pushkey.list(self, namespace)
3451 self.hook(b'listkeys', namespace=namespace, values=values)
3458 self.hook(b'listkeys', namespace=namespace, values=values)
3452 return values
3459 return values
3453
3460
3454 def debugwireargs(self, one, two, three=None, four=None, five=None):
3461 def debugwireargs(self, one, two, three=None, four=None, five=None):
3455 '''used to test argument passing over the wire'''
3462 '''used to test argument passing over the wire'''
3456 return b"%s %s %s %s %s" % (
3463 return b"%s %s %s %s %s" % (
3457 one,
3464 one,
3458 two,
3465 two,
3459 pycompat.bytestr(three),
3466 pycompat.bytestr(three),
3460 pycompat.bytestr(four),
3467 pycompat.bytestr(four),
3461 pycompat.bytestr(five),
3468 pycompat.bytestr(five),
3462 )
3469 )
3463
3470
3464 def savecommitmessage(self, text):
3471 def savecommitmessage(self, text):
3465 fp = self.vfs(b'last-message.txt', b'wb')
3472 fp = self.vfs(b'last-message.txt', b'wb')
3466 try:
3473 try:
3467 fp.write(text)
3474 fp.write(text)
3468 finally:
3475 finally:
3469 fp.close()
3476 fp.close()
3470 return self.pathto(fp.name[len(self.root) + 1 :])
3477 return self.pathto(fp.name[len(self.root) + 1 :])
3471
3478
3472 def register_wanted_sidedata(self, category):
3479 def register_wanted_sidedata(self, category):
3473 if repository.REPO_FEATURE_SIDE_DATA not in self.features:
3480 if repository.REPO_FEATURE_SIDE_DATA not in self.features:
3474 # Only revlogv2 repos can want sidedata.
3481 # Only revlogv2 repos can want sidedata.
3475 return
3482 return
3476 self._wanted_sidedata.add(pycompat.bytestr(category))
3483 self._wanted_sidedata.add(pycompat.bytestr(category))
3477
3484
3478 def register_sidedata_computer(
3485 def register_sidedata_computer(
3479 self, kind, category, keys, computer, flags, replace=False
3486 self, kind, category, keys, computer, flags, replace=False
3480 ):
3487 ):
3481 if kind not in revlogconst.ALL_KINDS:
3488 if kind not in revlogconst.ALL_KINDS:
3482 msg = _(b"unexpected revlog kind '%s'.")
3489 msg = _(b"unexpected revlog kind '%s'.")
3483 raise error.ProgrammingError(msg % kind)
3490 raise error.ProgrammingError(msg % kind)
3484 category = pycompat.bytestr(category)
3491 category = pycompat.bytestr(category)
3485 already_registered = category in self._sidedata_computers.get(kind, [])
3492 already_registered = category in self._sidedata_computers.get(kind, [])
3486 if already_registered and not replace:
3493 if already_registered and not replace:
3487 msg = _(
3494 msg = _(
3488 b"cannot register a sidedata computer twice for category '%s'."
3495 b"cannot register a sidedata computer twice for category '%s'."
3489 )
3496 )
3490 raise error.ProgrammingError(msg % category)
3497 raise error.ProgrammingError(msg % category)
3491 if replace and not already_registered:
3498 if replace and not already_registered:
3492 msg = _(
3499 msg = _(
3493 b"cannot replace a sidedata computer that isn't registered "
3500 b"cannot replace a sidedata computer that isn't registered "
3494 b"for category '%s'."
3501 b"for category '%s'."
3495 )
3502 )
3496 raise error.ProgrammingError(msg % category)
3503 raise error.ProgrammingError(msg % category)
3497 self._sidedata_computers.setdefault(kind, {})
3504 self._sidedata_computers.setdefault(kind, {})
3498 self._sidedata_computers[kind][category] = (keys, computer, flags)
3505 self._sidedata_computers[kind][category] = (keys, computer, flags)
3499
3506
3500
3507
3501 # used to avoid circular references so destructors work
3508 # used to avoid circular references so destructors work
3502 def aftertrans(files):
3509 def aftertrans(files):
3503 renamefiles = [tuple(t) for t in files]
3510 renamefiles = [tuple(t) for t in files]
3504
3511
3505 def a():
3512 def a():
3506 for vfs, src, dest in renamefiles:
3513 for vfs, src, dest in renamefiles:
3507 # if src and dest refer to a same file, vfs.rename is a no-op,
3514 # if src and dest refer to a same file, vfs.rename is a no-op,
3508 # leaving both src and dest on disk. delete dest to make sure
3515 # leaving both src and dest on disk. delete dest to make sure
3509 # the rename couldn't be such a no-op.
3516 # the rename couldn't be such a no-op.
3510 vfs.tryunlink(dest)
3517 vfs.tryunlink(dest)
3511 try:
3518 try:
3512 vfs.rename(src, dest)
3519 vfs.rename(src, dest)
3513 except FileNotFoundError: # journal file does not yet exist
3520 except FileNotFoundError: # journal file does not yet exist
3514 pass
3521 pass
3515
3522
3516 return a
3523 return a
3517
3524
3518
3525
3519 def undoname(fn):
3526 def undoname(fn):
3520 base, name = os.path.split(fn)
3527 base, name = os.path.split(fn)
3521 assert name.startswith(b'journal')
3528 assert name.startswith(b'journal')
3522 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3529 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3523
3530
3524
3531
3525 def instance(ui, path, create, intents=None, createopts=None):
3532 def instance(ui, path, create, intents=None, createopts=None):
3526
3533
3527 # prevent cyclic import localrepo -> upgrade -> localrepo
3534 # prevent cyclic import localrepo -> upgrade -> localrepo
3528 from . import upgrade
3535 from . import upgrade
3529
3536
3530 localpath = urlutil.urllocalpath(path)
3537 localpath = urlutil.urllocalpath(path)
3531 if create:
3538 if create:
3532 createrepository(ui, localpath, createopts=createopts)
3539 createrepository(ui, localpath, createopts=createopts)
3533
3540
3534 def repo_maker():
3541 def repo_maker():
3535 return makelocalrepository(ui, localpath, intents=intents)
3542 return makelocalrepository(ui, localpath, intents=intents)
3536
3543
3537 repo = repo_maker()
3544 repo = repo_maker()
3538 repo = upgrade.may_auto_upgrade(repo, repo_maker)
3545 repo = upgrade.may_auto_upgrade(repo, repo_maker)
3539 return repo
3546 return repo
3540
3547
3541
3548
3542 def islocal(path):
3549 def islocal(path):
3543 return True
3550 return True
3544
3551
3545
3552
3546 def defaultcreateopts(ui, createopts=None):
3553 def defaultcreateopts(ui, createopts=None):
3547 """Populate the default creation options for a repository.
3554 """Populate the default creation options for a repository.
3548
3555
3549 A dictionary of explicitly requested creation options can be passed
3556 A dictionary of explicitly requested creation options can be passed
3550 in. Missing keys will be populated.
3557 in. Missing keys will be populated.
3551 """
3558 """
3552 createopts = dict(createopts or {})
3559 createopts = dict(createopts or {})
3553
3560
3554 if b'backend' not in createopts:
3561 if b'backend' not in createopts:
3555 # experimental config: storage.new-repo-backend
3562 # experimental config: storage.new-repo-backend
3556 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3563 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3557
3564
3558 return createopts
3565 return createopts
3559
3566
3560
3567
3561 def clone_requirements(ui, createopts, srcrepo):
3568 def clone_requirements(ui, createopts, srcrepo):
3562 """clone the requirements of a local repo for a local clone
3569 """clone the requirements of a local repo for a local clone
3563
3570
3564 The store requirements are unchanged while the working copy requirements
3571 The store requirements are unchanged while the working copy requirements
3565 depends on the configuration
3572 depends on the configuration
3566 """
3573 """
3567 target_requirements = set()
3574 target_requirements = set()
3568 if not srcrepo.requirements:
3575 if not srcrepo.requirements:
3569 # this is a legacy revlog "v0" repository, we cannot do anything fancy
3576 # this is a legacy revlog "v0" repository, we cannot do anything fancy
3570 # with it.
3577 # with it.
3571 return target_requirements
3578 return target_requirements
3572 createopts = defaultcreateopts(ui, createopts=createopts)
3579 createopts = defaultcreateopts(ui, createopts=createopts)
3573 for r in newreporequirements(ui, createopts):
3580 for r in newreporequirements(ui, createopts):
3574 if r in requirementsmod.WORKING_DIR_REQUIREMENTS:
3581 if r in requirementsmod.WORKING_DIR_REQUIREMENTS:
3575 target_requirements.add(r)
3582 target_requirements.add(r)
3576
3583
3577 for r in srcrepo.requirements:
3584 for r in srcrepo.requirements:
3578 if r not in requirementsmod.WORKING_DIR_REQUIREMENTS:
3585 if r not in requirementsmod.WORKING_DIR_REQUIREMENTS:
3579 target_requirements.add(r)
3586 target_requirements.add(r)
3580 return target_requirements
3587 return target_requirements
3581
3588
3582
3589
3583 def newreporequirements(ui, createopts):
3590 def newreporequirements(ui, createopts):
3584 """Determine the set of requirements for a new local repository.
3591 """Determine the set of requirements for a new local repository.
3585
3592
3586 Extensions can wrap this function to specify custom requirements for
3593 Extensions can wrap this function to specify custom requirements for
3587 new repositories.
3594 new repositories.
3588 """
3595 """
3589
3596
3590 if b'backend' not in createopts:
3597 if b'backend' not in createopts:
3591 raise error.ProgrammingError(
3598 raise error.ProgrammingError(
3592 b'backend key not present in createopts; '
3599 b'backend key not present in createopts; '
3593 b'was defaultcreateopts() called?'
3600 b'was defaultcreateopts() called?'
3594 )
3601 )
3595
3602
3596 if createopts[b'backend'] != b'revlogv1':
3603 if createopts[b'backend'] != b'revlogv1':
3597 raise error.Abort(
3604 raise error.Abort(
3598 _(
3605 _(
3599 b'unable to determine repository requirements for '
3606 b'unable to determine repository requirements for '
3600 b'storage backend: %s'
3607 b'storage backend: %s'
3601 )
3608 )
3602 % createopts[b'backend']
3609 % createopts[b'backend']
3603 )
3610 )
3604
3611
3605 requirements = {requirementsmod.REVLOGV1_REQUIREMENT}
3612 requirements = {requirementsmod.REVLOGV1_REQUIREMENT}
3606 if ui.configbool(b'format', b'usestore'):
3613 if ui.configbool(b'format', b'usestore'):
3607 requirements.add(requirementsmod.STORE_REQUIREMENT)
3614 requirements.add(requirementsmod.STORE_REQUIREMENT)
3608 if ui.configbool(b'format', b'usefncache'):
3615 if ui.configbool(b'format', b'usefncache'):
3609 requirements.add(requirementsmod.FNCACHE_REQUIREMENT)
3616 requirements.add(requirementsmod.FNCACHE_REQUIREMENT)
3610 if ui.configbool(b'format', b'dotencode'):
3617 if ui.configbool(b'format', b'dotencode'):
3611 requirements.add(requirementsmod.DOTENCODE_REQUIREMENT)
3618 requirements.add(requirementsmod.DOTENCODE_REQUIREMENT)
3612
3619
3613 compengines = ui.configlist(b'format', b'revlog-compression')
3620 compengines = ui.configlist(b'format', b'revlog-compression')
3614 for compengine in compengines:
3621 for compengine in compengines:
3615 if compengine in util.compengines:
3622 if compengine in util.compengines:
3616 engine = util.compengines[compengine]
3623 engine = util.compengines[compengine]
3617 if engine.available() and engine.revlogheader():
3624 if engine.available() and engine.revlogheader():
3618 break
3625 break
3619 else:
3626 else:
3620 raise error.Abort(
3627 raise error.Abort(
3621 _(
3628 _(
3622 b'compression engines %s defined by '
3629 b'compression engines %s defined by '
3623 b'format.revlog-compression not available'
3630 b'format.revlog-compression not available'
3624 )
3631 )
3625 % b', '.join(b'"%s"' % e for e in compengines),
3632 % b', '.join(b'"%s"' % e for e in compengines),
3626 hint=_(
3633 hint=_(
3627 b'run "hg debuginstall" to list available '
3634 b'run "hg debuginstall" to list available '
3628 b'compression engines'
3635 b'compression engines'
3629 ),
3636 ),
3630 )
3637 )
3631
3638
3632 # zlib is the historical default and doesn't need an explicit requirement.
3639 # zlib is the historical default and doesn't need an explicit requirement.
3633 if compengine == b'zstd':
3640 if compengine == b'zstd':
3634 requirements.add(b'revlog-compression-zstd')
3641 requirements.add(b'revlog-compression-zstd')
3635 elif compengine != b'zlib':
3642 elif compengine != b'zlib':
3636 requirements.add(b'exp-compression-%s' % compengine)
3643 requirements.add(b'exp-compression-%s' % compengine)
3637
3644
3638 if scmutil.gdinitconfig(ui):
3645 if scmutil.gdinitconfig(ui):
3639 requirements.add(requirementsmod.GENERALDELTA_REQUIREMENT)
3646 requirements.add(requirementsmod.GENERALDELTA_REQUIREMENT)
3640 if ui.configbool(b'format', b'sparse-revlog'):
3647 if ui.configbool(b'format', b'sparse-revlog'):
3641 requirements.add(requirementsmod.SPARSEREVLOG_REQUIREMENT)
3648 requirements.add(requirementsmod.SPARSEREVLOG_REQUIREMENT)
3642
3649
3643 # experimental config: format.use-dirstate-v2
3650 # experimental config: format.use-dirstate-v2
3644 # Keep this logic in sync with `has_dirstate_v2()` in `tests/hghave.py`
3651 # Keep this logic in sync with `has_dirstate_v2()` in `tests/hghave.py`
3645 if ui.configbool(b'format', b'use-dirstate-v2'):
3652 if ui.configbool(b'format', b'use-dirstate-v2'):
3646 requirements.add(requirementsmod.DIRSTATE_V2_REQUIREMENT)
3653 requirements.add(requirementsmod.DIRSTATE_V2_REQUIREMENT)
3647
3654
3648 # experimental config: format.exp-use-copies-side-data-changeset
3655 # experimental config: format.exp-use-copies-side-data-changeset
3649 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3656 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3650 requirements.add(requirementsmod.CHANGELOGV2_REQUIREMENT)
3657 requirements.add(requirementsmod.CHANGELOGV2_REQUIREMENT)
3651 requirements.add(requirementsmod.COPIESSDC_REQUIREMENT)
3658 requirements.add(requirementsmod.COPIESSDC_REQUIREMENT)
3652 if ui.configbool(b'experimental', b'treemanifest'):
3659 if ui.configbool(b'experimental', b'treemanifest'):
3653 requirements.add(requirementsmod.TREEMANIFEST_REQUIREMENT)
3660 requirements.add(requirementsmod.TREEMANIFEST_REQUIREMENT)
3654
3661
3655 changelogv2 = ui.config(b'format', b'exp-use-changelog-v2')
3662 changelogv2 = ui.config(b'format', b'exp-use-changelog-v2')
3656 if changelogv2 == b'enable-unstable-format-and-corrupt-my-data':
3663 if changelogv2 == b'enable-unstable-format-and-corrupt-my-data':
3657 requirements.add(requirementsmod.CHANGELOGV2_REQUIREMENT)
3664 requirements.add(requirementsmod.CHANGELOGV2_REQUIREMENT)
3658
3665
3659 revlogv2 = ui.config(b'experimental', b'revlogv2')
3666 revlogv2 = ui.config(b'experimental', b'revlogv2')
3660 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3667 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3661 requirements.discard(requirementsmod.REVLOGV1_REQUIREMENT)
3668 requirements.discard(requirementsmod.REVLOGV1_REQUIREMENT)
3662 requirements.add(requirementsmod.REVLOGV2_REQUIREMENT)
3669 requirements.add(requirementsmod.REVLOGV2_REQUIREMENT)
3663 # experimental config: format.internal-phase
3670 # experimental config: format.internal-phase
3664 if ui.configbool(b'format', b'internal-phase'):
3671 if ui.configbool(b'format', b'internal-phase'):
3665 requirements.add(requirementsmod.INTERNAL_PHASE_REQUIREMENT)
3672 requirements.add(requirementsmod.INTERNAL_PHASE_REQUIREMENT)
3666
3673
3667 if createopts.get(b'narrowfiles'):
3674 if createopts.get(b'narrowfiles'):
3668 requirements.add(requirementsmod.NARROW_REQUIREMENT)
3675 requirements.add(requirementsmod.NARROW_REQUIREMENT)
3669
3676
3670 if createopts.get(b'lfs'):
3677 if createopts.get(b'lfs'):
3671 requirements.add(b'lfs')
3678 requirements.add(b'lfs')
3672
3679
3673 if ui.configbool(b'format', b'bookmarks-in-store'):
3680 if ui.configbool(b'format', b'bookmarks-in-store'):
3674 requirements.add(requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT)
3681 requirements.add(requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT)
3675
3682
3676 if ui.configbool(b'format', b'use-persistent-nodemap'):
3683 if ui.configbool(b'format', b'use-persistent-nodemap'):
3677 requirements.add(requirementsmod.NODEMAP_REQUIREMENT)
3684 requirements.add(requirementsmod.NODEMAP_REQUIREMENT)
3678
3685
3679 # if share-safe is enabled, let's create the new repository with the new
3686 # if share-safe is enabled, let's create the new repository with the new
3680 # requirement
3687 # requirement
3681 if ui.configbool(b'format', b'use-share-safe'):
3688 if ui.configbool(b'format', b'use-share-safe'):
3682 requirements.add(requirementsmod.SHARESAFE_REQUIREMENT)
3689 requirements.add(requirementsmod.SHARESAFE_REQUIREMENT)
3683
3690
3684 # if we are creating a share-repoΒΉ we have to handle requirement
3691 # if we are creating a share-repoΒΉ we have to handle requirement
3685 # differently.
3692 # differently.
3686 #
3693 #
3687 # [1] (i.e. reusing the store from another repository, just having a
3694 # [1] (i.e. reusing the store from another repository, just having a
3688 # working copy)
3695 # working copy)
3689 if b'sharedrepo' in createopts:
3696 if b'sharedrepo' in createopts:
3690 source_requirements = set(createopts[b'sharedrepo'].requirements)
3697 source_requirements = set(createopts[b'sharedrepo'].requirements)
3691
3698
3692 if requirementsmod.SHARESAFE_REQUIREMENT not in source_requirements:
3699 if requirementsmod.SHARESAFE_REQUIREMENT not in source_requirements:
3693 # share to an old school repository, we have to copy the
3700 # share to an old school repository, we have to copy the
3694 # requirements and hope for the best.
3701 # requirements and hope for the best.
3695 requirements = source_requirements
3702 requirements = source_requirements
3696 else:
3703 else:
3697 # We have control on the working copy only, so "copy" the non
3704 # We have control on the working copy only, so "copy" the non
3698 # working copy part over, ignoring previous logic.
3705 # working copy part over, ignoring previous logic.
3699 to_drop = set()
3706 to_drop = set()
3700 for req in requirements:
3707 for req in requirements:
3701 if req in requirementsmod.WORKING_DIR_REQUIREMENTS:
3708 if req in requirementsmod.WORKING_DIR_REQUIREMENTS:
3702 continue
3709 continue
3703 if req in source_requirements:
3710 if req in source_requirements:
3704 continue
3711 continue
3705 to_drop.add(req)
3712 to_drop.add(req)
3706 requirements -= to_drop
3713 requirements -= to_drop
3707 requirements |= source_requirements
3714 requirements |= source_requirements
3708
3715
3709 if createopts.get(b'sharedrelative'):
3716 if createopts.get(b'sharedrelative'):
3710 requirements.add(requirementsmod.RELATIVE_SHARED_REQUIREMENT)
3717 requirements.add(requirementsmod.RELATIVE_SHARED_REQUIREMENT)
3711 else:
3718 else:
3712 requirements.add(requirementsmod.SHARED_REQUIREMENT)
3719 requirements.add(requirementsmod.SHARED_REQUIREMENT)
3713
3720
3714 if ui.configbool(b'format', b'use-dirstate-tracked-hint'):
3721 if ui.configbool(b'format', b'use-dirstate-tracked-hint'):
3715 version = ui.configint(b'format', b'use-dirstate-tracked-hint.version')
3722 version = ui.configint(b'format', b'use-dirstate-tracked-hint.version')
3716 msg = _("ignoring unknown tracked key version: %d\n")
3723 msg = _("ignoring unknown tracked key version: %d\n")
3717 hint = _("see `hg help config.format.use-dirstate-tracked-hint-version")
3724 hint = _("see `hg help config.format.use-dirstate-tracked-hint-version")
3718 if version != 1:
3725 if version != 1:
3719 ui.warn(msg % version, hint=hint)
3726 ui.warn(msg % version, hint=hint)
3720 else:
3727 else:
3721 requirements.add(requirementsmod.DIRSTATE_TRACKED_HINT_V1)
3728 requirements.add(requirementsmod.DIRSTATE_TRACKED_HINT_V1)
3722
3729
3723 return requirements
3730 return requirements
3724
3731
3725
3732
3726 def checkrequirementscompat(ui, requirements):
3733 def checkrequirementscompat(ui, requirements):
3727 """Checks compatibility of repository requirements enabled and disabled.
3734 """Checks compatibility of repository requirements enabled and disabled.
3728
3735
3729 Returns a set of requirements which needs to be dropped because dependend
3736 Returns a set of requirements which needs to be dropped because dependend
3730 requirements are not enabled. Also warns users about it"""
3737 requirements are not enabled. Also warns users about it"""
3731
3738
3732 dropped = set()
3739 dropped = set()
3733
3740
3734 if requirementsmod.STORE_REQUIREMENT not in requirements:
3741 if requirementsmod.STORE_REQUIREMENT not in requirements:
3735 if requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT in requirements:
3742 if requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT in requirements:
3736 ui.warn(
3743 ui.warn(
3737 _(
3744 _(
3738 b'ignoring enabled \'format.bookmarks-in-store\' config '
3745 b'ignoring enabled \'format.bookmarks-in-store\' config '
3739 b'beacuse it is incompatible with disabled '
3746 b'beacuse it is incompatible with disabled '
3740 b'\'format.usestore\' config\n'
3747 b'\'format.usestore\' config\n'
3741 )
3748 )
3742 )
3749 )
3743 dropped.add(requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT)
3750 dropped.add(requirementsmod.BOOKMARKS_IN_STORE_REQUIREMENT)
3744
3751
3745 if (
3752 if (
3746 requirementsmod.SHARED_REQUIREMENT in requirements
3753 requirementsmod.SHARED_REQUIREMENT in requirements
3747 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
3754 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
3748 ):
3755 ):
3749 raise error.Abort(
3756 raise error.Abort(
3750 _(
3757 _(
3751 b"cannot create shared repository as source was created"
3758 b"cannot create shared repository as source was created"
3752 b" with 'format.usestore' config disabled"
3759 b" with 'format.usestore' config disabled"
3753 )
3760 )
3754 )
3761 )
3755
3762
3756 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
3763 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
3757 if ui.hasconfig(b'format', b'use-share-safe'):
3764 if ui.hasconfig(b'format', b'use-share-safe'):
3758 msg = _(
3765 msg = _(
3759 b"ignoring enabled 'format.use-share-safe' config because "
3766 b"ignoring enabled 'format.use-share-safe' config because "
3760 b"it is incompatible with disabled 'format.usestore'"
3767 b"it is incompatible with disabled 'format.usestore'"
3761 b" config\n"
3768 b" config\n"
3762 )
3769 )
3763 ui.warn(msg)
3770 ui.warn(msg)
3764 dropped.add(requirementsmod.SHARESAFE_REQUIREMENT)
3771 dropped.add(requirementsmod.SHARESAFE_REQUIREMENT)
3765
3772
3766 return dropped
3773 return dropped
3767
3774
3768
3775
3769 def filterknowncreateopts(ui, createopts):
3776 def filterknowncreateopts(ui, createopts):
3770 """Filters a dict of repo creation options against options that are known.
3777 """Filters a dict of repo creation options against options that are known.
3771
3778
3772 Receives a dict of repo creation options and returns a dict of those
3779 Receives a dict of repo creation options and returns a dict of those
3773 options that we don't know how to handle.
3780 options that we don't know how to handle.
3774
3781
3775 This function is called as part of repository creation. If the
3782 This function is called as part of repository creation. If the
3776 returned dict contains any items, repository creation will not
3783 returned dict contains any items, repository creation will not
3777 be allowed, as it means there was a request to create a repository
3784 be allowed, as it means there was a request to create a repository
3778 with options not recognized by loaded code.
3785 with options not recognized by loaded code.
3779
3786
3780 Extensions can wrap this function to filter out creation options
3787 Extensions can wrap this function to filter out creation options
3781 they know how to handle.
3788 they know how to handle.
3782 """
3789 """
3783 known = {
3790 known = {
3784 b'backend',
3791 b'backend',
3785 b'lfs',
3792 b'lfs',
3786 b'narrowfiles',
3793 b'narrowfiles',
3787 b'sharedrepo',
3794 b'sharedrepo',
3788 b'sharedrelative',
3795 b'sharedrelative',
3789 b'shareditems',
3796 b'shareditems',
3790 b'shallowfilestore',
3797 b'shallowfilestore',
3791 }
3798 }
3792
3799
3793 return {k: v for k, v in createopts.items() if k not in known}
3800 return {k: v for k, v in createopts.items() if k not in known}
3794
3801
3795
3802
3796 def createrepository(ui, path, createopts=None, requirements=None):
3803 def createrepository(ui, path, createopts=None, requirements=None):
3797 """Create a new repository in a vfs.
3804 """Create a new repository in a vfs.
3798
3805
3799 ``path`` path to the new repo's working directory.
3806 ``path`` path to the new repo's working directory.
3800 ``createopts`` options for the new repository.
3807 ``createopts`` options for the new repository.
3801 ``requirement`` predefined set of requirements.
3808 ``requirement`` predefined set of requirements.
3802 (incompatible with ``createopts``)
3809 (incompatible with ``createopts``)
3803
3810
3804 The following keys for ``createopts`` are recognized:
3811 The following keys for ``createopts`` are recognized:
3805
3812
3806 backend
3813 backend
3807 The storage backend to use.
3814 The storage backend to use.
3808 lfs
3815 lfs
3809 Repository will be created with ``lfs`` requirement. The lfs extension
3816 Repository will be created with ``lfs`` requirement. The lfs extension
3810 will automatically be loaded when the repository is accessed.
3817 will automatically be loaded when the repository is accessed.
3811 narrowfiles
3818 narrowfiles
3812 Set up repository to support narrow file storage.
3819 Set up repository to support narrow file storage.
3813 sharedrepo
3820 sharedrepo
3814 Repository object from which storage should be shared.
3821 Repository object from which storage should be shared.
3815 sharedrelative
3822 sharedrelative
3816 Boolean indicating if the path to the shared repo should be
3823 Boolean indicating if the path to the shared repo should be
3817 stored as relative. By default, the pointer to the "parent" repo
3824 stored as relative. By default, the pointer to the "parent" repo
3818 is stored as an absolute path.
3825 is stored as an absolute path.
3819 shareditems
3826 shareditems
3820 Set of items to share to the new repository (in addition to storage).
3827 Set of items to share to the new repository (in addition to storage).
3821 shallowfilestore
3828 shallowfilestore
3822 Indicates that storage for files should be shallow (not all ancestor
3829 Indicates that storage for files should be shallow (not all ancestor
3823 revisions are known).
3830 revisions are known).
3824 """
3831 """
3825
3832
3826 if requirements is not None:
3833 if requirements is not None:
3827 if createopts is not None:
3834 if createopts is not None:
3828 msg = b'cannot specify both createopts and requirements'
3835 msg = b'cannot specify both createopts and requirements'
3829 raise error.ProgrammingError(msg)
3836 raise error.ProgrammingError(msg)
3830 createopts = {}
3837 createopts = {}
3831 else:
3838 else:
3832 createopts = defaultcreateopts(ui, createopts=createopts)
3839 createopts = defaultcreateopts(ui, createopts=createopts)
3833
3840
3834 unknownopts = filterknowncreateopts(ui, createopts)
3841 unknownopts = filterknowncreateopts(ui, createopts)
3835
3842
3836 if not isinstance(unknownopts, dict):
3843 if not isinstance(unknownopts, dict):
3837 raise error.ProgrammingError(
3844 raise error.ProgrammingError(
3838 b'filterknowncreateopts() did not return a dict'
3845 b'filterknowncreateopts() did not return a dict'
3839 )
3846 )
3840
3847
3841 if unknownopts:
3848 if unknownopts:
3842 raise error.Abort(
3849 raise error.Abort(
3843 _(
3850 _(
3844 b'unable to create repository because of unknown '
3851 b'unable to create repository because of unknown '
3845 b'creation option: %s'
3852 b'creation option: %s'
3846 )
3853 )
3847 % b', '.join(sorted(unknownopts)),
3854 % b', '.join(sorted(unknownopts)),
3848 hint=_(b'is a required extension not loaded?'),
3855 hint=_(b'is a required extension not loaded?'),
3849 )
3856 )
3850
3857
3851 requirements = newreporequirements(ui, createopts=createopts)
3858 requirements = newreporequirements(ui, createopts=createopts)
3852 requirements -= checkrequirementscompat(ui, requirements)
3859 requirements -= checkrequirementscompat(ui, requirements)
3853
3860
3854 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3861 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3855
3862
3856 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3863 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3857 if hgvfs.exists():
3864 if hgvfs.exists():
3858 raise error.RepoError(_(b'repository %s already exists') % path)
3865 raise error.RepoError(_(b'repository %s already exists') % path)
3859
3866
3860 if b'sharedrepo' in createopts:
3867 if b'sharedrepo' in createopts:
3861 sharedpath = createopts[b'sharedrepo'].sharedpath
3868 sharedpath = createopts[b'sharedrepo'].sharedpath
3862
3869
3863 if createopts.get(b'sharedrelative'):
3870 if createopts.get(b'sharedrelative'):
3864 try:
3871 try:
3865 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3872 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3866 sharedpath = util.pconvert(sharedpath)
3873 sharedpath = util.pconvert(sharedpath)
3867 except (IOError, ValueError) as e:
3874 except (IOError, ValueError) as e:
3868 # ValueError is raised on Windows if the drive letters differ
3875 # ValueError is raised on Windows if the drive letters differ
3869 # on each path.
3876 # on each path.
3870 raise error.Abort(
3877 raise error.Abort(
3871 _(b'cannot calculate relative path'),
3878 _(b'cannot calculate relative path'),
3872 hint=stringutil.forcebytestr(e),
3879 hint=stringutil.forcebytestr(e),
3873 )
3880 )
3874
3881
3875 if not wdirvfs.exists():
3882 if not wdirvfs.exists():
3876 wdirvfs.makedirs()
3883 wdirvfs.makedirs()
3877
3884
3878 hgvfs.makedir(notindexed=True)
3885 hgvfs.makedir(notindexed=True)
3879 if b'sharedrepo' not in createopts:
3886 if b'sharedrepo' not in createopts:
3880 hgvfs.mkdir(b'cache')
3887 hgvfs.mkdir(b'cache')
3881 hgvfs.mkdir(b'wcache')
3888 hgvfs.mkdir(b'wcache')
3882
3889
3883 has_store = requirementsmod.STORE_REQUIREMENT in requirements
3890 has_store = requirementsmod.STORE_REQUIREMENT in requirements
3884 if has_store and b'sharedrepo' not in createopts:
3891 if has_store and b'sharedrepo' not in createopts:
3885 hgvfs.mkdir(b'store')
3892 hgvfs.mkdir(b'store')
3886
3893
3887 # We create an invalid changelog outside the store so very old
3894 # We create an invalid changelog outside the store so very old
3888 # Mercurial versions (which didn't know about the requirements
3895 # Mercurial versions (which didn't know about the requirements
3889 # file) encounter an error on reading the changelog. This
3896 # file) encounter an error on reading the changelog. This
3890 # effectively locks out old clients and prevents them from
3897 # effectively locks out old clients and prevents them from
3891 # mucking with a repo in an unknown format.
3898 # mucking with a repo in an unknown format.
3892 #
3899 #
3893 # The revlog header has version 65535, which won't be recognized by
3900 # The revlog header has version 65535, which won't be recognized by
3894 # such old clients.
3901 # such old clients.
3895 hgvfs.append(
3902 hgvfs.append(
3896 b'00changelog.i',
3903 b'00changelog.i',
3897 b'\0\0\xFF\xFF dummy changelog to prevent using the old repo '
3904 b'\0\0\xFF\xFF dummy changelog to prevent using the old repo '
3898 b'layout',
3905 b'layout',
3899 )
3906 )
3900
3907
3901 # Filter the requirements into working copy and store ones
3908 # Filter the requirements into working copy and store ones
3902 wcreq, storereq = scmutil.filterrequirements(requirements)
3909 wcreq, storereq = scmutil.filterrequirements(requirements)
3903 # write working copy ones
3910 # write working copy ones
3904 scmutil.writerequires(hgvfs, wcreq)
3911 scmutil.writerequires(hgvfs, wcreq)
3905 # If there are store requirements and the current repository
3912 # If there are store requirements and the current repository
3906 # is not a shared one, write stored requirements
3913 # is not a shared one, write stored requirements
3907 # For new shared repository, we don't need to write the store
3914 # For new shared repository, we don't need to write the store
3908 # requirements as they are already present in store requires
3915 # requirements as they are already present in store requires
3909 if storereq and b'sharedrepo' not in createopts:
3916 if storereq and b'sharedrepo' not in createopts:
3910 storevfs = vfsmod.vfs(hgvfs.join(b'store'), cacheaudited=True)
3917 storevfs = vfsmod.vfs(hgvfs.join(b'store'), cacheaudited=True)
3911 scmutil.writerequires(storevfs, storereq)
3918 scmutil.writerequires(storevfs, storereq)
3912
3919
3913 # Write out file telling readers where to find the shared store.
3920 # Write out file telling readers where to find the shared store.
3914 if b'sharedrepo' in createopts:
3921 if b'sharedrepo' in createopts:
3915 hgvfs.write(b'sharedpath', sharedpath)
3922 hgvfs.write(b'sharedpath', sharedpath)
3916
3923
3917 if createopts.get(b'shareditems'):
3924 if createopts.get(b'shareditems'):
3918 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3925 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3919 hgvfs.write(b'shared', shared)
3926 hgvfs.write(b'shared', shared)
3920
3927
3921
3928
3922 def poisonrepository(repo):
3929 def poisonrepository(repo):
3923 """Poison a repository instance so it can no longer be used."""
3930 """Poison a repository instance so it can no longer be used."""
3924 # Perform any cleanup on the instance.
3931 # Perform any cleanup on the instance.
3925 repo.close()
3932 repo.close()
3926
3933
3927 # Our strategy is to replace the type of the object with one that
3934 # Our strategy is to replace the type of the object with one that
3928 # has all attribute lookups result in error.
3935 # has all attribute lookups result in error.
3929 #
3936 #
3930 # But we have to allow the close() method because some constructors
3937 # But we have to allow the close() method because some constructors
3931 # of repos call close() on repo references.
3938 # of repos call close() on repo references.
3932 class poisonedrepository:
3939 class poisonedrepository:
3933 def __getattribute__(self, item):
3940 def __getattribute__(self, item):
3934 if item == 'close':
3941 if item == 'close':
3935 return object.__getattribute__(self, item)
3942 return object.__getattribute__(self, item)
3936
3943
3937 raise error.ProgrammingError(
3944 raise error.ProgrammingError(
3938 b'repo instances should not be used after unshare'
3945 b'repo instances should not be used after unshare'
3939 )
3946 )
3940
3947
3941 def close(self):
3948 def close(self):
3942 pass
3949 pass
3943
3950
3944 # We may have a repoview, which intercepts __setattr__. So be sure
3951 # We may have a repoview, which intercepts __setattr__. So be sure
3945 # we operate at the lowest level possible.
3952 # we operate at the lowest level possible.
3946 object.__setattr__(repo, '__class__', poisonedrepository)
3953 object.__setattr__(repo, '__class__', poisonedrepository)
@@ -1,253 +1,247 b''
1 #testcases dirstate-v1 dirstate-v2
1 #testcases dirstate-v1 dirstate-v2
2
2
3 #if dirstate-v2
3 #if dirstate-v2
4 $ cat >> $HGRCPATH << EOF
4 $ cat >> $HGRCPATH << EOF
5 > [format]
5 > [format]
6 > use-dirstate-v2=1
6 > use-dirstate-v2=1
7 > [storage]
7 > [storage]
8 > dirstate-v2.slow-path=allow
8 > dirstate-v2.slow-path=allow
9 > EOF
9 > EOF
10 #endif
10 #endif
11
11
12 ------ Test dirstate._dirs refcounting
12 ------ Test dirstate._dirs refcounting
13
13
14 $ hg init t
14 $ hg init t
15 $ cd t
15 $ cd t
16 $ mkdir -p a/b/c/d
16 $ mkdir -p a/b/c/d
17 $ touch a/b/c/d/x
17 $ touch a/b/c/d/x
18 $ touch a/b/c/d/y
18 $ touch a/b/c/d/y
19 $ touch a/b/c/d/z
19 $ touch a/b/c/d/z
20 $ hg ci -Am m
20 $ hg ci -Am m
21 adding a/b/c/d/x
21 adding a/b/c/d/x
22 adding a/b/c/d/y
22 adding a/b/c/d/y
23 adding a/b/c/d/z
23 adding a/b/c/d/z
24 $ hg mv a z
24 $ hg mv a z
25 moving a/b/c/d/x to z/b/c/d/x
25 moving a/b/c/d/x to z/b/c/d/x
26 moving a/b/c/d/y to z/b/c/d/y
26 moving a/b/c/d/y to z/b/c/d/y
27 moving a/b/c/d/z to z/b/c/d/z
27 moving a/b/c/d/z to z/b/c/d/z
28
28
29 Test name collisions
29 Test name collisions
30
30
31 $ rm z/b/c/d/x
31 $ rm z/b/c/d/x
32 $ mkdir z/b/c/d/x
32 $ mkdir z/b/c/d/x
33 $ touch z/b/c/d/x/y
33 $ touch z/b/c/d/x/y
34 $ hg add z/b/c/d/x/y
34 $ hg add z/b/c/d/x/y
35 abort: file 'z/b/c/d/x' in dirstate clashes with 'z/b/c/d/x/y'
35 abort: file 'z/b/c/d/x' in dirstate clashes with 'z/b/c/d/x/y'
36 [255]
36 [255]
37 $ rm -rf z/b/c/d
37 $ rm -rf z/b/c/d
38 $ touch z/b/c/d
38 $ touch z/b/c/d
39 $ hg add z/b/c/d
39 $ hg add z/b/c/d
40 abort: directory 'z/b/c/d' already in dirstate
40 abort: directory 'z/b/c/d' already in dirstate
41 [255]
41 [255]
42
42
43 $ cd ..
43 $ cd ..
44
44
45 Issue1790: dirstate entry locked into unset if file mtime is set into
45 Issue1790: dirstate entry locked into unset if file mtime is set into
46 the future
46 the future
47
47
48 Prepare test repo:
48 Prepare test repo:
49
49
50 $ hg init u
50 $ hg init u
51 $ cd u
51 $ cd u
52 $ echo a > a
52 $ echo a > a
53 $ hg add
53 $ hg add
54 adding a
54 adding a
55 $ hg ci -m1
55 $ hg ci -m1
56
56
57 Set mtime of a into the future:
57 Set mtime of a into the future:
58
58
59 $ touch -t 203101011200 a
59 $ touch -t 203101011200 a
60
60
61 Status must not set a's entry to unset (issue1790):
61 Status must not set a's entry to unset (issue1790):
62
62
63 $ hg status
63 $ hg status
64 $ hg debugstate
64 $ hg debugstate
65 n 644 2 2031-01-01 12:00:00 a
65 n 644 2 2031-01-01 12:00:00 a
66
66
67 Test modulo storage/comparison of absurd dates:
67 Test modulo storage/comparison of absurd dates:
68
68
69 #if no-aix
69 #if no-aix
70 $ touch -t 195001011200 a
70 $ touch -t 195001011200 a
71 $ hg st
71 $ hg st
72 $ hg debugstate
72 $ hg debugstate
73 n 644 2 2018-01-19 15:14:08 a
73 n 644 2 2018-01-19 15:14:08 a
74 #endif
74 #endif
75
75
76 Verify that exceptions during a dirstate change leave the dirstate
76 Verify that exceptions during a dirstate change leave the dirstate
77 coherent (issue4353)
77 coherent (issue4353)
78
78
79 $ cat > ../dirstateexception.py <<EOF
79 $ cat > ../dirstateexception.py <<EOF
80 > from mercurial import (
80 > from mercurial import (
81 > error,
81 > error,
82 > extensions,
82 > extensions,
83 > mergestate as mergestatemod,
83 > mergestate as mergestatemod,
84 > )
84 > )
85 >
85 >
86 > def wraprecordupdates(*args):
86 > def wraprecordupdates(*args):
87 > raise error.Abort(b"simulated error while recording dirstateupdates")
87 > raise error.Abort(b"simulated error while recording dirstateupdates")
88 >
88 >
89 > def reposetup(ui, repo):
89 > def reposetup(ui, repo):
90 > extensions.wrapfunction(mergestatemod, 'recordupdates',
90 > extensions.wrapfunction(mergestatemod, 'recordupdates',
91 > wraprecordupdates)
91 > wraprecordupdates)
92 > EOF
92 > EOF
93
93
94 $ hg rm a
94 $ hg rm a
95 $ hg commit -m 'rm a'
95 $ hg commit -m 'rm a'
96 $ echo "[extensions]" >> .hg/hgrc
96 $ echo "[extensions]" >> .hg/hgrc
97 $ echo "dirstateex=../dirstateexception.py" >> .hg/hgrc
97 $ echo "dirstateex=../dirstateexception.py" >> .hg/hgrc
98 $ hg up 0
98 $ hg up 0
99 abort: simulated error while recording dirstateupdates
99 abort: simulated error while recording dirstateupdates
100 [255]
100 [255]
101 $ hg log -r . -T '{rev}\n'
101 $ hg log -r . -T '{rev}\n'
102 1
102 1
103 $ hg status
103 $ hg status
104 ? a
104 ? a
105
105
106 #if dirstate-v2
106 #if dirstate-v2
107 Check that folders that are prefixes of others do not throw the packer into an
107 Check that folders that are prefixes of others do not throw the packer into an
108 infinite loop.
108 infinite loop.
109
109
110 $ cd ..
110 $ cd ..
111 $ hg init infinite-loop
111 $ hg init infinite-loop
112 $ cd infinite-loop
112 $ cd infinite-loop
113 $ mkdir hgext3rd hgext
113 $ mkdir hgext3rd hgext
114 $ touch hgext3rd/__init__.py hgext/zeroconf.py
114 $ touch hgext3rd/__init__.py hgext/zeroconf.py
115 $ hg commit -Aqm0
115 $ hg commit -Aqm0
116
116
117 $ hg st -c
117 $ hg st -c
118 C hgext/zeroconf.py
118 C hgext/zeroconf.py
119 C hgext3rd/__init__.py
119 C hgext3rd/__init__.py
120
120
121 $ cd ..
121 $ cd ..
122
122
123 Check that the old dirstate data file is removed correctly and the new one is
123 Check that the old dirstate data file is removed correctly and the new one is
124 valid.
124 valid.
125
125
126 $ dirstate_data_files () {
126 $ dirstate_data_files () {
127 > find .hg -maxdepth 1 -name "dirstate.*"
127 > find .hg -maxdepth 1 -name "dirstate.*"
128 > }
128 > }
129
129
130 $ find_dirstate_uuid () {
130 $ find_dirstate_uuid () {
131 > hg debugstate --docket | grep uuid | sed 's/.*uuid: \(.*\)/\1/'
131 > hg debugstate --docket | grep uuid | sed 's/.*uuid: \(.*\)/\1/'
132 > }
132 > }
133
133
134 $ find_dirstate_data_size () {
134 $ find_dirstate_data_size () {
135 > hg debugstate --docket | grep 'size of dirstate data' | sed 's/.*size of dirstate data: \(.*\)/\1/'
135 > hg debugstate --docket | grep 'size of dirstate data' | sed 's/.*size of dirstate data: \(.*\)/\1/'
136 > }
136 > }
137
137
138 $ dirstate_uuid_has_not_changed () {
138 $ dirstate_uuid_has_not_changed () {
139 > # Non-Rust always rewrites the whole dirstate
139 > # Non-Rust always rewrites the whole dirstate
140 > if [ $# -eq 1 ] || ([ -n "$HGMODULEPOLICY" ] && [ -z "${HGMODULEPOLICY##*rust*}" ]) || [ -n "$RHG_INSTALLED_AS_HG" ]; then
140 > if [ $# -eq 1 ] || ([ -n "$HGMODULEPOLICY" ] && [ -z "${HGMODULEPOLICY##*rust*}" ]) || [ -n "$RHG_INSTALLED_AS_HG" ]; then
141 > test $current_uid = $(find_dirstate_uuid)
141 > test $current_uid = $(find_dirstate_uuid)
142 > else
142 > else
143 > echo "not testing because using Python implementation"
143 > echo "not testing because using Python implementation"
144 > fi
144 > fi
145 > }
145 > }
146
146
147 $ cd ..
147 $ cd ..
148 $ hg init append-mostly
148 $ hg init append-mostly
149 $ cd append-mostly
149 $ cd append-mostly
150 $ mkdir dir dir2
150 $ mkdir dir dir2
151 $ touch dir/a dir/b dir/c dir/d dir/e dir2/f
151 $ touch dir/a dir/b dir/c dir/d dir/e dir2/f
152 $ hg commit -Aqm initial
152 $ hg commit -Aqm initial
153 $ hg st
153 $ hg st
154 $ dirstate_data_files | wc -l
154 $ dirstate_data_files | wc -l
155 *1 (re)
155 *1 (re)
156 $ current_uid=$(find_dirstate_uuid)
156 $ current_uid=$(find_dirstate_uuid)
157
157
158 Nothing changes here
158 Nothing changes here
159
159
160 $ hg st
160 $ hg st
161 $ dirstate_data_files | wc -l
161 $ dirstate_data_files | wc -l
162 *1 (re)
162 *1 (re)
163 $ dirstate_uuid_has_not_changed
163 $ dirstate_uuid_has_not_changed
164 not testing because using Python implementation (no-rust no-rhg !)
164 not testing because using Python implementation (no-rust no-rhg !)
165
165
166 Trigger an append with a small change
166 Trigger an append with a small change
167
167
168 $ current_data_size=$(find_dirstate_data_size)
168 $ current_data_size=$(find_dirstate_data_size)
169 $ rm dir2/f
169 $ rm dir2/f
170 $ hg st
170 $ hg st
171 ! dir2/f
171 ! dir2/f
172 $ dirstate_data_files | wc -l
172 $ dirstate_data_files | wc -l
173 *1 (re)
173 *1 (re)
174 $ dirstate_uuid_has_not_changed
174 $ dirstate_uuid_has_not_changed
175 not testing because using Python implementation (no-rust no-rhg !)
175 not testing because using Python implementation (no-rust no-rhg !)
176 $ new_data_size=$(find_dirstate_data_size)
176 $ new_data_size=$(find_dirstate_data_size)
177 $ [ "$current_data_size" -eq "$new_data_size" ]; echo $?
177 $ [ "$current_data_size" -eq "$new_data_size" ]; echo $?
178 0 (no-rust no-rhg !)
178 0 (no-rust no-rhg !)
179 1 (rust !)
179 1 (rust !)
180 1 (no-rust rhg !)
180 1 (no-rust rhg !)
181
181
182 Unused bytes counter is non-0 when appending
182 Unused bytes counter is non-0 when appending
183 $ touch file
183 $ touch file
184 $ hg add file
184 $ hg add file
185 $ current_uid=$(find_dirstate_uuid)
185 $ current_uid=$(find_dirstate_uuid)
186
186
187 Trigger a rust/rhg run which updates the unused bytes value
187 Trigger a rust/rhg run which updates the unused bytes value
188 $ hg st
188 $ hg st
189 A file
189 A file
190 ! dir2/f
190 ! dir2/f
191 $ dirstate_data_files | wc -l
191 $ dirstate_data_files | wc -l
192 *1 (re)
192 *1 (re)
193 $ dirstate_uuid_has_not_changed
193 $ dirstate_uuid_has_not_changed
194 not testing because using Python implementation (no-rust no-rhg !)
194 not testing because using Python implementation (no-rust no-rhg !)
195
195
196 $ hg debugstate --docket | grep unused
196 $ hg debugstate --docket | grep unused
197 number of unused bytes: 0 (no-rust no-rhg !)
197 number of unused bytes: 0 (no-rust no-rhg !)
198 number of unused bytes: [1-9]\d* (re) (rhg no-rust !)
198 number of unused bytes: [1-9]\d* (re) (rhg no-rust !)
199 number of unused bytes: [1-9]\d* (re) (rust no-rhg !)
199 number of unused bytes: [1-9]\d* (re) (rust no-rhg !)
200 number of unused bytes: [1-9]\d* (re) (rust rhg !)
200 number of unused bytes: [1-9]\d* (re) (rust rhg !)
201
201
202 Delete most of the dirstate to trigger a non-append
202 Delete most of the dirstate to trigger a non-append
203 $ hg rm dir/a dir/b dir/c dir/d
203 $ hg rm dir/a dir/b dir/c dir/d
204 $ dirstate_data_files | wc -l
204 $ dirstate_data_files | wc -l
205 *1 (re)
205 *1 (re)
206 $ dirstate_uuid_has_not_changed also-if-python
206 $ dirstate_uuid_has_not_changed also-if-python
207 [1]
207 [1]
208
208
209 Check that unused bytes counter is reset when creating a new docket
209 Check that unused bytes counter is reset when creating a new docket
210
210
211 $ hg debugstate --docket | grep unused
211 $ hg debugstate --docket | grep unused
212 number of unused bytes: 0
212 number of unused bytes: 0
213
213
214 #endif
214 #endif
215
215
216 Transaction compatibility
216 Transaction compatibility
217 -------------------------
217 -------------------------
218
218
219 The transaction preserves the dirstate.
219 The transaction preserves the dirstate.
220 We should make sure all of it (docket + data) is preserved
220 We should make sure all of it (docket + data) is preserved
221
221
222 #if dirstate-v2
222 #if dirstate-v2
223 $ hg commit -m 'bli'
223 $ hg commit -m 'bli'
224 #endif
224 #endif
225
225
226 $ hg update --quiet
226 $ hg update --quiet
227 $ hg revert --all --quiet
227 $ hg revert --all --quiet
228 $ rm -f a
228 $ rm -f a
229 $ echo foo > foo
229 $ echo foo > foo
230 $ hg add foo
230 $ hg add foo
231 $ hg commit -m foo
231 $ hg commit -m foo
232
232
233 #if dirstate-v2
233 #if dirstate-v2
234 $ uid=$(find_dirstate_uuid)
234 $ uid=$(find_dirstate_uuid)
235 $ touch bar
235 $ touch bar
236 $ while [ uid = $(find_dirstate_uuid) ]; do
236 $ while [ uid = $(find_dirstate_uuid) ]; do
237 > hg add bar;
237 > hg add bar;
238 > hg remove bar;
238 > hg remove bar;
239 > done;
239 > done;
240 $ rm bar
240 $ rm bar
241 #endif
241 #endif
242 $ hg rollback
242 $ hg rollback
243 repository tip rolled back to revision 1 (undo commit)
243 repository tip rolled back to revision 1 (undo commit)
244 working directory now based on revision 1
244 working directory now based on revision 1
245
245
246 #if dirstate-v1
247 $ hg status
246 $ hg status
248 A foo
247 A foo
249 #else
250 $ hg status
251 abort: $ENOENT$: '*/.hg/dirstate.*' (glob) (known-bad-output !)
252 [255]
253 #endif
General Comments 0
You need to be logged in to leave comments. Login now