##// END OF EJS Templates
dirstate: enforce `running_status` context for calling `status`...
marmoute -
r51044:03decaaf default
parent child Browse files
Show More
@@ -1,1778 +1,1778 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 timestamp,
34 timestamp,
35 )
35 )
36
36
37 from .interfaces import (
37 from .interfaces import (
38 dirstate as intdirstate,
38 dirstate as intdirstate,
39 util as interfaceutil,
39 util as interfaceutil,
40 )
40 )
41
41
42 parsers = policy.importmod('parsers')
42 parsers = policy.importmod('parsers')
43 rustmod = policy.importrust('dirstate')
43 rustmod = policy.importrust('dirstate')
44
44
45 HAS_FAST_DIRSTATE_V2 = rustmod is not None
45 HAS_FAST_DIRSTATE_V2 = rustmod is not None
46
46
47 propertycache = util.propertycache
47 propertycache = util.propertycache
48 filecache = scmutil.filecache
48 filecache = scmutil.filecache
49 _rangemask = dirstatemap.rangemask
49 _rangemask = dirstatemap.rangemask
50
50
51 DirstateItem = dirstatemap.DirstateItem
51 DirstateItem = dirstatemap.DirstateItem
52
52
53
53
54 class repocache(filecache):
54 class repocache(filecache):
55 """filecache for files in .hg/"""
55 """filecache for files in .hg/"""
56
56
57 def join(self, obj, fname):
57 def join(self, obj, fname):
58 return obj._opener.join(fname)
58 return obj._opener.join(fname)
59
59
60
60
61 class rootcache(filecache):
61 class rootcache(filecache):
62 """filecache for files in the repository root"""
62 """filecache for files in the repository root"""
63
63
64 def join(self, obj, fname):
64 def join(self, obj, fname):
65 return obj._join(fname)
65 return obj._join(fname)
66
66
67
67
68 def check_invalidated(func):
68 def check_invalidated(func):
69 """check we func is called a non-invalidated dirstate
69 """check we func is called a non-invalidated dirstate
70
70
71 The dirstate is in an "invalidated state" after an error occured during its
71 The dirstate is in an "invalidated state" after an error occured during its
72 modification and remains so until we exited the top level scope that framed
72 modification and remains so until we exited the top level scope that framed
73 such change.
73 such change.
74 """
74 """
75
75
76 def wrap(self, *args, **kwargs):
76 def wrap(self, *args, **kwargs):
77 if self._invalidated_context:
77 if self._invalidated_context:
78 msg = 'calling `%s` after the dirstate was invalidated'
78 msg = 'calling `%s` after the dirstate was invalidated'
79 msg %= func.__name__
79 msg %= func.__name__
80 raise error.ProgrammingError(msg)
80 raise error.ProgrammingError(msg)
81 return func(self, *args, **kwargs)
81 return func(self, *args, **kwargs)
82
82
83 return wrap
83 return wrap
84
84
85
85
86 def requires_changing_parents(func):
86 def requires_changing_parents(func):
87 def wrap(self, *args, **kwargs):
87 def wrap(self, *args, **kwargs):
88 if not self.is_changing_parents:
88 if not self.is_changing_parents:
89 msg = 'calling `%s` outside of a changing_parents context'
89 msg = 'calling `%s` outside of a changing_parents context'
90 msg %= func.__name__
90 msg %= func.__name__
91 raise error.ProgrammingError(msg)
91 raise error.ProgrammingError(msg)
92 return func(self, *args, **kwargs)
92 return func(self, *args, **kwargs)
93
93
94 return check_invalidated(wrap)
94 return check_invalidated(wrap)
95
95
96
96
97 def requires_changing_files(func):
97 def requires_changing_files(func):
98 def wrap(self, *args, **kwargs):
98 def wrap(self, *args, **kwargs):
99 if not self.is_changing_files:
99 if not self.is_changing_files:
100 msg = 'calling `%s` outside of a `changing_files`'
100 msg = 'calling `%s` outside of a `changing_files`'
101 msg %= func.__name__
101 msg %= func.__name__
102 raise error.ProgrammingError(msg)
102 raise error.ProgrammingError(msg)
103 return func(self, *args, **kwargs)
103 return func(self, *args, **kwargs)
104
104
105 return check_invalidated(wrap)
105 return check_invalidated(wrap)
106
106
107
107
108 def requires_changing_any(func):
108 def requires_changing_any(func):
109 def wrap(self, *args, **kwargs):
109 def wrap(self, *args, **kwargs):
110 if not self.is_changing_any:
110 if not self.is_changing_any:
111 msg = 'calling `%s` outside of a changing context'
111 msg = 'calling `%s` outside of a changing context'
112 msg %= func.__name__
112 msg %= func.__name__
113 raise error.ProgrammingError(msg)
113 raise error.ProgrammingError(msg)
114 return func(self, *args, **kwargs)
114 return func(self, *args, **kwargs)
115
115
116 return check_invalidated(wrap)
116 return check_invalidated(wrap)
117
117
118
118
119 def requires_not_changing_parents(func):
119 def requires_not_changing_parents(func):
120 def wrap(self, *args, **kwargs):
120 def wrap(self, *args, **kwargs):
121 if self.is_changing_parents:
121 if self.is_changing_parents:
122 msg = 'calling `%s` inside of a changing_parents context'
122 msg = 'calling `%s` inside of a changing_parents context'
123 msg %= func.__name__
123 msg %= func.__name__
124 raise error.ProgrammingError(msg)
124 raise error.ProgrammingError(msg)
125 return func(self, *args, **kwargs)
125 return func(self, *args, **kwargs)
126
126
127 return check_invalidated(wrap)
127 return check_invalidated(wrap)
128
128
129
129
130 CHANGE_TYPE_PARENTS = "parents"
130 CHANGE_TYPE_PARENTS = "parents"
131 CHANGE_TYPE_FILES = "files"
131 CHANGE_TYPE_FILES = "files"
132
132
133
133
134 @interfaceutil.implementer(intdirstate.idirstate)
134 @interfaceutil.implementer(intdirstate.idirstate)
135 class dirstate:
135 class dirstate:
136
136
137 # used by largefile to avoid overwritting transaction callbacK
137 # used by largefile to avoid overwritting transaction callbacK
138 _tr_key_suffix = b''
138 _tr_key_suffix = b''
139
139
140 def __init__(
140 def __init__(
141 self,
141 self,
142 opener,
142 opener,
143 ui,
143 ui,
144 root,
144 root,
145 validate,
145 validate,
146 sparsematchfn,
146 sparsematchfn,
147 nodeconstants,
147 nodeconstants,
148 use_dirstate_v2,
148 use_dirstate_v2,
149 use_tracked_hint=False,
149 use_tracked_hint=False,
150 ):
150 ):
151 """Create a new dirstate object.
151 """Create a new dirstate object.
152
152
153 opener is an open()-like callable that can be used to open the
153 opener is an open()-like callable that can be used to open the
154 dirstate file; root is the root of the directory tracked by
154 dirstate file; root is the root of the directory tracked by
155 the dirstate.
155 the dirstate.
156 """
156 """
157 self._use_dirstate_v2 = use_dirstate_v2
157 self._use_dirstate_v2 = use_dirstate_v2
158 self._use_tracked_hint = use_tracked_hint
158 self._use_tracked_hint = use_tracked_hint
159 self._nodeconstants = nodeconstants
159 self._nodeconstants = nodeconstants
160 self._opener = opener
160 self._opener = opener
161 self._validate = validate
161 self._validate = validate
162 self._root = root
162 self._root = root
163 # Either build a sparse-matcher or None if sparse is disabled
163 # Either build a sparse-matcher or None if sparse is disabled
164 self._sparsematchfn = sparsematchfn
164 self._sparsematchfn = sparsematchfn
165 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
165 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
166 # UNC path pointing to root share (issue4557)
166 # UNC path pointing to root share (issue4557)
167 self._rootdir = pathutil.normasprefix(root)
167 self._rootdir = pathutil.normasprefix(root)
168 # True is any internal state may be different
168 # True is any internal state may be different
169 self._dirty = False
169 self._dirty = False
170 # True if the set of tracked file may be different
170 # True if the set of tracked file may be different
171 self._dirty_tracked_set = False
171 self._dirty_tracked_set = False
172 self._ui = ui
172 self._ui = ui
173 self._filecache = {}
173 self._filecache = {}
174 # nesting level of `changing_parents` context
174 # nesting level of `changing_parents` context
175 self._changing_level = 0
175 self._changing_level = 0
176 # the change currently underway
176 # the change currently underway
177 self._change_type = None
177 self._change_type = None
178 # number of open _running_status context
178 # number of open _running_status context
179 self._running_status = 0
179 self._running_status = 0
180 # True if the current dirstate changing operations have been
180 # True if the current dirstate changing operations have been
181 # invalidated (used to make sure all nested contexts have been exited)
181 # invalidated (used to make sure all nested contexts have been exited)
182 self._invalidated_context = False
182 self._invalidated_context = False
183 self._attached_to_a_transaction = False
183 self._attached_to_a_transaction = False
184 self._filename = b'dirstate'
184 self._filename = b'dirstate'
185 self._filename_th = b'dirstate-tracked-hint'
185 self._filename_th = b'dirstate-tracked-hint'
186 self._pendingfilename = b'%s.pending' % self._filename
186 self._pendingfilename = b'%s.pending' % self._filename
187 self._plchangecallbacks = {}
187 self._plchangecallbacks = {}
188 self._origpl = None
188 self._origpl = None
189 self._mapcls = dirstatemap.dirstatemap
189 self._mapcls = dirstatemap.dirstatemap
190 # Access and cache cwd early, so we don't access it for the first time
190 # Access and cache cwd early, so we don't access it for the first time
191 # after a working-copy update caused it to not exist (accessing it then
191 # after a working-copy update caused it to not exist (accessing it then
192 # raises an exception).
192 # raises an exception).
193 self._cwd
193 self._cwd
194
194
195 def refresh(self):
195 def refresh(self):
196 if '_branch' in vars(self):
196 if '_branch' in vars(self):
197 del self._branch
197 del self._branch
198 if '_map' in vars(self) and self._map.may_need_refresh():
198 if '_map' in vars(self) and self._map.may_need_refresh():
199 self.invalidate()
199 self.invalidate()
200
200
201 def prefetch_parents(self):
201 def prefetch_parents(self):
202 """make sure the parents are loaded
202 """make sure the parents are loaded
203
203
204 Used to avoid a race condition.
204 Used to avoid a race condition.
205 """
205 """
206 self._pl
206 self._pl
207
207
208 @contextlib.contextmanager
208 @contextlib.contextmanager
209 @check_invalidated
209 @check_invalidated
210 def running_status(self, repo):
210 def running_status(self, repo):
211 """Wrap a status operation
211 """Wrap a status operation
212
212
213 This context is not mutally exclusive with the `changing_*` context. It
213 This context is not mutally exclusive with the `changing_*` context. It
214 also do not warrant for the `wlock` to be taken.
214 also do not warrant for the `wlock` to be taken.
215
215
216 If the wlock is taken, this context will behave in a simple way, and
216 If the wlock is taken, this context will behave in a simple way, and
217 ensure the data are scheduled for write when leaving the top level
217 ensure the data are scheduled for write when leaving the top level
218 context.
218 context.
219
219
220 If the lock is not taken, it will only warrant that the data are either
220 If the lock is not taken, it will only warrant that the data are either
221 committed (written) and rolled back (invalidated) when exiting the top
221 committed (written) and rolled back (invalidated) when exiting the top
222 level context. The write/invalidate action must be performed by the
222 level context. The write/invalidate action must be performed by the
223 wrapped code.
223 wrapped code.
224
224
225
225
226 The expected logic is:
226 The expected logic is:
227
227
228 A: read the dirstate
228 A: read the dirstate
229 B: run status
229 B: run status
230 This might make the dirstate dirty by updating cache,
230 This might make the dirstate dirty by updating cache,
231 especially in Rust.
231 especially in Rust.
232 C: do more "post status fixup if relevant
232 C: do more "post status fixup if relevant
233 D: try to take the w-lock (this will invalidate the changes if they were raced)
233 D: try to take the w-lock (this will invalidate the changes if they were raced)
234 E0: if dirstate changed on disk β†’ discard change (done by dirstate internal)
234 E0: if dirstate changed on disk β†’ discard change (done by dirstate internal)
235 E1: elif lock was acquired β†’ write the changes
235 E1: elif lock was acquired β†’ write the changes
236 E2: else β†’ discard the changes
236 E2: else β†’ discard the changes
237 """
237 """
238 has_lock = repo.currentwlock() is not None
238 has_lock = repo.currentwlock() is not None
239 is_changing = self.is_changing_any
239 is_changing = self.is_changing_any
240 tr = repo.currenttransaction()
240 tr = repo.currenttransaction()
241 has_tr = tr is not None
241 has_tr = tr is not None
242 nested = bool(self._running_status)
242 nested = bool(self._running_status)
243
243
244 first_and_alone = not (is_changing or has_tr or nested)
244 first_and_alone = not (is_changing or has_tr or nested)
245
245
246 # enforce no change happened outside of a proper context.
246 # enforce no change happened outside of a proper context.
247 if first_and_alone and self._dirty:
247 if first_and_alone and self._dirty:
248 has_tr = repo.currenttransaction() is not None
248 has_tr = repo.currenttransaction() is not None
249 if not has_tr and self._changing_level == 0 and self._dirty:
249 if not has_tr and self._changing_level == 0 and self._dirty:
250 msg = "entering a status context, but dirstate is already dirty"
250 msg = "entering a status context, but dirstate is already dirty"
251 raise error.ProgrammingError(msg)
251 raise error.ProgrammingError(msg)
252
252
253 should_write = has_lock and not (nested or is_changing)
253 should_write = has_lock and not (nested or is_changing)
254
254
255 self._running_status += 1
255 self._running_status += 1
256 try:
256 try:
257 yield
257 yield
258 except Exception:
258 except Exception:
259 self.invalidate()
259 self.invalidate()
260 raise
260 raise
261 finally:
261 finally:
262 self._running_status -= 1
262 self._running_status -= 1
263 if self._invalidated_context:
263 if self._invalidated_context:
264 should_write = False
264 should_write = False
265 self.invalidate()
265 self.invalidate()
266
266
267 if should_write:
267 if should_write:
268 assert repo.currenttransaction() is tr
268 assert repo.currenttransaction() is tr
269 self.write(tr)
269 self.write(tr)
270 elif not has_lock:
270 elif not has_lock:
271 if self._dirty:
271 if self._dirty:
272 msg = b'dirstate dirty while exiting an isolated status context'
272 msg = b'dirstate dirty while exiting an isolated status context'
273 repo.ui.develwarn(msg)
273 repo.ui.develwarn(msg)
274 self.invalidate()
274 self.invalidate()
275
275
276 @contextlib.contextmanager
276 @contextlib.contextmanager
277 @check_invalidated
277 @check_invalidated
278 def _changing(self, repo, change_type):
278 def _changing(self, repo, change_type):
279 if repo.currentwlock() is None:
279 if repo.currentwlock() is None:
280 msg = b"trying to change the dirstate without holding the wlock"
280 msg = b"trying to change the dirstate without holding the wlock"
281 raise error.ProgrammingError(msg)
281 raise error.ProgrammingError(msg)
282
282
283 has_tr = repo.currenttransaction() is not None
283 has_tr = repo.currenttransaction() is not None
284 if not has_tr and self._changing_level == 0 and self._dirty:
284 if not has_tr and self._changing_level == 0 and self._dirty:
285 msg = "entering a changing context, but dirstate is already dirty"
285 msg = "entering a changing context, but dirstate is already dirty"
286 raise error.ProgrammingError(msg)
286 raise error.ProgrammingError(msg)
287
287
288 assert self._changing_level >= 0
288 assert self._changing_level >= 0
289 # different type of change are mutually exclusive
289 # different type of change are mutually exclusive
290 if self._change_type is None:
290 if self._change_type is None:
291 assert self._changing_level == 0
291 assert self._changing_level == 0
292 self._change_type = change_type
292 self._change_type = change_type
293 elif self._change_type != change_type:
293 elif self._change_type != change_type:
294 msg = (
294 msg = (
295 'trying to open "%s" dirstate-changing context while a "%s" is'
295 'trying to open "%s" dirstate-changing context while a "%s" is'
296 ' already open'
296 ' already open'
297 )
297 )
298 msg %= (change_type, self._change_type)
298 msg %= (change_type, self._change_type)
299 raise error.ProgrammingError(msg)
299 raise error.ProgrammingError(msg)
300 should_write = False
300 should_write = False
301 self._changing_level += 1
301 self._changing_level += 1
302 try:
302 try:
303 yield
303 yield
304 except: # re-raises
304 except: # re-raises
305 self.invalidate() # this will set `_invalidated_context`
305 self.invalidate() # this will set `_invalidated_context`
306 raise
306 raise
307 finally:
307 finally:
308 assert self._changing_level > 0
308 assert self._changing_level > 0
309 self._changing_level -= 1
309 self._changing_level -= 1
310 # If the dirstate is being invalidated, call invalidate again.
310 # If the dirstate is being invalidated, call invalidate again.
311 # This will throw away anything added by a upper context and
311 # This will throw away anything added by a upper context and
312 # reset the `_invalidated_context` flag when relevant
312 # reset the `_invalidated_context` flag when relevant
313 if self._changing_level <= 0:
313 if self._changing_level <= 0:
314 self._change_type = None
314 self._change_type = None
315 assert self._changing_level == 0
315 assert self._changing_level == 0
316 if self._invalidated_context:
316 if self._invalidated_context:
317 # make sure we invalidate anything an upper context might
317 # make sure we invalidate anything an upper context might
318 # have changed.
318 # have changed.
319 self.invalidate()
319 self.invalidate()
320 else:
320 else:
321 should_write = self._changing_level <= 0
321 should_write = self._changing_level <= 0
322 tr = repo.currenttransaction()
322 tr = repo.currenttransaction()
323 if has_tr != (tr is not None):
323 if has_tr != (tr is not None):
324 if has_tr:
324 if has_tr:
325 m = "transaction vanished while changing dirstate"
325 m = "transaction vanished while changing dirstate"
326 else:
326 else:
327 m = "transaction appeared while changing dirstate"
327 m = "transaction appeared while changing dirstate"
328 raise error.ProgrammingError(m)
328 raise error.ProgrammingError(m)
329 if should_write:
329 if should_write:
330 self.write(tr)
330 self.write(tr)
331
331
332 @contextlib.contextmanager
332 @contextlib.contextmanager
333 def changing_parents(self, repo):
333 def changing_parents(self, repo):
334 with self._changing(repo, CHANGE_TYPE_PARENTS) as c:
334 with self._changing(repo, CHANGE_TYPE_PARENTS) as c:
335 yield c
335 yield c
336
336
337 @contextlib.contextmanager
337 @contextlib.contextmanager
338 def changing_files(self, repo):
338 def changing_files(self, repo):
339 with self._changing(repo, CHANGE_TYPE_FILES) as c:
339 with self._changing(repo, CHANGE_TYPE_FILES) as c:
340 yield c
340 yield c
341
341
342 # here to help migration to the new code
342 # here to help migration to the new code
343 def parentchange(self):
343 def parentchange(self):
344 msg = (
344 msg = (
345 "Mercurial 6.4 and later requires call to "
345 "Mercurial 6.4 and later requires call to "
346 "`dirstate.changing_parents(repo)`"
346 "`dirstate.changing_parents(repo)`"
347 )
347 )
348 raise error.ProgrammingError(msg)
348 raise error.ProgrammingError(msg)
349
349
350 @property
350 @property
351 def is_changing_any(self):
351 def is_changing_any(self):
352 """Returns true if the dirstate is in the middle of a set of changes.
352 """Returns true if the dirstate is in the middle of a set of changes.
353
353
354 This returns True for any kind of change.
354 This returns True for any kind of change.
355 """
355 """
356 return self._changing_level > 0
356 return self._changing_level > 0
357
357
358 def pendingparentchange(self):
358 def pendingparentchange(self):
359 return self.is_changing_parent()
359 return self.is_changing_parent()
360
360
361 def is_changing_parent(self):
361 def is_changing_parent(self):
362 """Returns true if the dirstate is in the middle of a set of changes
362 """Returns true if the dirstate is in the middle of a set of changes
363 that modify the dirstate parent.
363 that modify the dirstate parent.
364 """
364 """
365 self._ui.deprecwarn(b"dirstate.is_changing_parents", b"6.5")
365 self._ui.deprecwarn(b"dirstate.is_changing_parents", b"6.5")
366 return self.is_changing_parents
366 return self.is_changing_parents
367
367
368 @property
368 @property
369 def is_changing_parents(self):
369 def is_changing_parents(self):
370 """Returns true if the dirstate is in the middle of a set of changes
370 """Returns true if the dirstate is in the middle of a set of changes
371 that modify the dirstate parent.
371 that modify the dirstate parent.
372 """
372 """
373 if self._changing_level <= 0:
373 if self._changing_level <= 0:
374 return False
374 return False
375 return self._change_type == CHANGE_TYPE_PARENTS
375 return self._change_type == CHANGE_TYPE_PARENTS
376
376
377 @property
377 @property
378 def is_changing_files(self):
378 def is_changing_files(self):
379 """Returns true if the dirstate is in the middle of a set of changes
379 """Returns true if the dirstate is in the middle of a set of changes
380 that modify the files tracked or their sources.
380 that modify the files tracked or their sources.
381 """
381 """
382 if self._changing_level <= 0:
382 if self._changing_level <= 0:
383 return False
383 return False
384 return self._change_type == CHANGE_TYPE_FILES
384 return self._change_type == CHANGE_TYPE_FILES
385
385
386 @propertycache
386 @propertycache
387 def _map(self):
387 def _map(self):
388 """Return the dirstate contents (see documentation for dirstatemap)."""
388 """Return the dirstate contents (see documentation for dirstatemap)."""
389 return self._mapcls(
389 return self._mapcls(
390 self._ui,
390 self._ui,
391 self._opener,
391 self._opener,
392 self._root,
392 self._root,
393 self._nodeconstants,
393 self._nodeconstants,
394 self._use_dirstate_v2,
394 self._use_dirstate_v2,
395 )
395 )
396
396
397 @property
397 @property
398 def _sparsematcher(self):
398 def _sparsematcher(self):
399 """The matcher for the sparse checkout.
399 """The matcher for the sparse checkout.
400
400
401 The working directory may not include every file from a manifest. The
401 The working directory may not include every file from a manifest. The
402 matcher obtained by this property will match a path if it is to be
402 matcher obtained by this property will match a path if it is to be
403 included in the working directory.
403 included in the working directory.
404
404
405 When sparse if disabled, return None.
405 When sparse if disabled, return None.
406 """
406 """
407 if self._sparsematchfn is None:
407 if self._sparsematchfn is None:
408 return None
408 return None
409 # TODO there is potential to cache this property. For now, the matcher
409 # TODO there is potential to cache this property. For now, the matcher
410 # is resolved on every access. (But the called function does use a
410 # is resolved on every access. (But the called function does use a
411 # cache to keep the lookup fast.)
411 # cache to keep the lookup fast.)
412 return self._sparsematchfn()
412 return self._sparsematchfn()
413
413
414 @repocache(b'branch')
414 @repocache(b'branch')
415 def _branch(self):
415 def _branch(self):
416 try:
416 try:
417 return self._opener.read(b"branch").strip() or b"default"
417 return self._opener.read(b"branch").strip() or b"default"
418 except FileNotFoundError:
418 except FileNotFoundError:
419 return b"default"
419 return b"default"
420
420
421 @property
421 @property
422 def _pl(self):
422 def _pl(self):
423 return self._map.parents()
423 return self._map.parents()
424
424
425 def hasdir(self, d):
425 def hasdir(self, d):
426 return self._map.hastrackeddir(d)
426 return self._map.hastrackeddir(d)
427
427
428 @rootcache(b'.hgignore')
428 @rootcache(b'.hgignore')
429 def _ignore(self):
429 def _ignore(self):
430 files = self._ignorefiles()
430 files = self._ignorefiles()
431 if not files:
431 if not files:
432 return matchmod.never()
432 return matchmod.never()
433
433
434 pats = [b'include:%s' % f for f in files]
434 pats = [b'include:%s' % f for f in files]
435 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
435 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
436
436
437 @propertycache
437 @propertycache
438 def _slash(self):
438 def _slash(self):
439 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
439 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
440
440
441 @propertycache
441 @propertycache
442 def _checklink(self):
442 def _checklink(self):
443 return util.checklink(self._root)
443 return util.checklink(self._root)
444
444
445 @propertycache
445 @propertycache
446 def _checkexec(self):
446 def _checkexec(self):
447 return bool(util.checkexec(self._root))
447 return bool(util.checkexec(self._root))
448
448
449 @propertycache
449 @propertycache
450 def _checkcase(self):
450 def _checkcase(self):
451 return not util.fscasesensitive(self._join(b'.hg'))
451 return not util.fscasesensitive(self._join(b'.hg'))
452
452
453 def _join(self, f):
453 def _join(self, f):
454 # much faster than os.path.join()
454 # much faster than os.path.join()
455 # it's safe because f is always a relative path
455 # it's safe because f is always a relative path
456 return self._rootdir + f
456 return self._rootdir + f
457
457
458 def flagfunc(self, buildfallback):
458 def flagfunc(self, buildfallback):
459 """build a callable that returns flags associated with a filename
459 """build a callable that returns flags associated with a filename
460
460
461 The information is extracted from three possible layers:
461 The information is extracted from three possible layers:
462 1. the file system if it supports the information
462 1. the file system if it supports the information
463 2. the "fallback" information stored in the dirstate if any
463 2. the "fallback" information stored in the dirstate if any
464 3. a more expensive mechanism inferring the flags from the parents.
464 3. a more expensive mechanism inferring the flags from the parents.
465 """
465 """
466
466
467 # small hack to cache the result of buildfallback()
467 # small hack to cache the result of buildfallback()
468 fallback_func = []
468 fallback_func = []
469
469
470 def get_flags(x):
470 def get_flags(x):
471 entry = None
471 entry = None
472 fallback_value = None
472 fallback_value = None
473 try:
473 try:
474 st = os.lstat(self._join(x))
474 st = os.lstat(self._join(x))
475 except OSError:
475 except OSError:
476 return b''
476 return b''
477
477
478 if self._checklink:
478 if self._checklink:
479 if util.statislink(st):
479 if util.statislink(st):
480 return b'l'
480 return b'l'
481 else:
481 else:
482 entry = self.get_entry(x)
482 entry = self.get_entry(x)
483 if entry.has_fallback_symlink:
483 if entry.has_fallback_symlink:
484 if entry.fallback_symlink:
484 if entry.fallback_symlink:
485 return b'l'
485 return b'l'
486 else:
486 else:
487 if not fallback_func:
487 if not fallback_func:
488 fallback_func.append(buildfallback())
488 fallback_func.append(buildfallback())
489 fallback_value = fallback_func[0](x)
489 fallback_value = fallback_func[0](x)
490 if b'l' in fallback_value:
490 if b'l' in fallback_value:
491 return b'l'
491 return b'l'
492
492
493 if self._checkexec:
493 if self._checkexec:
494 if util.statisexec(st):
494 if util.statisexec(st):
495 return b'x'
495 return b'x'
496 else:
496 else:
497 if entry is None:
497 if entry is None:
498 entry = self.get_entry(x)
498 entry = self.get_entry(x)
499 if entry.has_fallback_exec:
499 if entry.has_fallback_exec:
500 if entry.fallback_exec:
500 if entry.fallback_exec:
501 return b'x'
501 return b'x'
502 else:
502 else:
503 if fallback_value is None:
503 if fallback_value is None:
504 if not fallback_func:
504 if not fallback_func:
505 fallback_func.append(buildfallback())
505 fallback_func.append(buildfallback())
506 fallback_value = fallback_func[0](x)
506 fallback_value = fallback_func[0](x)
507 if b'x' in fallback_value:
507 if b'x' in fallback_value:
508 return b'x'
508 return b'x'
509 return b''
509 return b''
510
510
511 return get_flags
511 return get_flags
512
512
513 @propertycache
513 @propertycache
514 def _cwd(self):
514 def _cwd(self):
515 # internal config: ui.forcecwd
515 # internal config: ui.forcecwd
516 forcecwd = self._ui.config(b'ui', b'forcecwd')
516 forcecwd = self._ui.config(b'ui', b'forcecwd')
517 if forcecwd:
517 if forcecwd:
518 return forcecwd
518 return forcecwd
519 return encoding.getcwd()
519 return encoding.getcwd()
520
520
521 def getcwd(self):
521 def getcwd(self):
522 """Return the path from which a canonical path is calculated.
522 """Return the path from which a canonical path is calculated.
523
523
524 This path should be used to resolve file patterns or to convert
524 This path should be used to resolve file patterns or to convert
525 canonical paths back to file paths for display. It shouldn't be
525 canonical paths back to file paths for display. It shouldn't be
526 used to get real file paths. Use vfs functions instead.
526 used to get real file paths. Use vfs functions instead.
527 """
527 """
528 cwd = self._cwd
528 cwd = self._cwd
529 if cwd == self._root:
529 if cwd == self._root:
530 return b''
530 return b''
531 # self._root ends with a path separator if self._root is '/' or 'C:\'
531 # self._root ends with a path separator if self._root is '/' or 'C:\'
532 rootsep = self._root
532 rootsep = self._root
533 if not util.endswithsep(rootsep):
533 if not util.endswithsep(rootsep):
534 rootsep += pycompat.ossep
534 rootsep += pycompat.ossep
535 if cwd.startswith(rootsep):
535 if cwd.startswith(rootsep):
536 return cwd[len(rootsep) :]
536 return cwd[len(rootsep) :]
537 else:
537 else:
538 # we're outside the repo. return an absolute path.
538 # we're outside the repo. return an absolute path.
539 return cwd
539 return cwd
540
540
541 def pathto(self, f, cwd=None):
541 def pathto(self, f, cwd=None):
542 if cwd is None:
542 if cwd is None:
543 cwd = self.getcwd()
543 cwd = self.getcwd()
544 path = util.pathto(self._root, cwd, f)
544 path = util.pathto(self._root, cwd, f)
545 if self._slash:
545 if self._slash:
546 return util.pconvert(path)
546 return util.pconvert(path)
547 return path
547 return path
548
548
549 def get_entry(self, path):
549 def get_entry(self, path):
550 """return a DirstateItem for the associated path"""
550 """return a DirstateItem for the associated path"""
551 entry = self._map.get(path)
551 entry = self._map.get(path)
552 if entry is None:
552 if entry is None:
553 return DirstateItem()
553 return DirstateItem()
554 return entry
554 return entry
555
555
556 def __contains__(self, key):
556 def __contains__(self, key):
557 return key in self._map
557 return key in self._map
558
558
559 def __iter__(self):
559 def __iter__(self):
560 return iter(sorted(self._map))
560 return iter(sorted(self._map))
561
561
562 def items(self):
562 def items(self):
563 return self._map.items()
563 return self._map.items()
564
564
565 iteritems = items
565 iteritems = items
566
566
567 def parents(self):
567 def parents(self):
568 return [self._validate(p) for p in self._pl]
568 return [self._validate(p) for p in self._pl]
569
569
570 def p1(self):
570 def p1(self):
571 return self._validate(self._pl[0])
571 return self._validate(self._pl[0])
572
572
573 def p2(self):
573 def p2(self):
574 return self._validate(self._pl[1])
574 return self._validate(self._pl[1])
575
575
576 @property
576 @property
577 def in_merge(self):
577 def in_merge(self):
578 """True if a merge is in progress"""
578 """True if a merge is in progress"""
579 return self._pl[1] != self._nodeconstants.nullid
579 return self._pl[1] != self._nodeconstants.nullid
580
580
581 def branch(self):
581 def branch(self):
582 return encoding.tolocal(self._branch)
582 return encoding.tolocal(self._branch)
583
583
584 @requires_changing_parents
584 @requires_changing_parents
585 def setparents(self, p1, p2=None):
585 def setparents(self, p1, p2=None):
586 """Set dirstate parents to p1 and p2.
586 """Set dirstate parents to p1 and p2.
587
587
588 When moving from two parents to one, "merged" entries a
588 When moving from two parents to one, "merged" entries a
589 adjusted to normal and previous copy records discarded and
589 adjusted to normal and previous copy records discarded and
590 returned by the call.
590 returned by the call.
591
591
592 See localrepo.setparents()
592 See localrepo.setparents()
593 """
593 """
594 if p2 is None:
594 if p2 is None:
595 p2 = self._nodeconstants.nullid
595 p2 = self._nodeconstants.nullid
596 if self._changing_level == 0:
596 if self._changing_level == 0:
597 raise ValueError(
597 raise ValueError(
598 b"cannot set dirstate parent outside of "
598 b"cannot set dirstate parent outside of "
599 b"dirstate.changing_parents context manager"
599 b"dirstate.changing_parents context manager"
600 )
600 )
601
601
602 self._dirty = True
602 self._dirty = True
603 oldp2 = self._pl[1]
603 oldp2 = self._pl[1]
604 if self._origpl is None:
604 if self._origpl is None:
605 self._origpl = self._pl
605 self._origpl = self._pl
606 nullid = self._nodeconstants.nullid
606 nullid = self._nodeconstants.nullid
607 # True if we need to fold p2 related state back to a linear case
607 # True if we need to fold p2 related state back to a linear case
608 fold_p2 = oldp2 != nullid and p2 == nullid
608 fold_p2 = oldp2 != nullid and p2 == nullid
609 return self._map.setparents(p1, p2, fold_p2=fold_p2)
609 return self._map.setparents(p1, p2, fold_p2=fold_p2)
610
610
611 def setbranch(self, branch):
611 def setbranch(self, branch):
612 self.__class__._branch.set(self, encoding.fromlocal(branch))
612 self.__class__._branch.set(self, encoding.fromlocal(branch))
613 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
613 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
614 try:
614 try:
615 f.write(self._branch + b'\n')
615 f.write(self._branch + b'\n')
616 f.close()
616 f.close()
617
617
618 # make sure filecache has the correct stat info for _branch after
618 # make sure filecache has the correct stat info for _branch after
619 # replacing the underlying file
619 # replacing the underlying file
620 ce = self._filecache[b'_branch']
620 ce = self._filecache[b'_branch']
621 if ce:
621 if ce:
622 ce.refresh()
622 ce.refresh()
623 except: # re-raises
623 except: # re-raises
624 f.discard()
624 f.discard()
625 raise
625 raise
626
626
627 def invalidate(self):
627 def invalidate(self):
628 """Causes the next access to reread the dirstate.
628 """Causes the next access to reread the dirstate.
629
629
630 This is different from localrepo.invalidatedirstate() because it always
630 This is different from localrepo.invalidatedirstate() because it always
631 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
631 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
632 check whether the dirstate has changed before rereading it."""
632 check whether the dirstate has changed before rereading it."""
633
633
634 for a in ("_map", "_branch", "_ignore"):
634 for a in ("_map", "_branch", "_ignore"):
635 if a in self.__dict__:
635 if a in self.__dict__:
636 delattr(self, a)
636 delattr(self, a)
637 self._dirty = False
637 self._dirty = False
638 self._dirty_tracked_set = False
638 self._dirty_tracked_set = False
639 self._invalidated_context = bool(
639 self._invalidated_context = bool(
640 self._changing_level > 0
640 self._changing_level > 0
641 or self._attached_to_a_transaction
641 or self._attached_to_a_transaction
642 or self._running_status
642 or self._running_status
643 )
643 )
644 self._origpl = None
644 self._origpl = None
645
645
646 @requires_changing_any
646 @requires_changing_any
647 def copy(self, source, dest):
647 def copy(self, source, dest):
648 """Mark dest as a copy of source. Unmark dest if source is None."""
648 """Mark dest as a copy of source. Unmark dest if source is None."""
649 if source == dest:
649 if source == dest:
650 return
650 return
651 self._dirty = True
651 self._dirty = True
652 if source is not None:
652 if source is not None:
653 self._check_sparse(source)
653 self._check_sparse(source)
654 self._map.copymap[dest] = source
654 self._map.copymap[dest] = source
655 else:
655 else:
656 self._map.copymap.pop(dest, None)
656 self._map.copymap.pop(dest, None)
657
657
658 def copied(self, file):
658 def copied(self, file):
659 return self._map.copymap.get(file, None)
659 return self._map.copymap.get(file, None)
660
660
661 def copies(self):
661 def copies(self):
662 return self._map.copymap
662 return self._map.copymap
663
663
664 @requires_changing_files
664 @requires_changing_files
665 def set_tracked(self, filename, reset_copy=False):
665 def set_tracked(self, filename, reset_copy=False):
666 """a "public" method for generic code to mark a file as tracked
666 """a "public" method for generic code to mark a file as tracked
667
667
668 This function is to be called outside of "update/merge" case. For
668 This function is to be called outside of "update/merge" case. For
669 example by a command like `hg add X`.
669 example by a command like `hg add X`.
670
670
671 if reset_copy is set, any existing copy information will be dropped.
671 if reset_copy is set, any existing copy information will be dropped.
672
672
673 return True the file was previously untracked, False otherwise.
673 return True the file was previously untracked, False otherwise.
674 """
674 """
675 self._dirty = True
675 self._dirty = True
676 entry = self._map.get(filename)
676 entry = self._map.get(filename)
677 if entry is None or not entry.tracked:
677 if entry is None or not entry.tracked:
678 self._check_new_tracked_filename(filename)
678 self._check_new_tracked_filename(filename)
679 pre_tracked = self._map.set_tracked(filename)
679 pre_tracked = self._map.set_tracked(filename)
680 if reset_copy:
680 if reset_copy:
681 self._map.copymap.pop(filename, None)
681 self._map.copymap.pop(filename, None)
682 if pre_tracked:
682 if pre_tracked:
683 self._dirty_tracked_set = True
683 self._dirty_tracked_set = True
684 return pre_tracked
684 return pre_tracked
685
685
686 @requires_changing_files
686 @requires_changing_files
687 def set_untracked(self, filename):
687 def set_untracked(self, filename):
688 """a "public" method for generic code to mark a file as untracked
688 """a "public" method for generic code to mark a file as untracked
689
689
690 This function is to be called outside of "update/merge" case. For
690 This function is to be called outside of "update/merge" case. For
691 example by a command like `hg remove X`.
691 example by a command like `hg remove X`.
692
692
693 return True the file was previously tracked, False otherwise.
693 return True the file was previously tracked, False otherwise.
694 """
694 """
695 ret = self._map.set_untracked(filename)
695 ret = self._map.set_untracked(filename)
696 if ret:
696 if ret:
697 self._dirty = True
697 self._dirty = True
698 self._dirty_tracked_set = True
698 self._dirty_tracked_set = True
699 return ret
699 return ret
700
700
701 @requires_not_changing_parents
701 @requires_not_changing_parents
702 def set_clean(self, filename, parentfiledata):
702 def set_clean(self, filename, parentfiledata):
703 """record that the current state of the file on disk is known to be clean"""
703 """record that the current state of the file on disk is known to be clean"""
704 self._dirty = True
704 self._dirty = True
705 if not self._map[filename].tracked:
705 if not self._map[filename].tracked:
706 self._check_new_tracked_filename(filename)
706 self._check_new_tracked_filename(filename)
707 (mode, size, mtime) = parentfiledata
707 (mode, size, mtime) = parentfiledata
708 self._map.set_clean(filename, mode, size, mtime)
708 self._map.set_clean(filename, mode, size, mtime)
709
709
710 @requires_not_changing_parents
710 @requires_not_changing_parents
711 def set_possibly_dirty(self, filename):
711 def set_possibly_dirty(self, filename):
712 """record that the current state of the file on disk is unknown"""
712 """record that the current state of the file on disk is unknown"""
713 self._dirty = True
713 self._dirty = True
714 self._map.set_possibly_dirty(filename)
714 self._map.set_possibly_dirty(filename)
715
715
716 @requires_changing_parents
716 @requires_changing_parents
717 def update_file_p1(
717 def update_file_p1(
718 self,
718 self,
719 filename,
719 filename,
720 p1_tracked,
720 p1_tracked,
721 ):
721 ):
722 """Set a file as tracked in the parent (or not)
722 """Set a file as tracked in the parent (or not)
723
723
724 This is to be called when adjust the dirstate to a new parent after an history
724 This is to be called when adjust the dirstate to a new parent after an history
725 rewriting operation.
725 rewriting operation.
726
726
727 It should not be called during a merge (p2 != nullid) and only within
727 It should not be called during a merge (p2 != nullid) and only within
728 a `with dirstate.changing_parents(repo):` context.
728 a `with dirstate.changing_parents(repo):` context.
729 """
729 """
730 if self.in_merge:
730 if self.in_merge:
731 msg = b'update_file_reference should not be called when merging'
731 msg = b'update_file_reference should not be called when merging'
732 raise error.ProgrammingError(msg)
732 raise error.ProgrammingError(msg)
733 entry = self._map.get(filename)
733 entry = self._map.get(filename)
734 if entry is None:
734 if entry is None:
735 wc_tracked = False
735 wc_tracked = False
736 else:
736 else:
737 wc_tracked = entry.tracked
737 wc_tracked = entry.tracked
738 if not (p1_tracked or wc_tracked):
738 if not (p1_tracked or wc_tracked):
739 # the file is no longer relevant to anyone
739 # the file is no longer relevant to anyone
740 if self._map.get(filename) is not None:
740 if self._map.get(filename) is not None:
741 self._map.reset_state(filename)
741 self._map.reset_state(filename)
742 self._dirty = True
742 self._dirty = True
743 elif (not p1_tracked) and wc_tracked:
743 elif (not p1_tracked) and wc_tracked:
744 if entry is not None and entry.added:
744 if entry is not None and entry.added:
745 return # avoid dropping copy information (maybe?)
745 return # avoid dropping copy information (maybe?)
746
746
747 self._map.reset_state(
747 self._map.reset_state(
748 filename,
748 filename,
749 wc_tracked,
749 wc_tracked,
750 p1_tracked,
750 p1_tracked,
751 # the underlying reference might have changed, we will have to
751 # the underlying reference might have changed, we will have to
752 # check it.
752 # check it.
753 has_meaningful_mtime=False,
753 has_meaningful_mtime=False,
754 )
754 )
755
755
756 @requires_changing_parents
756 @requires_changing_parents
757 def update_file(
757 def update_file(
758 self,
758 self,
759 filename,
759 filename,
760 wc_tracked,
760 wc_tracked,
761 p1_tracked,
761 p1_tracked,
762 p2_info=False,
762 p2_info=False,
763 possibly_dirty=False,
763 possibly_dirty=False,
764 parentfiledata=None,
764 parentfiledata=None,
765 ):
765 ):
766 """update the information about a file in the dirstate
766 """update the information about a file in the dirstate
767
767
768 This is to be called when the direstates parent changes to keep track
768 This is to be called when the direstates parent changes to keep track
769 of what is the file situation in regards to the working copy and its parent.
769 of what is the file situation in regards to the working copy and its parent.
770
770
771 This function must be called within a `dirstate.changing_parents` context.
771 This function must be called within a `dirstate.changing_parents` context.
772
772
773 note: the API is at an early stage and we might need to adjust it
773 note: the API is at an early stage and we might need to adjust it
774 depending of what information ends up being relevant and useful to
774 depending of what information ends up being relevant and useful to
775 other processing.
775 other processing.
776 """
776 """
777 self._update_file(
777 self._update_file(
778 filename=filename,
778 filename=filename,
779 wc_tracked=wc_tracked,
779 wc_tracked=wc_tracked,
780 p1_tracked=p1_tracked,
780 p1_tracked=p1_tracked,
781 p2_info=p2_info,
781 p2_info=p2_info,
782 possibly_dirty=possibly_dirty,
782 possibly_dirty=possibly_dirty,
783 parentfiledata=parentfiledata,
783 parentfiledata=parentfiledata,
784 )
784 )
785
785
786 # XXX since this make the dirstate dirty, we should enforce that it is done
786 # XXX since this make the dirstate dirty, we should enforce that it is done
787 # withing an appropriate change-context that scope the change and ensure it
787 # withing an appropriate change-context that scope the change and ensure it
788 # eventually get written on disk (or rolled back)
788 # eventually get written on disk (or rolled back)
789 def hacky_extension_update_file(self, *args, **kwargs):
789 def hacky_extension_update_file(self, *args, **kwargs):
790 """NEVER USE THIS, YOU DO NOT NEED IT
790 """NEVER USE THIS, YOU DO NOT NEED IT
791
791
792 This function is a variant of "update_file" to be called by a small set
792 This function is a variant of "update_file" to be called by a small set
793 of extensions, it also adjust the internal state of file, but can be
793 of extensions, it also adjust the internal state of file, but can be
794 called outside an `changing_parents` context.
794 called outside an `changing_parents` context.
795
795
796 A very small number of extension meddle with the working copy content
796 A very small number of extension meddle with the working copy content
797 in a way that requires to adjust the dirstate accordingly. At the time
797 in a way that requires to adjust the dirstate accordingly. At the time
798 this command is written they are :
798 this command is written they are :
799 - keyword,
799 - keyword,
800 - largefile,
800 - largefile,
801 PLEASE DO NOT GROW THIS LIST ANY FURTHER.
801 PLEASE DO NOT GROW THIS LIST ANY FURTHER.
802
802
803 This function could probably be replaced by more semantic one (like
803 This function could probably be replaced by more semantic one (like
804 "adjust expected size" or "always revalidate file content", etc)
804 "adjust expected size" or "always revalidate file content", etc)
805 however at the time where this is writen, this is too much of a detour
805 however at the time where this is writen, this is too much of a detour
806 to be considered.
806 to be considered.
807 """
807 """
808 self._update_file(
808 self._update_file(
809 *args,
809 *args,
810 **kwargs,
810 **kwargs,
811 )
811 )
812
812
813 def _update_file(
813 def _update_file(
814 self,
814 self,
815 filename,
815 filename,
816 wc_tracked,
816 wc_tracked,
817 p1_tracked,
817 p1_tracked,
818 p2_info=False,
818 p2_info=False,
819 possibly_dirty=False,
819 possibly_dirty=False,
820 parentfiledata=None,
820 parentfiledata=None,
821 ):
821 ):
822
822
823 # note: I do not think we need to double check name clash here since we
823 # note: I do not think we need to double check name clash here since we
824 # are in a update/merge case that should already have taken care of
824 # are in a update/merge case that should already have taken care of
825 # this. The test agrees
825 # this. The test agrees
826
826
827 self._dirty = True
827 self._dirty = True
828 old_entry = self._map.get(filename)
828 old_entry = self._map.get(filename)
829 if old_entry is None:
829 if old_entry is None:
830 prev_tracked = False
830 prev_tracked = False
831 else:
831 else:
832 prev_tracked = old_entry.tracked
832 prev_tracked = old_entry.tracked
833 if prev_tracked != wc_tracked:
833 if prev_tracked != wc_tracked:
834 self._dirty_tracked_set = True
834 self._dirty_tracked_set = True
835
835
836 self._map.reset_state(
836 self._map.reset_state(
837 filename,
837 filename,
838 wc_tracked,
838 wc_tracked,
839 p1_tracked,
839 p1_tracked,
840 p2_info=p2_info,
840 p2_info=p2_info,
841 has_meaningful_mtime=not possibly_dirty,
841 has_meaningful_mtime=not possibly_dirty,
842 parentfiledata=parentfiledata,
842 parentfiledata=parentfiledata,
843 )
843 )
844
844
845 def _check_new_tracked_filename(self, filename):
845 def _check_new_tracked_filename(self, filename):
846 scmutil.checkfilename(filename)
846 scmutil.checkfilename(filename)
847 if self._map.hastrackeddir(filename):
847 if self._map.hastrackeddir(filename):
848 msg = _(b'directory %r already in dirstate')
848 msg = _(b'directory %r already in dirstate')
849 msg %= pycompat.bytestr(filename)
849 msg %= pycompat.bytestr(filename)
850 raise error.Abort(msg)
850 raise error.Abort(msg)
851 # shadows
851 # shadows
852 for d in pathutil.finddirs(filename):
852 for d in pathutil.finddirs(filename):
853 if self._map.hastrackeddir(d):
853 if self._map.hastrackeddir(d):
854 break
854 break
855 entry = self._map.get(d)
855 entry = self._map.get(d)
856 if entry is not None and not entry.removed:
856 if entry is not None and not entry.removed:
857 msg = _(b'file %r in dirstate clashes with %r')
857 msg = _(b'file %r in dirstate clashes with %r')
858 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
858 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
859 raise error.Abort(msg)
859 raise error.Abort(msg)
860 self._check_sparse(filename)
860 self._check_sparse(filename)
861
861
862 def _check_sparse(self, filename):
862 def _check_sparse(self, filename):
863 """Check that a filename is inside the sparse profile"""
863 """Check that a filename is inside the sparse profile"""
864 sparsematch = self._sparsematcher
864 sparsematch = self._sparsematcher
865 if sparsematch is not None and not sparsematch.always():
865 if sparsematch is not None and not sparsematch.always():
866 if not sparsematch(filename):
866 if not sparsematch(filename):
867 msg = _(b"cannot add '%s' - it is outside the sparse checkout")
867 msg = _(b"cannot add '%s' - it is outside the sparse checkout")
868 hint = _(
868 hint = _(
869 b'include file with `hg debugsparse --include <pattern>` or use '
869 b'include file with `hg debugsparse --include <pattern>` or use '
870 b'`hg add -s <file>` to include file directory while adding'
870 b'`hg add -s <file>` to include file directory while adding'
871 )
871 )
872 raise error.Abort(msg % filename, hint=hint)
872 raise error.Abort(msg % filename, hint=hint)
873
873
874 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
874 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
875 if exists is None:
875 if exists is None:
876 exists = os.path.lexists(os.path.join(self._root, path))
876 exists = os.path.lexists(os.path.join(self._root, path))
877 if not exists:
877 if not exists:
878 # Maybe a path component exists
878 # Maybe a path component exists
879 if not ignoremissing and b'/' in path:
879 if not ignoremissing and b'/' in path:
880 d, f = path.rsplit(b'/', 1)
880 d, f = path.rsplit(b'/', 1)
881 d = self._normalize(d, False, ignoremissing, None)
881 d = self._normalize(d, False, ignoremissing, None)
882 folded = d + b"/" + f
882 folded = d + b"/" + f
883 else:
883 else:
884 # No path components, preserve original case
884 # No path components, preserve original case
885 folded = path
885 folded = path
886 else:
886 else:
887 # recursively normalize leading directory components
887 # recursively normalize leading directory components
888 # against dirstate
888 # against dirstate
889 if b'/' in normed:
889 if b'/' in normed:
890 d, f = normed.rsplit(b'/', 1)
890 d, f = normed.rsplit(b'/', 1)
891 d = self._normalize(d, False, ignoremissing, True)
891 d = self._normalize(d, False, ignoremissing, True)
892 r = self._root + b"/" + d
892 r = self._root + b"/" + d
893 folded = d + b"/" + util.fspath(f, r)
893 folded = d + b"/" + util.fspath(f, r)
894 else:
894 else:
895 folded = util.fspath(normed, self._root)
895 folded = util.fspath(normed, self._root)
896 storemap[normed] = folded
896 storemap[normed] = folded
897
897
898 return folded
898 return folded
899
899
900 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
900 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
901 normed = util.normcase(path)
901 normed = util.normcase(path)
902 folded = self._map.filefoldmap.get(normed, None)
902 folded = self._map.filefoldmap.get(normed, None)
903 if folded is None:
903 if folded is None:
904 if isknown:
904 if isknown:
905 folded = path
905 folded = path
906 else:
906 else:
907 folded = self._discoverpath(
907 folded = self._discoverpath(
908 path, normed, ignoremissing, exists, self._map.filefoldmap
908 path, normed, ignoremissing, exists, self._map.filefoldmap
909 )
909 )
910 return folded
910 return folded
911
911
912 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
912 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
913 normed = util.normcase(path)
913 normed = util.normcase(path)
914 folded = self._map.filefoldmap.get(normed, None)
914 folded = self._map.filefoldmap.get(normed, None)
915 if folded is None:
915 if folded is None:
916 folded = self._map.dirfoldmap.get(normed, None)
916 folded = self._map.dirfoldmap.get(normed, None)
917 if folded is None:
917 if folded is None:
918 if isknown:
918 if isknown:
919 folded = path
919 folded = path
920 else:
920 else:
921 # store discovered result in dirfoldmap so that future
921 # store discovered result in dirfoldmap so that future
922 # normalizefile calls don't start matching directories
922 # normalizefile calls don't start matching directories
923 folded = self._discoverpath(
923 folded = self._discoverpath(
924 path, normed, ignoremissing, exists, self._map.dirfoldmap
924 path, normed, ignoremissing, exists, self._map.dirfoldmap
925 )
925 )
926 return folded
926 return folded
927
927
928 def normalize(self, path, isknown=False, ignoremissing=False):
928 def normalize(self, path, isknown=False, ignoremissing=False):
929 """
929 """
930 normalize the case of a pathname when on a casefolding filesystem
930 normalize the case of a pathname when on a casefolding filesystem
931
931
932 isknown specifies whether the filename came from walking the
932 isknown specifies whether the filename came from walking the
933 disk, to avoid extra filesystem access.
933 disk, to avoid extra filesystem access.
934
934
935 If ignoremissing is True, missing path are returned
935 If ignoremissing is True, missing path are returned
936 unchanged. Otherwise, we try harder to normalize possibly
936 unchanged. Otherwise, we try harder to normalize possibly
937 existing path components.
937 existing path components.
938
938
939 The normalized case is determined based on the following precedence:
939 The normalized case is determined based on the following precedence:
940
940
941 - version of name already stored in the dirstate
941 - version of name already stored in the dirstate
942 - version of name stored on disk
942 - version of name stored on disk
943 - version provided via command arguments
943 - version provided via command arguments
944 """
944 """
945
945
946 if self._checkcase:
946 if self._checkcase:
947 return self._normalize(path, isknown, ignoremissing)
947 return self._normalize(path, isknown, ignoremissing)
948 return path
948 return path
949
949
950 # XXX this method is barely used, as a result:
950 # XXX this method is barely used, as a result:
951 # - its semantic is unclear
951 # - its semantic is unclear
952 # - do we really needs it ?
952 # - do we really needs it ?
953 @requires_changing_parents
953 @requires_changing_parents
954 def clear(self):
954 def clear(self):
955 self._map.clear()
955 self._map.clear()
956 self._dirty = True
956 self._dirty = True
957
957
958 @requires_changing_parents
958 @requires_changing_parents
959 def rebuild(self, parent, allfiles, changedfiles=None):
959 def rebuild(self, parent, allfiles, changedfiles=None):
960 matcher = self._sparsematcher
960 matcher = self._sparsematcher
961 if matcher is not None and not matcher.always():
961 if matcher is not None and not matcher.always():
962 # should not add non-matching files
962 # should not add non-matching files
963 allfiles = [f for f in allfiles if matcher(f)]
963 allfiles = [f for f in allfiles if matcher(f)]
964 if changedfiles:
964 if changedfiles:
965 changedfiles = [f for f in changedfiles if matcher(f)]
965 changedfiles = [f for f in changedfiles if matcher(f)]
966
966
967 if changedfiles is not None:
967 if changedfiles is not None:
968 # these files will be deleted from the dirstate when they are
968 # these files will be deleted from the dirstate when they are
969 # not found to be in allfiles
969 # not found to be in allfiles
970 dirstatefilestoremove = {f for f in self if not matcher(f)}
970 dirstatefilestoremove = {f for f in self if not matcher(f)}
971 changedfiles = dirstatefilestoremove.union(changedfiles)
971 changedfiles = dirstatefilestoremove.union(changedfiles)
972
972
973 if changedfiles is None:
973 if changedfiles is None:
974 # Rebuild entire dirstate
974 # Rebuild entire dirstate
975 to_lookup = allfiles
975 to_lookup = allfiles
976 to_drop = []
976 to_drop = []
977 self.clear()
977 self.clear()
978 elif len(changedfiles) < 10:
978 elif len(changedfiles) < 10:
979 # Avoid turning allfiles into a set, which can be expensive if it's
979 # Avoid turning allfiles into a set, which can be expensive if it's
980 # large.
980 # large.
981 to_lookup = []
981 to_lookup = []
982 to_drop = []
982 to_drop = []
983 for f in changedfiles:
983 for f in changedfiles:
984 if f in allfiles:
984 if f in allfiles:
985 to_lookup.append(f)
985 to_lookup.append(f)
986 else:
986 else:
987 to_drop.append(f)
987 to_drop.append(f)
988 else:
988 else:
989 changedfilesset = set(changedfiles)
989 changedfilesset = set(changedfiles)
990 to_lookup = changedfilesset & set(allfiles)
990 to_lookup = changedfilesset & set(allfiles)
991 to_drop = changedfilesset - to_lookup
991 to_drop = changedfilesset - to_lookup
992
992
993 if self._origpl is None:
993 if self._origpl is None:
994 self._origpl = self._pl
994 self._origpl = self._pl
995 self._map.setparents(parent, self._nodeconstants.nullid)
995 self._map.setparents(parent, self._nodeconstants.nullid)
996
996
997 for f in to_lookup:
997 for f in to_lookup:
998 if self.in_merge:
998 if self.in_merge:
999 self.set_tracked(f)
999 self.set_tracked(f)
1000 else:
1000 else:
1001 self._map.reset_state(
1001 self._map.reset_state(
1002 f,
1002 f,
1003 wc_tracked=True,
1003 wc_tracked=True,
1004 p1_tracked=True,
1004 p1_tracked=True,
1005 )
1005 )
1006 for f in to_drop:
1006 for f in to_drop:
1007 self._map.reset_state(f)
1007 self._map.reset_state(f)
1008
1008
1009 self._dirty = True
1009 self._dirty = True
1010
1010
1011 def identity(self):
1011 def identity(self):
1012 """Return identity of dirstate itself to detect changing in storage
1012 """Return identity of dirstate itself to detect changing in storage
1013
1013
1014 If identity of previous dirstate is equal to this, writing
1014 If identity of previous dirstate is equal to this, writing
1015 changes based on the former dirstate out can keep consistency.
1015 changes based on the former dirstate out can keep consistency.
1016 """
1016 """
1017 return self._map.identity
1017 return self._map.identity
1018
1018
1019 def write(self, tr):
1019 def write(self, tr):
1020 if not self._dirty:
1020 if not self._dirty:
1021 return
1021 return
1022 # make sure we don't request a write of invalidated content
1022 # make sure we don't request a write of invalidated content
1023 # XXX move before the dirty check once `unlock` stop calling `write`
1023 # XXX move before the dirty check once `unlock` stop calling `write`
1024 assert not self._invalidated_context
1024 assert not self._invalidated_context
1025
1025
1026 write_key = self._use_tracked_hint and self._dirty_tracked_set
1026 write_key = self._use_tracked_hint and self._dirty_tracked_set
1027 if tr:
1027 if tr:
1028
1028
1029 def on_abort(tr):
1029 def on_abort(tr):
1030 self._attached_to_a_transaction = False
1030 self._attached_to_a_transaction = False
1031 self.invalidate()
1031 self.invalidate()
1032
1032
1033 # make sure we invalidate the current change on abort
1033 # make sure we invalidate the current change on abort
1034 if tr is not None:
1034 if tr is not None:
1035 tr.addabort(
1035 tr.addabort(
1036 b'dirstate-invalidate%s' % self._tr_key_suffix,
1036 b'dirstate-invalidate%s' % self._tr_key_suffix,
1037 on_abort,
1037 on_abort,
1038 )
1038 )
1039
1039
1040 self._attached_to_a_transaction = True
1040 self._attached_to_a_transaction = True
1041
1041
1042 def on_success(f):
1042 def on_success(f):
1043 self._attached_to_a_transaction = False
1043 self._attached_to_a_transaction = False
1044 self._writedirstate(tr, f),
1044 self._writedirstate(tr, f),
1045
1045
1046 # delay writing in-memory changes out
1046 # delay writing in-memory changes out
1047 tr.addfilegenerator(
1047 tr.addfilegenerator(
1048 b'dirstate-1-main%s' % self._tr_key_suffix,
1048 b'dirstate-1-main%s' % self._tr_key_suffix,
1049 (self._filename,),
1049 (self._filename,),
1050 on_success,
1050 on_success,
1051 location=b'plain',
1051 location=b'plain',
1052 post_finalize=True,
1052 post_finalize=True,
1053 )
1053 )
1054 if write_key:
1054 if write_key:
1055 tr.addfilegenerator(
1055 tr.addfilegenerator(
1056 b'dirstate-2-key-post%s' % self._tr_key_suffix,
1056 b'dirstate-2-key-post%s' % self._tr_key_suffix,
1057 (self._filename_th,),
1057 (self._filename_th,),
1058 lambda f: self._write_tracked_hint(tr, f),
1058 lambda f: self._write_tracked_hint(tr, f),
1059 location=b'plain',
1059 location=b'plain',
1060 post_finalize=True,
1060 post_finalize=True,
1061 )
1061 )
1062 return
1062 return
1063
1063
1064 file = lambda f: self._opener(f, b"w", atomictemp=True, checkambig=True)
1064 file = lambda f: self._opener(f, b"w", atomictemp=True, checkambig=True)
1065 with file(self._filename) as f:
1065 with file(self._filename) as f:
1066 self._writedirstate(tr, f)
1066 self._writedirstate(tr, f)
1067 if write_key:
1067 if write_key:
1068 # we update the key-file after writing to make sure reader have a
1068 # we update the key-file after writing to make sure reader have a
1069 # key that match the newly written content
1069 # key that match the newly written content
1070 with file(self._filename_th) as f:
1070 with file(self._filename_th) as f:
1071 self._write_tracked_hint(tr, f)
1071 self._write_tracked_hint(tr, f)
1072
1072
1073 def delete_tracked_hint(self):
1073 def delete_tracked_hint(self):
1074 """remove the tracked_hint file
1074 """remove the tracked_hint file
1075
1075
1076 To be used by format downgrades operation"""
1076 To be used by format downgrades operation"""
1077 self._opener.unlink(self._filename_th)
1077 self._opener.unlink(self._filename_th)
1078 self._use_tracked_hint = False
1078 self._use_tracked_hint = False
1079
1079
1080 def addparentchangecallback(self, category, callback):
1080 def addparentchangecallback(self, category, callback):
1081 """add a callback to be called when the wd parents are changed
1081 """add a callback to be called when the wd parents are changed
1082
1082
1083 Callback will be called with the following arguments:
1083 Callback will be called with the following arguments:
1084 dirstate, (oldp1, oldp2), (newp1, newp2)
1084 dirstate, (oldp1, oldp2), (newp1, newp2)
1085
1085
1086 Category is a unique identifier to allow overwriting an old callback
1086 Category is a unique identifier to allow overwriting an old callback
1087 with a newer callback.
1087 with a newer callback.
1088 """
1088 """
1089 self._plchangecallbacks[category] = callback
1089 self._plchangecallbacks[category] = callback
1090
1090
1091 def _writedirstate(self, tr, st):
1091 def _writedirstate(self, tr, st):
1092 # make sure we don't write invalidated content
1092 # make sure we don't write invalidated content
1093 assert not self._invalidated_context
1093 assert not self._invalidated_context
1094 # notify callbacks about parents change
1094 # notify callbacks about parents change
1095 if self._origpl is not None and self._origpl != self._pl:
1095 if self._origpl is not None and self._origpl != self._pl:
1096 for c, callback in sorted(self._plchangecallbacks.items()):
1096 for c, callback in sorted(self._plchangecallbacks.items()):
1097 callback(self, self._origpl, self._pl)
1097 callback(self, self._origpl, self._pl)
1098 self._origpl = None
1098 self._origpl = None
1099 self._map.write(tr, st)
1099 self._map.write(tr, st)
1100 self._dirty = False
1100 self._dirty = False
1101 self._dirty_tracked_set = False
1101 self._dirty_tracked_set = False
1102
1102
1103 def _write_tracked_hint(self, tr, f):
1103 def _write_tracked_hint(self, tr, f):
1104 key = node.hex(uuid.uuid4().bytes)
1104 key = node.hex(uuid.uuid4().bytes)
1105 f.write(b"1\n%s\n" % key) # 1 is the format version
1105 f.write(b"1\n%s\n" % key) # 1 is the format version
1106
1106
1107 def _dirignore(self, f):
1107 def _dirignore(self, f):
1108 if self._ignore(f):
1108 if self._ignore(f):
1109 return True
1109 return True
1110 for p in pathutil.finddirs(f):
1110 for p in pathutil.finddirs(f):
1111 if self._ignore(p):
1111 if self._ignore(p):
1112 return True
1112 return True
1113 return False
1113 return False
1114
1114
1115 def _ignorefiles(self):
1115 def _ignorefiles(self):
1116 files = []
1116 files = []
1117 if os.path.exists(self._join(b'.hgignore')):
1117 if os.path.exists(self._join(b'.hgignore')):
1118 files.append(self._join(b'.hgignore'))
1118 files.append(self._join(b'.hgignore'))
1119 for name, path in self._ui.configitems(b"ui"):
1119 for name, path in self._ui.configitems(b"ui"):
1120 if name == b'ignore' or name.startswith(b'ignore.'):
1120 if name == b'ignore' or name.startswith(b'ignore.'):
1121 # we need to use os.path.join here rather than self._join
1121 # we need to use os.path.join here rather than self._join
1122 # because path is arbitrary and user-specified
1122 # because path is arbitrary and user-specified
1123 files.append(os.path.join(self._rootdir, util.expandpath(path)))
1123 files.append(os.path.join(self._rootdir, util.expandpath(path)))
1124 return files
1124 return files
1125
1125
1126 def _ignorefileandline(self, f):
1126 def _ignorefileandline(self, f):
1127 files = collections.deque(self._ignorefiles())
1127 files = collections.deque(self._ignorefiles())
1128 visited = set()
1128 visited = set()
1129 while files:
1129 while files:
1130 i = files.popleft()
1130 i = files.popleft()
1131 patterns = matchmod.readpatternfile(
1131 patterns = matchmod.readpatternfile(
1132 i, self._ui.warn, sourceinfo=True
1132 i, self._ui.warn, sourceinfo=True
1133 )
1133 )
1134 for pattern, lineno, line in patterns:
1134 for pattern, lineno, line in patterns:
1135 kind, p = matchmod._patsplit(pattern, b'glob')
1135 kind, p = matchmod._patsplit(pattern, b'glob')
1136 if kind == b"subinclude":
1136 if kind == b"subinclude":
1137 if p not in visited:
1137 if p not in visited:
1138 files.append(p)
1138 files.append(p)
1139 continue
1139 continue
1140 m = matchmod.match(
1140 m = matchmod.match(
1141 self._root, b'', [], [pattern], warn=self._ui.warn
1141 self._root, b'', [], [pattern], warn=self._ui.warn
1142 )
1142 )
1143 if m(f):
1143 if m(f):
1144 return (i, lineno, line)
1144 return (i, lineno, line)
1145 visited.add(i)
1145 visited.add(i)
1146 return (None, -1, b"")
1146 return (None, -1, b"")
1147
1147
1148 def _walkexplicit(self, match, subrepos):
1148 def _walkexplicit(self, match, subrepos):
1149 """Get stat data about the files explicitly specified by match.
1149 """Get stat data about the files explicitly specified by match.
1150
1150
1151 Return a triple (results, dirsfound, dirsnotfound).
1151 Return a triple (results, dirsfound, dirsnotfound).
1152 - results is a mapping from filename to stat result. It also contains
1152 - results is a mapping from filename to stat result. It also contains
1153 listings mapping subrepos and .hg to None.
1153 listings mapping subrepos and .hg to None.
1154 - dirsfound is a list of files found to be directories.
1154 - dirsfound is a list of files found to be directories.
1155 - dirsnotfound is a list of files that the dirstate thinks are
1155 - dirsnotfound is a list of files that the dirstate thinks are
1156 directories and that were not found."""
1156 directories and that were not found."""
1157
1157
1158 def badtype(mode):
1158 def badtype(mode):
1159 kind = _(b'unknown')
1159 kind = _(b'unknown')
1160 if stat.S_ISCHR(mode):
1160 if stat.S_ISCHR(mode):
1161 kind = _(b'character device')
1161 kind = _(b'character device')
1162 elif stat.S_ISBLK(mode):
1162 elif stat.S_ISBLK(mode):
1163 kind = _(b'block device')
1163 kind = _(b'block device')
1164 elif stat.S_ISFIFO(mode):
1164 elif stat.S_ISFIFO(mode):
1165 kind = _(b'fifo')
1165 kind = _(b'fifo')
1166 elif stat.S_ISSOCK(mode):
1166 elif stat.S_ISSOCK(mode):
1167 kind = _(b'socket')
1167 kind = _(b'socket')
1168 elif stat.S_ISDIR(mode):
1168 elif stat.S_ISDIR(mode):
1169 kind = _(b'directory')
1169 kind = _(b'directory')
1170 return _(b'unsupported file type (type is %s)') % kind
1170 return _(b'unsupported file type (type is %s)') % kind
1171
1171
1172 badfn = match.bad
1172 badfn = match.bad
1173 dmap = self._map
1173 dmap = self._map
1174 lstat = os.lstat
1174 lstat = os.lstat
1175 getkind = stat.S_IFMT
1175 getkind = stat.S_IFMT
1176 dirkind = stat.S_IFDIR
1176 dirkind = stat.S_IFDIR
1177 regkind = stat.S_IFREG
1177 regkind = stat.S_IFREG
1178 lnkkind = stat.S_IFLNK
1178 lnkkind = stat.S_IFLNK
1179 join = self._join
1179 join = self._join
1180 dirsfound = []
1180 dirsfound = []
1181 foundadd = dirsfound.append
1181 foundadd = dirsfound.append
1182 dirsnotfound = []
1182 dirsnotfound = []
1183 notfoundadd = dirsnotfound.append
1183 notfoundadd = dirsnotfound.append
1184
1184
1185 if not match.isexact() and self._checkcase:
1185 if not match.isexact() and self._checkcase:
1186 normalize = self._normalize
1186 normalize = self._normalize
1187 else:
1187 else:
1188 normalize = None
1188 normalize = None
1189
1189
1190 files = sorted(match.files())
1190 files = sorted(match.files())
1191 subrepos.sort()
1191 subrepos.sort()
1192 i, j = 0, 0
1192 i, j = 0, 0
1193 while i < len(files) and j < len(subrepos):
1193 while i < len(files) and j < len(subrepos):
1194 subpath = subrepos[j] + b"/"
1194 subpath = subrepos[j] + b"/"
1195 if files[i] < subpath:
1195 if files[i] < subpath:
1196 i += 1
1196 i += 1
1197 continue
1197 continue
1198 while i < len(files) and files[i].startswith(subpath):
1198 while i < len(files) and files[i].startswith(subpath):
1199 del files[i]
1199 del files[i]
1200 j += 1
1200 j += 1
1201
1201
1202 if not files or b'' in files:
1202 if not files or b'' in files:
1203 files = [b'']
1203 files = [b'']
1204 # constructing the foldmap is expensive, so don't do it for the
1204 # constructing the foldmap is expensive, so don't do it for the
1205 # common case where files is ['']
1205 # common case where files is ['']
1206 normalize = None
1206 normalize = None
1207 results = dict.fromkeys(subrepos)
1207 results = dict.fromkeys(subrepos)
1208 results[b'.hg'] = None
1208 results[b'.hg'] = None
1209
1209
1210 for ff in files:
1210 for ff in files:
1211 if normalize:
1211 if normalize:
1212 nf = normalize(ff, False, True)
1212 nf = normalize(ff, False, True)
1213 else:
1213 else:
1214 nf = ff
1214 nf = ff
1215 if nf in results:
1215 if nf in results:
1216 continue
1216 continue
1217
1217
1218 try:
1218 try:
1219 st = lstat(join(nf))
1219 st = lstat(join(nf))
1220 kind = getkind(st.st_mode)
1220 kind = getkind(st.st_mode)
1221 if kind == dirkind:
1221 if kind == dirkind:
1222 if nf in dmap:
1222 if nf in dmap:
1223 # file replaced by dir on disk but still in dirstate
1223 # file replaced by dir on disk but still in dirstate
1224 results[nf] = None
1224 results[nf] = None
1225 foundadd((nf, ff))
1225 foundadd((nf, ff))
1226 elif kind == regkind or kind == lnkkind:
1226 elif kind == regkind or kind == lnkkind:
1227 results[nf] = st
1227 results[nf] = st
1228 else:
1228 else:
1229 badfn(ff, badtype(kind))
1229 badfn(ff, badtype(kind))
1230 if nf in dmap:
1230 if nf in dmap:
1231 results[nf] = None
1231 results[nf] = None
1232 except (OSError) as inst:
1232 except (OSError) as inst:
1233 # nf not found on disk - it is dirstate only
1233 # nf not found on disk - it is dirstate only
1234 if nf in dmap: # does it exactly match a missing file?
1234 if nf in dmap: # does it exactly match a missing file?
1235 results[nf] = None
1235 results[nf] = None
1236 else: # does it match a missing directory?
1236 else: # does it match a missing directory?
1237 if self._map.hasdir(nf):
1237 if self._map.hasdir(nf):
1238 notfoundadd(nf)
1238 notfoundadd(nf)
1239 else:
1239 else:
1240 badfn(ff, encoding.strtolocal(inst.strerror))
1240 badfn(ff, encoding.strtolocal(inst.strerror))
1241
1241
1242 # match.files() may contain explicitly-specified paths that shouldn't
1242 # match.files() may contain explicitly-specified paths that shouldn't
1243 # be taken; drop them from the list of files found. dirsfound/notfound
1243 # be taken; drop them from the list of files found. dirsfound/notfound
1244 # aren't filtered here because they will be tested later.
1244 # aren't filtered here because they will be tested later.
1245 if match.anypats():
1245 if match.anypats():
1246 for f in list(results):
1246 for f in list(results):
1247 if f == b'.hg' or f in subrepos:
1247 if f == b'.hg' or f in subrepos:
1248 # keep sentinel to disable further out-of-repo walks
1248 # keep sentinel to disable further out-of-repo walks
1249 continue
1249 continue
1250 if not match(f):
1250 if not match(f):
1251 del results[f]
1251 del results[f]
1252
1252
1253 # Case insensitive filesystems cannot rely on lstat() failing to detect
1253 # Case insensitive filesystems cannot rely on lstat() failing to detect
1254 # a case-only rename. Prune the stat object for any file that does not
1254 # a case-only rename. Prune the stat object for any file that does not
1255 # match the case in the filesystem, if there are multiple files that
1255 # match the case in the filesystem, if there are multiple files that
1256 # normalize to the same path.
1256 # normalize to the same path.
1257 if match.isexact() and self._checkcase:
1257 if match.isexact() and self._checkcase:
1258 normed = {}
1258 normed = {}
1259
1259
1260 for f, st in results.items():
1260 for f, st in results.items():
1261 if st is None:
1261 if st is None:
1262 continue
1262 continue
1263
1263
1264 nc = util.normcase(f)
1264 nc = util.normcase(f)
1265 paths = normed.get(nc)
1265 paths = normed.get(nc)
1266
1266
1267 if paths is None:
1267 if paths is None:
1268 paths = set()
1268 paths = set()
1269 normed[nc] = paths
1269 normed[nc] = paths
1270
1270
1271 paths.add(f)
1271 paths.add(f)
1272
1272
1273 for norm, paths in normed.items():
1273 for norm, paths in normed.items():
1274 if len(paths) > 1:
1274 if len(paths) > 1:
1275 for path in paths:
1275 for path in paths:
1276 folded = self._discoverpath(
1276 folded = self._discoverpath(
1277 path, norm, True, None, self._map.dirfoldmap
1277 path, norm, True, None, self._map.dirfoldmap
1278 )
1278 )
1279 if path != folded:
1279 if path != folded:
1280 results[path] = None
1280 results[path] = None
1281
1281
1282 return results, dirsfound, dirsnotfound
1282 return results, dirsfound, dirsnotfound
1283
1283
1284 def walk(self, match, subrepos, unknown, ignored, full=True):
1284 def walk(self, match, subrepos, unknown, ignored, full=True):
1285 """
1285 """
1286 Walk recursively through the directory tree, finding all files
1286 Walk recursively through the directory tree, finding all files
1287 matched by match.
1287 matched by match.
1288
1288
1289 If full is False, maybe skip some known-clean files.
1289 If full is False, maybe skip some known-clean files.
1290
1290
1291 Return a dict mapping filename to stat-like object (either
1291 Return a dict mapping filename to stat-like object (either
1292 mercurial.osutil.stat instance or return value of os.stat()).
1292 mercurial.osutil.stat instance or return value of os.stat()).
1293
1293
1294 """
1294 """
1295 # full is a flag that extensions that hook into walk can use -- this
1295 # full is a flag that extensions that hook into walk can use -- this
1296 # implementation doesn't use it at all. This satisfies the contract
1296 # implementation doesn't use it at all. This satisfies the contract
1297 # because we only guarantee a "maybe".
1297 # because we only guarantee a "maybe".
1298
1298
1299 if ignored:
1299 if ignored:
1300 ignore = util.never
1300 ignore = util.never
1301 dirignore = util.never
1301 dirignore = util.never
1302 elif unknown:
1302 elif unknown:
1303 ignore = self._ignore
1303 ignore = self._ignore
1304 dirignore = self._dirignore
1304 dirignore = self._dirignore
1305 else:
1305 else:
1306 # if not unknown and not ignored, drop dir recursion and step 2
1306 # if not unknown and not ignored, drop dir recursion and step 2
1307 ignore = util.always
1307 ignore = util.always
1308 dirignore = util.always
1308 dirignore = util.always
1309
1309
1310 if self._sparsematchfn is not None:
1310 if self._sparsematchfn is not None:
1311 em = matchmod.exact(match.files())
1311 em = matchmod.exact(match.files())
1312 sm = matchmod.unionmatcher([self._sparsematcher, em])
1312 sm = matchmod.unionmatcher([self._sparsematcher, em])
1313 match = matchmod.intersectmatchers(match, sm)
1313 match = matchmod.intersectmatchers(match, sm)
1314
1314
1315 matchfn = match.matchfn
1315 matchfn = match.matchfn
1316 matchalways = match.always()
1316 matchalways = match.always()
1317 matchtdir = match.traversedir
1317 matchtdir = match.traversedir
1318 dmap = self._map
1318 dmap = self._map
1319 listdir = util.listdir
1319 listdir = util.listdir
1320 lstat = os.lstat
1320 lstat = os.lstat
1321 dirkind = stat.S_IFDIR
1321 dirkind = stat.S_IFDIR
1322 regkind = stat.S_IFREG
1322 regkind = stat.S_IFREG
1323 lnkkind = stat.S_IFLNK
1323 lnkkind = stat.S_IFLNK
1324 join = self._join
1324 join = self._join
1325
1325
1326 exact = skipstep3 = False
1326 exact = skipstep3 = False
1327 if match.isexact(): # match.exact
1327 if match.isexact(): # match.exact
1328 exact = True
1328 exact = True
1329 dirignore = util.always # skip step 2
1329 dirignore = util.always # skip step 2
1330 elif match.prefix(): # match.match, no patterns
1330 elif match.prefix(): # match.match, no patterns
1331 skipstep3 = True
1331 skipstep3 = True
1332
1332
1333 if not exact and self._checkcase:
1333 if not exact and self._checkcase:
1334 normalize = self._normalize
1334 normalize = self._normalize
1335 normalizefile = self._normalizefile
1335 normalizefile = self._normalizefile
1336 skipstep3 = False
1336 skipstep3 = False
1337 else:
1337 else:
1338 normalize = self._normalize
1338 normalize = self._normalize
1339 normalizefile = None
1339 normalizefile = None
1340
1340
1341 # step 1: find all explicit files
1341 # step 1: find all explicit files
1342 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1342 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1343 if matchtdir:
1343 if matchtdir:
1344 for d in work:
1344 for d in work:
1345 matchtdir(d[0])
1345 matchtdir(d[0])
1346 for d in dirsnotfound:
1346 for d in dirsnotfound:
1347 matchtdir(d)
1347 matchtdir(d)
1348
1348
1349 skipstep3 = skipstep3 and not (work or dirsnotfound)
1349 skipstep3 = skipstep3 and not (work or dirsnotfound)
1350 work = [d for d in work if not dirignore(d[0])]
1350 work = [d for d in work if not dirignore(d[0])]
1351
1351
1352 # step 2: visit subdirectories
1352 # step 2: visit subdirectories
1353 def traverse(work, alreadynormed):
1353 def traverse(work, alreadynormed):
1354 wadd = work.append
1354 wadd = work.append
1355 while work:
1355 while work:
1356 tracing.counter('dirstate.walk work', len(work))
1356 tracing.counter('dirstate.walk work', len(work))
1357 nd = work.pop()
1357 nd = work.pop()
1358 visitentries = match.visitchildrenset(nd)
1358 visitentries = match.visitchildrenset(nd)
1359 if not visitentries:
1359 if not visitentries:
1360 continue
1360 continue
1361 if visitentries == b'this' or visitentries == b'all':
1361 if visitentries == b'this' or visitentries == b'all':
1362 visitentries = None
1362 visitentries = None
1363 skip = None
1363 skip = None
1364 if nd != b'':
1364 if nd != b'':
1365 skip = b'.hg'
1365 skip = b'.hg'
1366 try:
1366 try:
1367 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1367 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1368 entries = listdir(join(nd), stat=True, skip=skip)
1368 entries = listdir(join(nd), stat=True, skip=skip)
1369 except (PermissionError, FileNotFoundError) as inst:
1369 except (PermissionError, FileNotFoundError) as inst:
1370 match.bad(
1370 match.bad(
1371 self.pathto(nd), encoding.strtolocal(inst.strerror)
1371 self.pathto(nd), encoding.strtolocal(inst.strerror)
1372 )
1372 )
1373 continue
1373 continue
1374 for f, kind, st in entries:
1374 for f, kind, st in entries:
1375 # Some matchers may return files in the visitentries set,
1375 # Some matchers may return files in the visitentries set,
1376 # instead of 'this', if the matcher explicitly mentions them
1376 # instead of 'this', if the matcher explicitly mentions them
1377 # and is not an exactmatcher. This is acceptable; we do not
1377 # and is not an exactmatcher. This is acceptable; we do not
1378 # make any hard assumptions about file-or-directory below
1378 # make any hard assumptions about file-or-directory below
1379 # based on the presence of `f` in visitentries. If
1379 # based on the presence of `f` in visitentries. If
1380 # visitchildrenset returned a set, we can always skip the
1380 # visitchildrenset returned a set, we can always skip the
1381 # entries *not* in the set it provided regardless of whether
1381 # entries *not* in the set it provided regardless of whether
1382 # they're actually a file or a directory.
1382 # they're actually a file or a directory.
1383 if visitentries and f not in visitentries:
1383 if visitentries and f not in visitentries:
1384 continue
1384 continue
1385 if normalizefile:
1385 if normalizefile:
1386 # even though f might be a directory, we're only
1386 # even though f might be a directory, we're only
1387 # interested in comparing it to files currently in the
1387 # interested in comparing it to files currently in the
1388 # dmap -- therefore normalizefile is enough
1388 # dmap -- therefore normalizefile is enough
1389 nf = normalizefile(
1389 nf = normalizefile(
1390 nd and (nd + b"/" + f) or f, True, True
1390 nd and (nd + b"/" + f) or f, True, True
1391 )
1391 )
1392 else:
1392 else:
1393 nf = nd and (nd + b"/" + f) or f
1393 nf = nd and (nd + b"/" + f) or f
1394 if nf not in results:
1394 if nf not in results:
1395 if kind == dirkind:
1395 if kind == dirkind:
1396 if not ignore(nf):
1396 if not ignore(nf):
1397 if matchtdir:
1397 if matchtdir:
1398 matchtdir(nf)
1398 matchtdir(nf)
1399 wadd(nf)
1399 wadd(nf)
1400 if nf in dmap and (matchalways or matchfn(nf)):
1400 if nf in dmap and (matchalways or matchfn(nf)):
1401 results[nf] = None
1401 results[nf] = None
1402 elif kind == regkind or kind == lnkkind:
1402 elif kind == regkind or kind == lnkkind:
1403 if nf in dmap:
1403 if nf in dmap:
1404 if matchalways or matchfn(nf):
1404 if matchalways or matchfn(nf):
1405 results[nf] = st
1405 results[nf] = st
1406 elif (matchalways or matchfn(nf)) and not ignore(
1406 elif (matchalways or matchfn(nf)) and not ignore(
1407 nf
1407 nf
1408 ):
1408 ):
1409 # unknown file -- normalize if necessary
1409 # unknown file -- normalize if necessary
1410 if not alreadynormed:
1410 if not alreadynormed:
1411 nf = normalize(nf, False, True)
1411 nf = normalize(nf, False, True)
1412 results[nf] = st
1412 results[nf] = st
1413 elif nf in dmap and (matchalways or matchfn(nf)):
1413 elif nf in dmap and (matchalways or matchfn(nf)):
1414 results[nf] = None
1414 results[nf] = None
1415
1415
1416 for nd, d in work:
1416 for nd, d in work:
1417 # alreadynormed means that processwork doesn't have to do any
1417 # alreadynormed means that processwork doesn't have to do any
1418 # expensive directory normalization
1418 # expensive directory normalization
1419 alreadynormed = not normalize or nd == d
1419 alreadynormed = not normalize or nd == d
1420 traverse([d], alreadynormed)
1420 traverse([d], alreadynormed)
1421
1421
1422 for s in subrepos:
1422 for s in subrepos:
1423 del results[s]
1423 del results[s]
1424 del results[b'.hg']
1424 del results[b'.hg']
1425
1425
1426 # step 3: visit remaining files from dmap
1426 # step 3: visit remaining files from dmap
1427 if not skipstep3 and not exact:
1427 if not skipstep3 and not exact:
1428 # If a dmap file is not in results yet, it was either
1428 # If a dmap file is not in results yet, it was either
1429 # a) not matching matchfn b) ignored, c) missing, or d) under a
1429 # a) not matching matchfn b) ignored, c) missing, or d) under a
1430 # symlink directory.
1430 # symlink directory.
1431 if not results and matchalways:
1431 if not results and matchalways:
1432 visit = [f for f in dmap]
1432 visit = [f for f in dmap]
1433 else:
1433 else:
1434 visit = [f for f in dmap if f not in results and matchfn(f)]
1434 visit = [f for f in dmap if f not in results and matchfn(f)]
1435 visit.sort()
1435 visit.sort()
1436
1436
1437 if unknown:
1437 if unknown:
1438 # unknown == True means we walked all dirs under the roots
1438 # unknown == True means we walked all dirs under the roots
1439 # that wasn't ignored, and everything that matched was stat'ed
1439 # that wasn't ignored, and everything that matched was stat'ed
1440 # and is already in results.
1440 # and is already in results.
1441 # The rest must thus be ignored or under a symlink.
1441 # The rest must thus be ignored or under a symlink.
1442 audit_path = pathutil.pathauditor(self._root, cached=True)
1442 audit_path = pathutil.pathauditor(self._root, cached=True)
1443
1443
1444 for nf in iter(visit):
1444 for nf in iter(visit):
1445 # If a stat for the same file was already added with a
1445 # If a stat for the same file was already added with a
1446 # different case, don't add one for this, since that would
1446 # different case, don't add one for this, since that would
1447 # make it appear as if the file exists under both names
1447 # make it appear as if the file exists under both names
1448 # on disk.
1448 # on disk.
1449 if (
1449 if (
1450 normalizefile
1450 normalizefile
1451 and normalizefile(nf, True, True) in results
1451 and normalizefile(nf, True, True) in results
1452 ):
1452 ):
1453 results[nf] = None
1453 results[nf] = None
1454 # Report ignored items in the dmap as long as they are not
1454 # Report ignored items in the dmap as long as they are not
1455 # under a symlink directory.
1455 # under a symlink directory.
1456 elif audit_path.check(nf):
1456 elif audit_path.check(nf):
1457 try:
1457 try:
1458 results[nf] = lstat(join(nf))
1458 results[nf] = lstat(join(nf))
1459 # file was just ignored, no links, and exists
1459 # file was just ignored, no links, and exists
1460 except OSError:
1460 except OSError:
1461 # file doesn't exist
1461 # file doesn't exist
1462 results[nf] = None
1462 results[nf] = None
1463 else:
1463 else:
1464 # It's either missing or under a symlink directory
1464 # It's either missing or under a symlink directory
1465 # which we in this case report as missing
1465 # which we in this case report as missing
1466 results[nf] = None
1466 results[nf] = None
1467 else:
1467 else:
1468 # We may not have walked the full directory tree above,
1468 # We may not have walked the full directory tree above,
1469 # so stat and check everything we missed.
1469 # so stat and check everything we missed.
1470 iv = iter(visit)
1470 iv = iter(visit)
1471 for st in util.statfiles([join(i) for i in visit]):
1471 for st in util.statfiles([join(i) for i in visit]):
1472 results[next(iv)] = st
1472 results[next(iv)] = st
1473 return results
1473 return results
1474
1474
1475 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1475 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1476 if self._sparsematchfn is not None:
1476 if self._sparsematchfn is not None:
1477 em = matchmod.exact(matcher.files())
1477 em = matchmod.exact(matcher.files())
1478 sm = matchmod.unionmatcher([self._sparsematcher, em])
1478 sm = matchmod.unionmatcher([self._sparsematcher, em])
1479 matcher = matchmod.intersectmatchers(matcher, sm)
1479 matcher = matchmod.intersectmatchers(matcher, sm)
1480 # Force Rayon (Rust parallelism library) to respect the number of
1480 # Force Rayon (Rust parallelism library) to respect the number of
1481 # workers. This is a temporary workaround until Rust code knows
1481 # workers. This is a temporary workaround until Rust code knows
1482 # how to read the config file.
1482 # how to read the config file.
1483 numcpus = self._ui.configint(b"worker", b"numcpus")
1483 numcpus = self._ui.configint(b"worker", b"numcpus")
1484 if numcpus is not None:
1484 if numcpus is not None:
1485 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1485 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1486
1486
1487 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1487 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1488 if not workers_enabled:
1488 if not workers_enabled:
1489 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1489 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1490
1490
1491 (
1491 (
1492 lookup,
1492 lookup,
1493 modified,
1493 modified,
1494 added,
1494 added,
1495 removed,
1495 removed,
1496 deleted,
1496 deleted,
1497 clean,
1497 clean,
1498 ignored,
1498 ignored,
1499 unknown,
1499 unknown,
1500 warnings,
1500 warnings,
1501 bad,
1501 bad,
1502 traversed,
1502 traversed,
1503 dirty,
1503 dirty,
1504 ) = rustmod.status(
1504 ) = rustmod.status(
1505 self._map._map,
1505 self._map._map,
1506 matcher,
1506 matcher,
1507 self._rootdir,
1507 self._rootdir,
1508 self._ignorefiles(),
1508 self._ignorefiles(),
1509 self._checkexec,
1509 self._checkexec,
1510 bool(list_clean),
1510 bool(list_clean),
1511 bool(list_ignored),
1511 bool(list_ignored),
1512 bool(list_unknown),
1512 bool(list_unknown),
1513 bool(matcher.traversedir),
1513 bool(matcher.traversedir),
1514 )
1514 )
1515
1515
1516 self._dirty |= dirty
1516 self._dirty |= dirty
1517
1517
1518 if matcher.traversedir:
1518 if matcher.traversedir:
1519 for dir in traversed:
1519 for dir in traversed:
1520 matcher.traversedir(dir)
1520 matcher.traversedir(dir)
1521
1521
1522 if self._ui.warn:
1522 if self._ui.warn:
1523 for item in warnings:
1523 for item in warnings:
1524 if isinstance(item, tuple):
1524 if isinstance(item, tuple):
1525 file_path, syntax = item
1525 file_path, syntax = item
1526 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1526 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1527 file_path,
1527 file_path,
1528 syntax,
1528 syntax,
1529 )
1529 )
1530 self._ui.warn(msg)
1530 self._ui.warn(msg)
1531 else:
1531 else:
1532 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1532 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1533 self._ui.warn(
1533 self._ui.warn(
1534 msg
1534 msg
1535 % (
1535 % (
1536 pathutil.canonpath(
1536 pathutil.canonpath(
1537 self._rootdir, self._rootdir, item
1537 self._rootdir, self._rootdir, item
1538 ),
1538 ),
1539 b"No such file or directory",
1539 b"No such file or directory",
1540 )
1540 )
1541 )
1541 )
1542
1542
1543 for fn, message in bad:
1543 for fn, message in bad:
1544 matcher.bad(fn, encoding.strtolocal(message))
1544 matcher.bad(fn, encoding.strtolocal(message))
1545
1545
1546 status = scmutil.status(
1546 status = scmutil.status(
1547 modified=modified,
1547 modified=modified,
1548 added=added,
1548 added=added,
1549 removed=removed,
1549 removed=removed,
1550 deleted=deleted,
1550 deleted=deleted,
1551 unknown=unknown,
1551 unknown=unknown,
1552 ignored=ignored,
1552 ignored=ignored,
1553 clean=clean,
1553 clean=clean,
1554 )
1554 )
1555 return (lookup, status)
1555 return (lookup, status)
1556
1556
1557 # XXX since this can make the dirstate dirty (through rust), we should
1558 # enforce that it is done withing an appropriate change-context that scope
1559 # the change and ensure it eventually get written on disk (or rolled back)
1560 def status(self, match, subrepos, ignored, clean, unknown):
1557 def status(self, match, subrepos, ignored, clean, unknown):
1561 """Determine the status of the working copy relative to the
1558 """Determine the status of the working copy relative to the
1562 dirstate and return a pair of (unsure, status), where status is of type
1559 dirstate and return a pair of (unsure, status), where status is of type
1563 scmutil.status and:
1560 scmutil.status and:
1564
1561
1565 unsure:
1562 unsure:
1566 files that might have been modified since the dirstate was
1563 files that might have been modified since the dirstate was
1567 written, but need to be read to be sure (size is the same
1564 written, but need to be read to be sure (size is the same
1568 but mtime differs)
1565 but mtime differs)
1569 status.modified:
1566 status.modified:
1570 files that have definitely been modified since the dirstate
1567 files that have definitely been modified since the dirstate
1571 was written (different size or mode)
1568 was written (different size or mode)
1572 status.clean:
1569 status.clean:
1573 files that have definitely not been modified since the
1570 files that have definitely not been modified since the
1574 dirstate was written
1571 dirstate was written
1575 """
1572 """
1573 if not self._running_status:
1574 msg = "Calling `status` outside a `running_status` context"
1575 raise error.ProgrammingError(msg)
1576 listignored, listclean, listunknown = ignored, clean, unknown
1576 listignored, listclean, listunknown = ignored, clean, unknown
1577 lookup, modified, added, unknown, ignored = [], [], [], [], []
1577 lookup, modified, added, unknown, ignored = [], [], [], [], []
1578 removed, deleted, clean = [], [], []
1578 removed, deleted, clean = [], [], []
1579
1579
1580 dmap = self._map
1580 dmap = self._map
1581 dmap.preload()
1581 dmap.preload()
1582
1582
1583 use_rust = True
1583 use_rust = True
1584
1584
1585 allowed_matchers = (
1585 allowed_matchers = (
1586 matchmod.alwaysmatcher,
1586 matchmod.alwaysmatcher,
1587 matchmod.differencematcher,
1587 matchmod.differencematcher,
1588 matchmod.exactmatcher,
1588 matchmod.exactmatcher,
1589 matchmod.includematcher,
1589 matchmod.includematcher,
1590 matchmod.intersectionmatcher,
1590 matchmod.intersectionmatcher,
1591 matchmod.nevermatcher,
1591 matchmod.nevermatcher,
1592 matchmod.unionmatcher,
1592 matchmod.unionmatcher,
1593 )
1593 )
1594
1594
1595 if rustmod is None:
1595 if rustmod is None:
1596 use_rust = False
1596 use_rust = False
1597 elif self._checkcase:
1597 elif self._checkcase:
1598 # Case-insensitive filesystems are not handled yet
1598 # Case-insensitive filesystems are not handled yet
1599 use_rust = False
1599 use_rust = False
1600 elif subrepos:
1600 elif subrepos:
1601 use_rust = False
1601 use_rust = False
1602 elif not isinstance(match, allowed_matchers):
1602 elif not isinstance(match, allowed_matchers):
1603 # Some matchers have yet to be implemented
1603 # Some matchers have yet to be implemented
1604 use_rust = False
1604 use_rust = False
1605
1605
1606 # Get the time from the filesystem so we can disambiguate files that
1606 # Get the time from the filesystem so we can disambiguate files that
1607 # appear modified in the present or future.
1607 # appear modified in the present or future.
1608 try:
1608 try:
1609 mtime_boundary = timestamp.get_fs_now(self._opener)
1609 mtime_boundary = timestamp.get_fs_now(self._opener)
1610 except OSError:
1610 except OSError:
1611 # In largefiles or readonly context
1611 # In largefiles or readonly context
1612 mtime_boundary = None
1612 mtime_boundary = None
1613
1613
1614 if use_rust:
1614 if use_rust:
1615 try:
1615 try:
1616 res = self._rust_status(
1616 res = self._rust_status(
1617 match, listclean, listignored, listunknown
1617 match, listclean, listignored, listunknown
1618 )
1618 )
1619 return res + (mtime_boundary,)
1619 return res + (mtime_boundary,)
1620 except rustmod.FallbackError:
1620 except rustmod.FallbackError:
1621 pass
1621 pass
1622
1622
1623 def noop(f):
1623 def noop(f):
1624 pass
1624 pass
1625
1625
1626 dcontains = dmap.__contains__
1626 dcontains = dmap.__contains__
1627 dget = dmap.__getitem__
1627 dget = dmap.__getitem__
1628 ladd = lookup.append # aka "unsure"
1628 ladd = lookup.append # aka "unsure"
1629 madd = modified.append
1629 madd = modified.append
1630 aadd = added.append
1630 aadd = added.append
1631 uadd = unknown.append if listunknown else noop
1631 uadd = unknown.append if listunknown else noop
1632 iadd = ignored.append if listignored else noop
1632 iadd = ignored.append if listignored else noop
1633 radd = removed.append
1633 radd = removed.append
1634 dadd = deleted.append
1634 dadd = deleted.append
1635 cadd = clean.append if listclean else noop
1635 cadd = clean.append if listclean else noop
1636 mexact = match.exact
1636 mexact = match.exact
1637 dirignore = self._dirignore
1637 dirignore = self._dirignore
1638 checkexec = self._checkexec
1638 checkexec = self._checkexec
1639 checklink = self._checklink
1639 checklink = self._checklink
1640 copymap = self._map.copymap
1640 copymap = self._map.copymap
1641
1641
1642 # We need to do full walks when either
1642 # We need to do full walks when either
1643 # - we're listing all clean files, or
1643 # - we're listing all clean files, or
1644 # - match.traversedir does something, because match.traversedir should
1644 # - match.traversedir does something, because match.traversedir should
1645 # be called for every dir in the working dir
1645 # be called for every dir in the working dir
1646 full = listclean or match.traversedir is not None
1646 full = listclean or match.traversedir is not None
1647 for fn, st in self.walk(
1647 for fn, st in self.walk(
1648 match, subrepos, listunknown, listignored, full=full
1648 match, subrepos, listunknown, listignored, full=full
1649 ).items():
1649 ).items():
1650 if not dcontains(fn):
1650 if not dcontains(fn):
1651 if (listignored or mexact(fn)) and dirignore(fn):
1651 if (listignored or mexact(fn)) and dirignore(fn):
1652 if listignored:
1652 if listignored:
1653 iadd(fn)
1653 iadd(fn)
1654 else:
1654 else:
1655 uadd(fn)
1655 uadd(fn)
1656 continue
1656 continue
1657
1657
1658 t = dget(fn)
1658 t = dget(fn)
1659 mode = t.mode
1659 mode = t.mode
1660 size = t.size
1660 size = t.size
1661
1661
1662 if not st and t.tracked:
1662 if not st and t.tracked:
1663 dadd(fn)
1663 dadd(fn)
1664 elif t.p2_info:
1664 elif t.p2_info:
1665 madd(fn)
1665 madd(fn)
1666 elif t.added:
1666 elif t.added:
1667 aadd(fn)
1667 aadd(fn)
1668 elif t.removed:
1668 elif t.removed:
1669 radd(fn)
1669 radd(fn)
1670 elif t.tracked:
1670 elif t.tracked:
1671 if not checklink and t.has_fallback_symlink:
1671 if not checklink and t.has_fallback_symlink:
1672 # If the file system does not support symlink, the mode
1672 # If the file system does not support symlink, the mode
1673 # might not be correctly stored in the dirstate, so do not
1673 # might not be correctly stored in the dirstate, so do not
1674 # trust it.
1674 # trust it.
1675 ladd(fn)
1675 ladd(fn)
1676 elif not checkexec and t.has_fallback_exec:
1676 elif not checkexec and t.has_fallback_exec:
1677 # If the file system does not support exec bits, the mode
1677 # If the file system does not support exec bits, the mode
1678 # might not be correctly stored in the dirstate, so do not
1678 # might not be correctly stored in the dirstate, so do not
1679 # trust it.
1679 # trust it.
1680 ladd(fn)
1680 ladd(fn)
1681 elif (
1681 elif (
1682 size >= 0
1682 size >= 0
1683 and (
1683 and (
1684 (size != st.st_size and size != st.st_size & _rangemask)
1684 (size != st.st_size and size != st.st_size & _rangemask)
1685 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1685 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1686 )
1686 )
1687 or fn in copymap
1687 or fn in copymap
1688 ):
1688 ):
1689 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1689 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1690 # issue6456: Size returned may be longer due to
1690 # issue6456: Size returned may be longer due to
1691 # encryption on EXT-4 fscrypt, undecided.
1691 # encryption on EXT-4 fscrypt, undecided.
1692 ladd(fn)
1692 ladd(fn)
1693 else:
1693 else:
1694 madd(fn)
1694 madd(fn)
1695 elif not t.mtime_likely_equal_to(timestamp.mtime_of(st)):
1695 elif not t.mtime_likely_equal_to(timestamp.mtime_of(st)):
1696 # There might be a change in the future if for example the
1696 # There might be a change in the future if for example the
1697 # internal clock is off, but this is a case where the issues
1697 # internal clock is off, but this is a case where the issues
1698 # the user would face would be a lot worse and there is
1698 # the user would face would be a lot worse and there is
1699 # nothing we can really do.
1699 # nothing we can really do.
1700 ladd(fn)
1700 ladd(fn)
1701 elif listclean:
1701 elif listclean:
1702 cadd(fn)
1702 cadd(fn)
1703 status = scmutil.status(
1703 status = scmutil.status(
1704 modified, added, removed, deleted, unknown, ignored, clean
1704 modified, added, removed, deleted, unknown, ignored, clean
1705 )
1705 )
1706 return (lookup, status, mtime_boundary)
1706 return (lookup, status, mtime_boundary)
1707
1707
1708 def matches(self, match):
1708 def matches(self, match):
1709 """
1709 """
1710 return files in the dirstate (in whatever state) filtered by match
1710 return files in the dirstate (in whatever state) filtered by match
1711 """
1711 """
1712 dmap = self._map
1712 dmap = self._map
1713 if rustmod is not None:
1713 if rustmod is not None:
1714 dmap = self._map._map
1714 dmap = self._map._map
1715
1715
1716 if match.always():
1716 if match.always():
1717 return dmap.keys()
1717 return dmap.keys()
1718 files = match.files()
1718 files = match.files()
1719 if match.isexact():
1719 if match.isexact():
1720 # fast path -- filter the other way around, since typically files is
1720 # fast path -- filter the other way around, since typically files is
1721 # much smaller than dmap
1721 # much smaller than dmap
1722 return [f for f in files if f in dmap]
1722 return [f for f in files if f in dmap]
1723 if match.prefix() and all(fn in dmap for fn in files):
1723 if match.prefix() and all(fn in dmap for fn in files):
1724 # fast path -- all the values are known to be files, so just return
1724 # fast path -- all the values are known to be files, so just return
1725 # that
1725 # that
1726 return list(files)
1726 return list(files)
1727 return [f for f in dmap if match(f)]
1727 return [f for f in dmap if match(f)]
1728
1728
1729 def _actualfilename(self, tr):
1729 def _actualfilename(self, tr):
1730 if tr:
1730 if tr:
1731 return self._pendingfilename
1731 return self._pendingfilename
1732 else:
1732 else:
1733 return self._filename
1733 return self._filename
1734
1734
1735 def all_file_names(self):
1735 def all_file_names(self):
1736 """list all filename currently used by this dirstate
1736 """list all filename currently used by this dirstate
1737
1737
1738 This is only used to do `hg rollback` related backup in the transaction
1738 This is only used to do `hg rollback` related backup in the transaction
1739 """
1739 """
1740 if not self._opener.exists(self._filename):
1740 if not self._opener.exists(self._filename):
1741 # no data every written to disk yet
1741 # no data every written to disk yet
1742 return ()
1742 return ()
1743 elif self._use_dirstate_v2:
1743 elif self._use_dirstate_v2:
1744 return (
1744 return (
1745 self._filename,
1745 self._filename,
1746 self._map.docket.data_filename(),
1746 self._map.docket.data_filename(),
1747 )
1747 )
1748 else:
1748 else:
1749 return (self._filename,)
1749 return (self._filename,)
1750
1750
1751 def verify(self, m1, m2, p1, narrow_matcher=None):
1751 def verify(self, m1, m2, p1, narrow_matcher=None):
1752 """
1752 """
1753 check the dirstate contents against the parent manifest and yield errors
1753 check the dirstate contents against the parent manifest and yield errors
1754 """
1754 """
1755 missing_from_p1 = _(
1755 missing_from_p1 = _(
1756 b"%s marked as tracked in p1 (%s) but not in manifest1\n"
1756 b"%s marked as tracked in p1 (%s) but not in manifest1\n"
1757 )
1757 )
1758 unexpected_in_p1 = _(b"%s marked as added, but also in manifest1\n")
1758 unexpected_in_p1 = _(b"%s marked as added, but also in manifest1\n")
1759 missing_from_ps = _(
1759 missing_from_ps = _(
1760 b"%s marked as modified, but not in either manifest\n"
1760 b"%s marked as modified, but not in either manifest\n"
1761 )
1761 )
1762 missing_from_ds = _(
1762 missing_from_ds = _(
1763 b"%s in manifest1, but not marked as tracked in p1 (%s)\n"
1763 b"%s in manifest1, but not marked as tracked in p1 (%s)\n"
1764 )
1764 )
1765 for f, entry in self.items():
1765 for f, entry in self.items():
1766 if entry.p1_tracked:
1766 if entry.p1_tracked:
1767 if entry.modified and f not in m1 and f not in m2:
1767 if entry.modified and f not in m1 and f not in m2:
1768 yield missing_from_ps % f
1768 yield missing_from_ps % f
1769 elif f not in m1:
1769 elif f not in m1:
1770 yield missing_from_p1 % (f, node.short(p1))
1770 yield missing_from_p1 % (f, node.short(p1))
1771 if entry.added and f in m1:
1771 if entry.added and f in m1:
1772 yield unexpected_in_p1 % f
1772 yield unexpected_in_p1 % f
1773 for f in m1:
1773 for f in m1:
1774 if narrow_matcher is not None and not narrow_matcher(f):
1774 if narrow_matcher is not None and not narrow_matcher(f):
1775 continue
1775 continue
1776 entry = self.get_entry(f)
1776 entry = self.get_entry(f)
1777 if not entry.p1_tracked:
1777 if not entry.p1_tracked:
1778 yield missing_from_ds % (f, node.short(p1))
1778 yield missing_from_ds % (f, node.short(p1))
General Comments 0
You need to be logged in to leave comments. Login now