##// END OF EJS Templates
dirstate: make a conditionnal easier to read in `setparents`...
marmoute -
r48801:dd267f16 default
parent child Browse files
Show More
@@ -1,1618 +1,1616
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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import collections
10 import collections
11 import contextlib
11 import contextlib
12 import errno
12 import errno
13 import os
13 import os
14 import stat
14 import stat
15
15
16 from .i18n import _
16 from .i18n import _
17 from .pycompat import delattr
17 from .pycompat import delattr
18
18
19 from hgdemandimport import tracing
19 from hgdemandimport import tracing
20
20
21 from . import (
21 from . import (
22 dirstatemap,
22 dirstatemap,
23 encoding,
23 encoding,
24 error,
24 error,
25 match as matchmod,
25 match as matchmod,
26 pathutil,
26 pathutil,
27 policy,
27 policy,
28 pycompat,
28 pycompat,
29 scmutil,
29 scmutil,
30 sparse,
30 sparse,
31 util,
31 util,
32 )
32 )
33
33
34 from .interfaces import (
34 from .interfaces import (
35 dirstate as intdirstate,
35 dirstate as intdirstate,
36 util as interfaceutil,
36 util as interfaceutil,
37 )
37 )
38
38
39 parsers = policy.importmod('parsers')
39 parsers = policy.importmod('parsers')
40 rustmod = policy.importrust('dirstate')
40 rustmod = policy.importrust('dirstate')
41
41
42 SUPPORTS_DIRSTATE_V2 = rustmod is not None
42 SUPPORTS_DIRSTATE_V2 = rustmod is not None
43
43
44 propertycache = util.propertycache
44 propertycache = util.propertycache
45 filecache = scmutil.filecache
45 filecache = scmutil.filecache
46 _rangemask = dirstatemap.rangemask
46 _rangemask = dirstatemap.rangemask
47
47
48 DirstateItem = parsers.DirstateItem
48 DirstateItem = parsers.DirstateItem
49
49
50
50
51 class repocache(filecache):
51 class repocache(filecache):
52 """filecache for files in .hg/"""
52 """filecache for files in .hg/"""
53
53
54 def join(self, obj, fname):
54 def join(self, obj, fname):
55 return obj._opener.join(fname)
55 return obj._opener.join(fname)
56
56
57
57
58 class rootcache(filecache):
58 class rootcache(filecache):
59 """filecache for files in the repository root"""
59 """filecache for files in the repository root"""
60
60
61 def join(self, obj, fname):
61 def join(self, obj, fname):
62 return obj._join(fname)
62 return obj._join(fname)
63
63
64
64
65 def _getfsnow(vfs):
65 def _getfsnow(vfs):
66 '''Get "now" timestamp on filesystem'''
66 '''Get "now" timestamp on filesystem'''
67 tmpfd, tmpname = vfs.mkstemp()
67 tmpfd, tmpname = vfs.mkstemp()
68 try:
68 try:
69 return os.fstat(tmpfd)[stat.ST_MTIME]
69 return os.fstat(tmpfd)[stat.ST_MTIME]
70 finally:
70 finally:
71 os.close(tmpfd)
71 os.close(tmpfd)
72 vfs.unlink(tmpname)
72 vfs.unlink(tmpname)
73
73
74
74
75 def requires_parents_change(func):
75 def requires_parents_change(func):
76 def wrap(self, *args, **kwargs):
76 def wrap(self, *args, **kwargs):
77 if not self.pendingparentchange():
77 if not self.pendingparentchange():
78 msg = 'calling `%s` outside of a parentchange context'
78 msg = 'calling `%s` outside of a parentchange context'
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_no_parents_change(func):
86 def requires_no_parents_change(func):
87 def wrap(self, *args, **kwargs):
87 def wrap(self, *args, **kwargs):
88 if self.pendingparentchange():
88 if self.pendingparentchange():
89 msg = 'calling `%s` inside of a parentchange context'
89 msg = 'calling `%s` inside of a parentchange 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 wrap
94 return wrap
95
95
96
96
97 @interfaceutil.implementer(intdirstate.idirstate)
97 @interfaceutil.implementer(intdirstate.idirstate)
98 class dirstate(object):
98 class dirstate(object):
99 def __init__(
99 def __init__(
100 self,
100 self,
101 opener,
101 opener,
102 ui,
102 ui,
103 root,
103 root,
104 validate,
104 validate,
105 sparsematchfn,
105 sparsematchfn,
106 nodeconstants,
106 nodeconstants,
107 use_dirstate_v2,
107 use_dirstate_v2,
108 ):
108 ):
109 """Create a new dirstate object.
109 """Create a new dirstate object.
110
110
111 opener is an open()-like callable that can be used to open the
111 opener is an open()-like callable that can be used to open the
112 dirstate file; root is the root of the directory tracked by
112 dirstate file; root is the root of the directory tracked by
113 the dirstate.
113 the dirstate.
114 """
114 """
115 self._use_dirstate_v2 = use_dirstate_v2
115 self._use_dirstate_v2 = use_dirstate_v2
116 self._nodeconstants = nodeconstants
116 self._nodeconstants = nodeconstants
117 self._opener = opener
117 self._opener = opener
118 self._validate = validate
118 self._validate = validate
119 self._root = root
119 self._root = root
120 self._sparsematchfn = sparsematchfn
120 self._sparsematchfn = sparsematchfn
121 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
121 # ntpath.join(root, '') of Python 2.7.9 does not add sep if root is
122 # UNC path pointing to root share (issue4557)
122 # UNC path pointing to root share (issue4557)
123 self._rootdir = pathutil.normasprefix(root)
123 self._rootdir = pathutil.normasprefix(root)
124 self._dirty = False
124 self._dirty = False
125 self._lastnormaltime = 0
125 self._lastnormaltime = 0
126 self._ui = ui
126 self._ui = ui
127 self._filecache = {}
127 self._filecache = {}
128 self._parentwriters = 0
128 self._parentwriters = 0
129 self._filename = b'dirstate'
129 self._filename = b'dirstate'
130 self._pendingfilename = b'%s.pending' % self._filename
130 self._pendingfilename = b'%s.pending' % self._filename
131 self._plchangecallbacks = {}
131 self._plchangecallbacks = {}
132 self._origpl = None
132 self._origpl = None
133 self._updatedfiles = set()
133 self._updatedfiles = set()
134 self._mapcls = dirstatemap.dirstatemap
134 self._mapcls = dirstatemap.dirstatemap
135 # Access and cache cwd early, so we don't access it for the first time
135 # Access and cache cwd early, so we don't access it for the first time
136 # after a working-copy update caused it to not exist (accessing it then
136 # after a working-copy update caused it to not exist (accessing it then
137 # raises an exception).
137 # raises an exception).
138 self._cwd
138 self._cwd
139
139
140 def prefetch_parents(self):
140 def prefetch_parents(self):
141 """make sure the parents are loaded
141 """make sure the parents are loaded
142
142
143 Used to avoid a race condition.
143 Used to avoid a race condition.
144 """
144 """
145 self._pl
145 self._pl
146
146
147 @contextlib.contextmanager
147 @contextlib.contextmanager
148 def parentchange(self):
148 def parentchange(self):
149 """Context manager for handling dirstate parents.
149 """Context manager for handling dirstate parents.
150
150
151 If an exception occurs in the scope of the context manager,
151 If an exception occurs in the scope of the context manager,
152 the incoherent dirstate won't be written when wlock is
152 the incoherent dirstate won't be written when wlock is
153 released.
153 released.
154 """
154 """
155 self._parentwriters += 1
155 self._parentwriters += 1
156 yield
156 yield
157 # Typically we want the "undo" step of a context manager in a
157 # Typically we want the "undo" step of a context manager in a
158 # finally block so it happens even when an exception
158 # finally block so it happens even when an exception
159 # occurs. In this case, however, we only want to decrement
159 # occurs. In this case, however, we only want to decrement
160 # parentwriters if the code in the with statement exits
160 # parentwriters if the code in the with statement exits
161 # normally, so we don't have a try/finally here on purpose.
161 # normally, so we don't have a try/finally here on purpose.
162 self._parentwriters -= 1
162 self._parentwriters -= 1
163
163
164 def pendingparentchange(self):
164 def pendingparentchange(self):
165 """Returns true if the dirstate is in the middle of a set of changes
165 """Returns true if the dirstate is in the middle of a set of changes
166 that modify the dirstate parent.
166 that modify the dirstate parent.
167 """
167 """
168 return self._parentwriters > 0
168 return self._parentwriters > 0
169
169
170 @propertycache
170 @propertycache
171 def _map(self):
171 def _map(self):
172 """Return the dirstate contents (see documentation for dirstatemap)."""
172 """Return the dirstate contents (see documentation for dirstatemap)."""
173 self._map = self._mapcls(
173 self._map = self._mapcls(
174 self._ui,
174 self._ui,
175 self._opener,
175 self._opener,
176 self._root,
176 self._root,
177 self._nodeconstants,
177 self._nodeconstants,
178 self._use_dirstate_v2,
178 self._use_dirstate_v2,
179 )
179 )
180 return self._map
180 return self._map
181
181
182 @property
182 @property
183 def _sparsematcher(self):
183 def _sparsematcher(self):
184 """The matcher for the sparse checkout.
184 """The matcher for the sparse checkout.
185
185
186 The working directory may not include every file from a manifest. The
186 The working directory may not include every file from a manifest. The
187 matcher obtained by this property will match a path if it is to be
187 matcher obtained by this property will match a path if it is to be
188 included in the working directory.
188 included in the working directory.
189 """
189 """
190 # TODO there is potential to cache this property. For now, the matcher
190 # TODO there is potential to cache this property. For now, the matcher
191 # is resolved on every access. (But the called function does use a
191 # is resolved on every access. (But the called function does use a
192 # cache to keep the lookup fast.)
192 # cache to keep the lookup fast.)
193 return self._sparsematchfn()
193 return self._sparsematchfn()
194
194
195 @repocache(b'branch')
195 @repocache(b'branch')
196 def _branch(self):
196 def _branch(self):
197 try:
197 try:
198 return self._opener.read(b"branch").strip() or b"default"
198 return self._opener.read(b"branch").strip() or b"default"
199 except IOError as inst:
199 except IOError as inst:
200 if inst.errno != errno.ENOENT:
200 if inst.errno != errno.ENOENT:
201 raise
201 raise
202 return b"default"
202 return b"default"
203
203
204 @property
204 @property
205 def _pl(self):
205 def _pl(self):
206 return self._map.parents()
206 return self._map.parents()
207
207
208 def hasdir(self, d):
208 def hasdir(self, d):
209 return self._map.hastrackeddir(d)
209 return self._map.hastrackeddir(d)
210
210
211 @rootcache(b'.hgignore')
211 @rootcache(b'.hgignore')
212 def _ignore(self):
212 def _ignore(self):
213 files = self._ignorefiles()
213 files = self._ignorefiles()
214 if not files:
214 if not files:
215 return matchmod.never()
215 return matchmod.never()
216
216
217 pats = [b'include:%s' % f for f in files]
217 pats = [b'include:%s' % f for f in files]
218 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
218 return matchmod.match(self._root, b'', [], pats, warn=self._ui.warn)
219
219
220 @propertycache
220 @propertycache
221 def _slash(self):
221 def _slash(self):
222 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
222 return self._ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/'
223
223
224 @propertycache
224 @propertycache
225 def _checklink(self):
225 def _checklink(self):
226 return util.checklink(self._root)
226 return util.checklink(self._root)
227
227
228 @propertycache
228 @propertycache
229 def _checkexec(self):
229 def _checkexec(self):
230 return bool(util.checkexec(self._root))
230 return bool(util.checkexec(self._root))
231
231
232 @propertycache
232 @propertycache
233 def _checkcase(self):
233 def _checkcase(self):
234 return not util.fscasesensitive(self._join(b'.hg'))
234 return not util.fscasesensitive(self._join(b'.hg'))
235
235
236 def _join(self, f):
236 def _join(self, f):
237 # much faster than os.path.join()
237 # much faster than os.path.join()
238 # it's safe because f is always a relative path
238 # it's safe because f is always a relative path
239 return self._rootdir + f
239 return self._rootdir + f
240
240
241 def flagfunc(self, buildfallback):
241 def flagfunc(self, buildfallback):
242 if self._checklink and self._checkexec:
242 if self._checklink and self._checkexec:
243
243
244 def f(x):
244 def f(x):
245 try:
245 try:
246 st = os.lstat(self._join(x))
246 st = os.lstat(self._join(x))
247 if util.statislink(st):
247 if util.statislink(st):
248 return b'l'
248 return b'l'
249 if util.statisexec(st):
249 if util.statisexec(st):
250 return b'x'
250 return b'x'
251 except OSError:
251 except OSError:
252 pass
252 pass
253 return b''
253 return b''
254
254
255 return f
255 return f
256
256
257 fallback = buildfallback()
257 fallback = buildfallback()
258 if self._checklink:
258 if self._checklink:
259
259
260 def f(x):
260 def f(x):
261 if os.path.islink(self._join(x)):
261 if os.path.islink(self._join(x)):
262 return b'l'
262 return b'l'
263 if b'x' in fallback(x):
263 if b'x' in fallback(x):
264 return b'x'
264 return b'x'
265 return b''
265 return b''
266
266
267 return f
267 return f
268 if self._checkexec:
268 if self._checkexec:
269
269
270 def f(x):
270 def f(x):
271 if b'l' in fallback(x):
271 if b'l' in fallback(x):
272 return b'l'
272 return b'l'
273 if util.isexec(self._join(x)):
273 if util.isexec(self._join(x)):
274 return b'x'
274 return b'x'
275 return b''
275 return b''
276
276
277 return f
277 return f
278 else:
278 else:
279 return fallback
279 return fallback
280
280
281 @propertycache
281 @propertycache
282 def _cwd(self):
282 def _cwd(self):
283 # internal config: ui.forcecwd
283 # internal config: ui.forcecwd
284 forcecwd = self._ui.config(b'ui', b'forcecwd')
284 forcecwd = self._ui.config(b'ui', b'forcecwd')
285 if forcecwd:
285 if forcecwd:
286 return forcecwd
286 return forcecwd
287 return encoding.getcwd()
287 return encoding.getcwd()
288
288
289 def getcwd(self):
289 def getcwd(self):
290 """Return the path from which a canonical path is calculated.
290 """Return the path from which a canonical path is calculated.
291
291
292 This path should be used to resolve file patterns or to convert
292 This path should be used to resolve file patterns or to convert
293 canonical paths back to file paths for display. It shouldn't be
293 canonical paths back to file paths for display. It shouldn't be
294 used to get real file paths. Use vfs functions instead.
294 used to get real file paths. Use vfs functions instead.
295 """
295 """
296 cwd = self._cwd
296 cwd = self._cwd
297 if cwd == self._root:
297 if cwd == self._root:
298 return b''
298 return b''
299 # self._root ends with a path separator if self._root is '/' or 'C:\'
299 # self._root ends with a path separator if self._root is '/' or 'C:\'
300 rootsep = self._root
300 rootsep = self._root
301 if not util.endswithsep(rootsep):
301 if not util.endswithsep(rootsep):
302 rootsep += pycompat.ossep
302 rootsep += pycompat.ossep
303 if cwd.startswith(rootsep):
303 if cwd.startswith(rootsep):
304 return cwd[len(rootsep) :]
304 return cwd[len(rootsep) :]
305 else:
305 else:
306 # we're outside the repo. return an absolute path.
306 # we're outside the repo. return an absolute path.
307 return cwd
307 return cwd
308
308
309 def pathto(self, f, cwd=None):
309 def pathto(self, f, cwd=None):
310 if cwd is None:
310 if cwd is None:
311 cwd = self.getcwd()
311 cwd = self.getcwd()
312 path = util.pathto(self._root, cwd, f)
312 path = util.pathto(self._root, cwd, f)
313 if self._slash:
313 if self._slash:
314 return util.pconvert(path)
314 return util.pconvert(path)
315 return path
315 return path
316
316
317 def __getitem__(self, key):
317 def __getitem__(self, key):
318 """Return the current state of key (a filename) in the dirstate.
318 """Return the current state of key (a filename) in the dirstate.
319
319
320 States are:
320 States are:
321 n normal
321 n normal
322 m needs merging
322 m needs merging
323 r marked for removal
323 r marked for removal
324 a marked for addition
324 a marked for addition
325 ? not tracked
325 ? not tracked
326
326
327 XXX The "state" is a bit obscure to be in the "public" API. we should
327 XXX The "state" is a bit obscure to be in the "public" API. we should
328 consider migrating all user of this to going through the dirstate entry
328 consider migrating all user of this to going through the dirstate entry
329 instead.
329 instead.
330 """
330 """
331 entry = self._map.get(key)
331 entry = self._map.get(key)
332 if entry is not None:
332 if entry is not None:
333 return entry.state
333 return entry.state
334 return b'?'
334 return b'?'
335
335
336 def __contains__(self, key):
336 def __contains__(self, key):
337 return key in self._map
337 return key in self._map
338
338
339 def __iter__(self):
339 def __iter__(self):
340 return iter(sorted(self._map))
340 return iter(sorted(self._map))
341
341
342 def items(self):
342 def items(self):
343 return pycompat.iteritems(self._map)
343 return pycompat.iteritems(self._map)
344
344
345 iteritems = items
345 iteritems = items
346
346
347 def directories(self):
347 def directories(self):
348 return self._map.directories()
348 return self._map.directories()
349
349
350 def parents(self):
350 def parents(self):
351 return [self._validate(p) for p in self._pl]
351 return [self._validate(p) for p in self._pl]
352
352
353 def p1(self):
353 def p1(self):
354 return self._validate(self._pl[0])
354 return self._validate(self._pl[0])
355
355
356 def p2(self):
356 def p2(self):
357 return self._validate(self._pl[1])
357 return self._validate(self._pl[1])
358
358
359 @property
359 @property
360 def in_merge(self):
360 def in_merge(self):
361 """True if a merge is in progress"""
361 """True if a merge is in progress"""
362 return self._pl[1] != self._nodeconstants.nullid
362 return self._pl[1] != self._nodeconstants.nullid
363
363
364 def branch(self):
364 def branch(self):
365 return encoding.tolocal(self._branch)
365 return encoding.tolocal(self._branch)
366
366
367 def setparents(self, p1, p2=None):
367 def setparents(self, p1, p2=None):
368 """Set dirstate parents to p1 and p2.
368 """Set dirstate parents to p1 and p2.
369
369
370 When moving from two parents to one, "merged" entries a
370 When moving from two parents to one, "merged" entries a
371 adjusted to normal and previous copy records discarded and
371 adjusted to normal and previous copy records discarded and
372 returned by the call.
372 returned by the call.
373
373
374 See localrepo.setparents()
374 See localrepo.setparents()
375 """
375 """
376 if p2 is None:
376 if p2 is None:
377 p2 = self._nodeconstants.nullid
377 p2 = self._nodeconstants.nullid
378 if self._parentwriters == 0:
378 if self._parentwriters == 0:
379 raise ValueError(
379 raise ValueError(
380 b"cannot set dirstate parent outside of "
380 b"cannot set dirstate parent outside of "
381 b"dirstate.parentchange context manager"
381 b"dirstate.parentchange context manager"
382 )
382 )
383
383
384 self._dirty = True
384 self._dirty = True
385 oldp2 = self._pl[1]
385 oldp2 = self._pl[1]
386 if self._origpl is None:
386 if self._origpl is None:
387 self._origpl = self._pl
387 self._origpl = self._pl
388 self._map.setparents(p1, p2)
388 self._map.setparents(p1, p2)
389 copies = {}
389 copies = {}
390 if (
390 nullid = self._nodeconstants.nullid
391 oldp2 != self._nodeconstants.nullid
391 if oldp2 != nullid and p2 == nullid:
392 and p2 == self._nodeconstants.nullid
393 ):
394 candidatefiles = self._map.non_normal_or_other_parent_paths()
392 candidatefiles = self._map.non_normal_or_other_parent_paths()
395
393
396 for f in candidatefiles:
394 for f in candidatefiles:
397 s = self._map.get(f)
395 s = self._map.get(f)
398 if s is None:
396 if s is None:
399 continue
397 continue
400
398
401 # Discard "merged" markers when moving away from a merge state
399 # Discard "merged" markers when moving away from a merge state
402 if s.merged:
400 if s.merged:
403 source = self._map.copymap.get(f)
401 source = self._map.copymap.get(f)
404 if source:
402 if source:
405 copies[f] = source
403 copies[f] = source
406 self._normallookup(f)
404 self._normallookup(f)
407 # Also fix up otherparent markers
405 # Also fix up otherparent markers
408 elif s.from_p2:
406 elif s.from_p2:
409 source = self._map.copymap.get(f)
407 source = self._map.copymap.get(f)
410 if source:
408 if source:
411 copies[f] = source
409 copies[f] = source
412 self._check_new_tracked_filename(f)
410 self._check_new_tracked_filename(f)
413 self._updatedfiles.add(f)
411 self._updatedfiles.add(f)
414 self._map.reset_state(
412 self._map.reset_state(
415 f,
413 f,
416 p1_tracked=False,
414 p1_tracked=False,
417 wc_tracked=True,
415 wc_tracked=True,
418 )
416 )
419 return copies
417 return copies
420
418
421 def setbranch(self, branch):
419 def setbranch(self, branch):
422 self.__class__._branch.set(self, encoding.fromlocal(branch))
420 self.__class__._branch.set(self, encoding.fromlocal(branch))
423 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
421 f = self._opener(b'branch', b'w', atomictemp=True, checkambig=True)
424 try:
422 try:
425 f.write(self._branch + b'\n')
423 f.write(self._branch + b'\n')
426 f.close()
424 f.close()
427
425
428 # make sure filecache has the correct stat info for _branch after
426 # make sure filecache has the correct stat info for _branch after
429 # replacing the underlying file
427 # replacing the underlying file
430 ce = self._filecache[b'_branch']
428 ce = self._filecache[b'_branch']
431 if ce:
429 if ce:
432 ce.refresh()
430 ce.refresh()
433 except: # re-raises
431 except: # re-raises
434 f.discard()
432 f.discard()
435 raise
433 raise
436
434
437 def invalidate(self):
435 def invalidate(self):
438 """Causes the next access to reread the dirstate.
436 """Causes the next access to reread the dirstate.
439
437
440 This is different from localrepo.invalidatedirstate() because it always
438 This is different from localrepo.invalidatedirstate() because it always
441 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
439 rereads the dirstate. Use localrepo.invalidatedirstate() if you want to
442 check whether the dirstate has changed before rereading it."""
440 check whether the dirstate has changed before rereading it."""
443
441
444 for a in ("_map", "_branch", "_ignore"):
442 for a in ("_map", "_branch", "_ignore"):
445 if a in self.__dict__:
443 if a in self.__dict__:
446 delattr(self, a)
444 delattr(self, a)
447 self._lastnormaltime = 0
445 self._lastnormaltime = 0
448 self._dirty = False
446 self._dirty = False
449 self._updatedfiles.clear()
447 self._updatedfiles.clear()
450 self._parentwriters = 0
448 self._parentwriters = 0
451 self._origpl = None
449 self._origpl = None
452
450
453 def copy(self, source, dest):
451 def copy(self, source, dest):
454 """Mark dest as a copy of source. Unmark dest if source is None."""
452 """Mark dest as a copy of source. Unmark dest if source is None."""
455 if source == dest:
453 if source == dest:
456 return
454 return
457 self._dirty = True
455 self._dirty = True
458 if source is not None:
456 if source is not None:
459 self._map.copymap[dest] = source
457 self._map.copymap[dest] = source
460 self._updatedfiles.add(source)
458 self._updatedfiles.add(source)
461 self._updatedfiles.add(dest)
459 self._updatedfiles.add(dest)
462 elif self._map.copymap.pop(dest, None):
460 elif self._map.copymap.pop(dest, None):
463 self._updatedfiles.add(dest)
461 self._updatedfiles.add(dest)
464
462
465 def copied(self, file):
463 def copied(self, file):
466 return self._map.copymap.get(file, None)
464 return self._map.copymap.get(file, None)
467
465
468 def copies(self):
466 def copies(self):
469 return self._map.copymap
467 return self._map.copymap
470
468
471 @requires_no_parents_change
469 @requires_no_parents_change
472 def set_tracked(self, filename):
470 def set_tracked(self, filename):
473 """a "public" method for generic code to mark a file as tracked
471 """a "public" method for generic code to mark a file as tracked
474
472
475 This function is to be called outside of "update/merge" case. For
473 This function is to be called outside of "update/merge" case. For
476 example by a command like `hg add X`.
474 example by a command like `hg add X`.
477
475
478 return True the file was previously untracked, False otherwise.
476 return True the file was previously untracked, False otherwise.
479 """
477 """
480 self._dirty = True
478 self._dirty = True
481 self._updatedfiles.add(filename)
479 self._updatedfiles.add(filename)
482 entry = self._map.get(filename)
480 entry = self._map.get(filename)
483 if entry is None:
481 if entry is None:
484 self._check_new_tracked_filename(filename)
482 self._check_new_tracked_filename(filename)
485 self._map.addfile(filename, added=True)
483 self._map.addfile(filename, added=True)
486 return True
484 return True
487 elif not entry.tracked:
485 elif not entry.tracked:
488 self._normallookup(filename)
486 self._normallookup(filename)
489 return True
487 return True
490 # XXX This is probably overkill for more case, but we need this to
488 # XXX This is probably overkill for more case, but we need this to
491 # fully replace the `normallookup` call with `set_tracked` one.
489 # fully replace the `normallookup` call with `set_tracked` one.
492 # Consider smoothing this in the future.
490 # Consider smoothing this in the future.
493 self.set_possibly_dirty(filename)
491 self.set_possibly_dirty(filename)
494 return False
492 return False
495
493
496 @requires_no_parents_change
494 @requires_no_parents_change
497 def set_untracked(self, filename):
495 def set_untracked(self, filename):
498 """a "public" method for generic code to mark a file as untracked
496 """a "public" method for generic code to mark a file as untracked
499
497
500 This function is to be called outside of "update/merge" case. For
498 This function is to be called outside of "update/merge" case. For
501 example by a command like `hg remove X`.
499 example by a command like `hg remove X`.
502
500
503 return True the file was previously tracked, False otherwise.
501 return True the file was previously tracked, False otherwise.
504 """
502 """
505 ret = self._map.set_untracked(filename)
503 ret = self._map.set_untracked(filename)
506 if ret:
504 if ret:
507 self._dirty = True
505 self._dirty = True
508 self._updatedfiles.add(filename)
506 self._updatedfiles.add(filename)
509 return ret
507 return ret
510
508
511 @requires_no_parents_change
509 @requires_no_parents_change
512 def set_clean(self, filename, parentfiledata=None):
510 def set_clean(self, filename, parentfiledata=None):
513 """record that the current state of the file on disk is known to be clean"""
511 """record that the current state of the file on disk is known to be clean"""
514 self._dirty = True
512 self._dirty = True
515 self._updatedfiles.add(filename)
513 self._updatedfiles.add(filename)
516 if parentfiledata:
514 if parentfiledata:
517 (mode, size, mtime) = parentfiledata
515 (mode, size, mtime) = parentfiledata
518 else:
516 else:
519 (mode, size, mtime) = self._get_filedata(filename)
517 (mode, size, mtime) = self._get_filedata(filename)
520 if not self._map[filename].tracked:
518 if not self._map[filename].tracked:
521 self._check_new_tracked_filename(filename)
519 self._check_new_tracked_filename(filename)
522 self._map.set_clean(filename, mode, size, mtime)
520 self._map.set_clean(filename, mode, size, mtime)
523 if mtime > self._lastnormaltime:
521 if mtime > self._lastnormaltime:
524 # Remember the most recent modification timeslot for status(),
522 # Remember the most recent modification timeslot for status(),
525 # to make sure we won't miss future size-preserving file content
523 # to make sure we won't miss future size-preserving file content
526 # modifications that happen within the same timeslot.
524 # modifications that happen within the same timeslot.
527 self._lastnormaltime = mtime
525 self._lastnormaltime = mtime
528
526
529 @requires_no_parents_change
527 @requires_no_parents_change
530 def set_possibly_dirty(self, filename):
528 def set_possibly_dirty(self, filename):
531 """record that the current state of the file on disk is unknown"""
529 """record that the current state of the file on disk is unknown"""
532 self._dirty = True
530 self._dirty = True
533 self._updatedfiles.add(filename)
531 self._updatedfiles.add(filename)
534 self._map.set_possibly_dirty(filename)
532 self._map.set_possibly_dirty(filename)
535
533
536 @requires_parents_change
534 @requires_parents_change
537 def update_file_p1(
535 def update_file_p1(
538 self,
536 self,
539 filename,
537 filename,
540 p1_tracked,
538 p1_tracked,
541 ):
539 ):
542 """Set a file as tracked in the parent (or not)
540 """Set a file as tracked in the parent (or not)
543
541
544 This is to be called when adjust the dirstate to a new parent after an history
542 This is to be called when adjust the dirstate to a new parent after an history
545 rewriting operation.
543 rewriting operation.
546
544
547 It should not be called during a merge (p2 != nullid) and only within
545 It should not be called during a merge (p2 != nullid) and only within
548 a `with dirstate.parentchange():` context.
546 a `with dirstate.parentchange():` context.
549 """
547 """
550 if self.in_merge:
548 if self.in_merge:
551 msg = b'update_file_reference should not be called when merging'
549 msg = b'update_file_reference should not be called when merging'
552 raise error.ProgrammingError(msg)
550 raise error.ProgrammingError(msg)
553 entry = self._map.get(filename)
551 entry = self._map.get(filename)
554 if entry is None:
552 if entry is None:
555 wc_tracked = False
553 wc_tracked = False
556 else:
554 else:
557 wc_tracked = entry.tracked
555 wc_tracked = entry.tracked
558 possibly_dirty = False
556 possibly_dirty = False
559 if p1_tracked and wc_tracked:
557 if p1_tracked and wc_tracked:
560 # the underlying reference might have changed, we will have to
558 # the underlying reference might have changed, we will have to
561 # check it.
559 # check it.
562 possibly_dirty = True
560 possibly_dirty = True
563 elif not (p1_tracked or wc_tracked):
561 elif not (p1_tracked or wc_tracked):
564 # the file is no longer relevant to anyone
562 # the file is no longer relevant to anyone
565 self._drop(filename)
563 self._drop(filename)
566 elif (not p1_tracked) and wc_tracked:
564 elif (not p1_tracked) and wc_tracked:
567 if entry is not None and entry.added:
565 if entry is not None and entry.added:
568 return # avoid dropping copy information (maybe?)
566 return # avoid dropping copy information (maybe?)
569 elif p1_tracked and not wc_tracked:
567 elif p1_tracked and not wc_tracked:
570 pass
568 pass
571 else:
569 else:
572 assert False, 'unreachable'
570 assert False, 'unreachable'
573
571
574 # this mean we are doing call for file we do not really care about the
572 # this mean we are doing call for file we do not really care about the
575 # data (eg: added or removed), however this should be a minor overhead
573 # data (eg: added or removed), however this should be a minor overhead
576 # compared to the overall update process calling this.
574 # compared to the overall update process calling this.
577 parentfiledata = None
575 parentfiledata = None
578 if wc_tracked:
576 if wc_tracked:
579 parentfiledata = self._get_filedata(filename)
577 parentfiledata = self._get_filedata(filename)
580
578
581 self._updatedfiles.add(filename)
579 self._updatedfiles.add(filename)
582 self._map.reset_state(
580 self._map.reset_state(
583 filename,
581 filename,
584 wc_tracked,
582 wc_tracked,
585 p1_tracked,
583 p1_tracked,
586 possibly_dirty=possibly_dirty,
584 possibly_dirty=possibly_dirty,
587 parentfiledata=parentfiledata,
585 parentfiledata=parentfiledata,
588 )
586 )
589 if (
587 if (
590 parentfiledata is not None
588 parentfiledata is not None
591 and parentfiledata[2] > self._lastnormaltime
589 and parentfiledata[2] > self._lastnormaltime
592 ):
590 ):
593 # Remember the most recent modification timeslot for status(),
591 # Remember the most recent modification timeslot for status(),
594 # to make sure we won't miss future size-preserving file content
592 # to make sure we won't miss future size-preserving file content
595 # modifications that happen within the same timeslot.
593 # modifications that happen within the same timeslot.
596 self._lastnormaltime = parentfiledata[2]
594 self._lastnormaltime = parentfiledata[2]
597
595
598 @requires_parents_change
596 @requires_parents_change
599 def update_file(
597 def update_file(
600 self,
598 self,
601 filename,
599 filename,
602 wc_tracked,
600 wc_tracked,
603 p1_tracked,
601 p1_tracked,
604 p2_tracked=False,
602 p2_tracked=False,
605 merged=False,
603 merged=False,
606 clean_p1=False,
604 clean_p1=False,
607 clean_p2=False,
605 clean_p2=False,
608 possibly_dirty=False,
606 possibly_dirty=False,
609 parentfiledata=None,
607 parentfiledata=None,
610 ):
608 ):
611 """update the information about a file in the dirstate
609 """update the information about a file in the dirstate
612
610
613 This is to be called when the direstates parent changes to keep track
611 This is to be called when the direstates parent changes to keep track
614 of what is the file situation in regards to the working copy and its parent.
612 of what is the file situation in regards to the working copy and its parent.
615
613
616 This function must be called within a `dirstate.parentchange` context.
614 This function must be called within a `dirstate.parentchange` context.
617
615
618 note: the API is at an early stage and we might need to adjust it
616 note: the API is at an early stage and we might need to adjust it
619 depending of what information ends up being relevant and useful to
617 depending of what information ends up being relevant and useful to
620 other processing.
618 other processing.
621 """
619 """
622 if merged and (clean_p1 or clean_p2):
620 if merged and (clean_p1 or clean_p2):
623 msg = b'`merged` argument incompatible with `clean_p1`/`clean_p2`'
621 msg = b'`merged` argument incompatible with `clean_p1`/`clean_p2`'
624 raise error.ProgrammingError(msg)
622 raise error.ProgrammingError(msg)
625
623
626 # note: I do not think we need to double check name clash here since we
624 # note: I do not think we need to double check name clash here since we
627 # are in a update/merge case that should already have taken care of
625 # are in a update/merge case that should already have taken care of
628 # this. The test agrees
626 # this. The test agrees
629
627
630 self._dirty = True
628 self._dirty = True
631 self._updatedfiles.add(filename)
629 self._updatedfiles.add(filename)
632
630
633 need_parent_file_data = (
631 need_parent_file_data = (
634 not (possibly_dirty or clean_p2 or merged)
632 not (possibly_dirty or clean_p2 or merged)
635 and wc_tracked
633 and wc_tracked
636 and p1_tracked
634 and p1_tracked
637 )
635 )
638
636
639 # this mean we are doing call for file we do not really care about the
637 # this mean we are doing call for file we do not really care about the
640 # data (eg: added or removed), however this should be a minor overhead
638 # data (eg: added or removed), however this should be a minor overhead
641 # compared to the overall update process calling this.
639 # compared to the overall update process calling this.
642 if need_parent_file_data:
640 if need_parent_file_data:
643 if parentfiledata is None:
641 if parentfiledata is None:
644 parentfiledata = self._get_filedata(filename)
642 parentfiledata = self._get_filedata(filename)
645 mtime = parentfiledata[2]
643 mtime = parentfiledata[2]
646
644
647 if mtime > self._lastnormaltime:
645 if mtime > self._lastnormaltime:
648 # Remember the most recent modification timeslot for
646 # Remember the most recent modification timeslot for
649 # status(), to make sure we won't miss future
647 # status(), to make sure we won't miss future
650 # size-preserving file content modifications that happen
648 # size-preserving file content modifications that happen
651 # within the same timeslot.
649 # within the same timeslot.
652 self._lastnormaltime = mtime
650 self._lastnormaltime = mtime
653
651
654 self._map.reset_state(
652 self._map.reset_state(
655 filename,
653 filename,
656 wc_tracked,
654 wc_tracked,
657 p1_tracked,
655 p1_tracked,
658 p2_tracked=p2_tracked,
656 p2_tracked=p2_tracked,
659 merged=merged,
657 merged=merged,
660 clean_p1=clean_p1,
658 clean_p1=clean_p1,
661 clean_p2=clean_p2,
659 clean_p2=clean_p2,
662 possibly_dirty=possibly_dirty,
660 possibly_dirty=possibly_dirty,
663 parentfiledata=parentfiledata,
661 parentfiledata=parentfiledata,
664 )
662 )
665 if (
663 if (
666 parentfiledata is not None
664 parentfiledata is not None
667 and parentfiledata[2] > self._lastnormaltime
665 and parentfiledata[2] > self._lastnormaltime
668 ):
666 ):
669 # Remember the most recent modification timeslot for status(),
667 # Remember the most recent modification timeslot for status(),
670 # to make sure we won't miss future size-preserving file content
668 # to make sure we won't miss future size-preserving file content
671 # modifications that happen within the same timeslot.
669 # modifications that happen within the same timeslot.
672 self._lastnormaltime = parentfiledata[2]
670 self._lastnormaltime = parentfiledata[2]
673
671
674 def _addpath(
672 def _addpath(
675 self,
673 self,
676 f,
674 f,
677 mode=0,
675 mode=0,
678 size=None,
676 size=None,
679 mtime=None,
677 mtime=None,
680 added=False,
678 added=False,
681 merged=False,
679 merged=False,
682 from_p2=False,
680 from_p2=False,
683 possibly_dirty=False,
681 possibly_dirty=False,
684 ):
682 ):
685 entry = self._map.get(f)
683 entry = self._map.get(f)
686 if added or entry is not None and not entry.tracked:
684 if added or entry is not None and not entry.tracked:
687 self._check_new_tracked_filename(f)
685 self._check_new_tracked_filename(f)
688 self._dirty = True
686 self._dirty = True
689 self._updatedfiles.add(f)
687 self._updatedfiles.add(f)
690 self._map.addfile(
688 self._map.addfile(
691 f,
689 f,
692 mode=mode,
690 mode=mode,
693 size=size,
691 size=size,
694 mtime=mtime,
692 mtime=mtime,
695 added=added,
693 added=added,
696 merged=merged,
694 merged=merged,
697 from_p2=from_p2,
695 from_p2=from_p2,
698 possibly_dirty=possibly_dirty,
696 possibly_dirty=possibly_dirty,
699 )
697 )
700
698
701 def _check_new_tracked_filename(self, filename):
699 def _check_new_tracked_filename(self, filename):
702 scmutil.checkfilename(filename)
700 scmutil.checkfilename(filename)
703 if self._map.hastrackeddir(filename):
701 if self._map.hastrackeddir(filename):
704 msg = _(b'directory %r already in dirstate')
702 msg = _(b'directory %r already in dirstate')
705 msg %= pycompat.bytestr(filename)
703 msg %= pycompat.bytestr(filename)
706 raise error.Abort(msg)
704 raise error.Abort(msg)
707 # shadows
705 # shadows
708 for d in pathutil.finddirs(filename):
706 for d in pathutil.finddirs(filename):
709 if self._map.hastrackeddir(d):
707 if self._map.hastrackeddir(d):
710 break
708 break
711 entry = self._map.get(d)
709 entry = self._map.get(d)
712 if entry is not None and not entry.removed:
710 if entry is not None and not entry.removed:
713 msg = _(b'file %r in dirstate clashes with %r')
711 msg = _(b'file %r in dirstate clashes with %r')
714 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
712 msg %= (pycompat.bytestr(d), pycompat.bytestr(filename))
715 raise error.Abort(msg)
713 raise error.Abort(msg)
716
714
717 def _get_filedata(self, filename):
715 def _get_filedata(self, filename):
718 """returns"""
716 """returns"""
719 s = os.lstat(self._join(filename))
717 s = os.lstat(self._join(filename))
720 mode = s.st_mode
718 mode = s.st_mode
721 size = s.st_size
719 size = s.st_size
722 mtime = s[stat.ST_MTIME]
720 mtime = s[stat.ST_MTIME]
723 return (mode, size, mtime)
721 return (mode, size, mtime)
724
722
725 def _normallookup(self, f):
723 def _normallookup(self, f):
726 '''Mark a file normal, but possibly dirty.'''
724 '''Mark a file normal, but possibly dirty.'''
727 if self.in_merge:
725 if self.in_merge:
728 # if there is a merge going on and the file was either
726 # if there is a merge going on and the file was either
729 # "merged" or coming from other parent (-2) before
727 # "merged" or coming from other parent (-2) before
730 # being removed, restore that state.
728 # being removed, restore that state.
731 entry = self._map.get(f)
729 entry = self._map.get(f)
732 if entry is not None:
730 if entry is not None:
733 # XXX this should probably be dealt with a a lower level
731 # XXX this should probably be dealt with a a lower level
734 # (see `merged_removed` and `from_p2_removed`)
732 # (see `merged_removed` and `from_p2_removed`)
735 if entry.merged_removed or entry.from_p2_removed:
733 if entry.merged_removed or entry.from_p2_removed:
736 source = self._map.copymap.get(f)
734 source = self._map.copymap.get(f)
737 self._addpath(f, from_p2=True)
735 self._addpath(f, from_p2=True)
738 self._map.copymap.pop(f, None)
736 self._map.copymap.pop(f, None)
739 if source is not None:
737 if source is not None:
740 self.copy(source, f)
738 self.copy(source, f)
741 return
739 return
742 elif entry.merged or entry.from_p2:
740 elif entry.merged or entry.from_p2:
743 return
741 return
744 self._addpath(f, possibly_dirty=True)
742 self._addpath(f, possibly_dirty=True)
745 self._map.copymap.pop(f, None)
743 self._map.copymap.pop(f, None)
746
744
747 def _drop(self, filename):
745 def _drop(self, filename):
748 """internal function to drop a file from the dirstate"""
746 """internal function to drop a file from the dirstate"""
749 if self._map.dropfile(filename):
747 if self._map.dropfile(filename):
750 self._dirty = True
748 self._dirty = True
751 self._updatedfiles.add(filename)
749 self._updatedfiles.add(filename)
752
750
753 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
751 def _discoverpath(self, path, normed, ignoremissing, exists, storemap):
754 if exists is None:
752 if exists is None:
755 exists = os.path.lexists(os.path.join(self._root, path))
753 exists = os.path.lexists(os.path.join(self._root, path))
756 if not exists:
754 if not exists:
757 # Maybe a path component exists
755 # Maybe a path component exists
758 if not ignoremissing and b'/' in path:
756 if not ignoremissing and b'/' in path:
759 d, f = path.rsplit(b'/', 1)
757 d, f = path.rsplit(b'/', 1)
760 d = self._normalize(d, False, ignoremissing, None)
758 d = self._normalize(d, False, ignoremissing, None)
761 folded = d + b"/" + f
759 folded = d + b"/" + f
762 else:
760 else:
763 # No path components, preserve original case
761 # No path components, preserve original case
764 folded = path
762 folded = path
765 else:
763 else:
766 # recursively normalize leading directory components
764 # recursively normalize leading directory components
767 # against dirstate
765 # against dirstate
768 if b'/' in normed:
766 if b'/' in normed:
769 d, f = normed.rsplit(b'/', 1)
767 d, f = normed.rsplit(b'/', 1)
770 d = self._normalize(d, False, ignoremissing, True)
768 d = self._normalize(d, False, ignoremissing, True)
771 r = self._root + b"/" + d
769 r = self._root + b"/" + d
772 folded = d + b"/" + util.fspath(f, r)
770 folded = d + b"/" + util.fspath(f, r)
773 else:
771 else:
774 folded = util.fspath(normed, self._root)
772 folded = util.fspath(normed, self._root)
775 storemap[normed] = folded
773 storemap[normed] = folded
776
774
777 return folded
775 return folded
778
776
779 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
777 def _normalizefile(self, path, isknown, ignoremissing=False, exists=None):
780 normed = util.normcase(path)
778 normed = util.normcase(path)
781 folded = self._map.filefoldmap.get(normed, None)
779 folded = self._map.filefoldmap.get(normed, None)
782 if folded is None:
780 if folded is None:
783 if isknown:
781 if isknown:
784 folded = path
782 folded = path
785 else:
783 else:
786 folded = self._discoverpath(
784 folded = self._discoverpath(
787 path, normed, ignoremissing, exists, self._map.filefoldmap
785 path, normed, ignoremissing, exists, self._map.filefoldmap
788 )
786 )
789 return folded
787 return folded
790
788
791 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
789 def _normalize(self, path, isknown, ignoremissing=False, exists=None):
792 normed = util.normcase(path)
790 normed = util.normcase(path)
793 folded = self._map.filefoldmap.get(normed, None)
791 folded = self._map.filefoldmap.get(normed, None)
794 if folded is None:
792 if folded is None:
795 folded = self._map.dirfoldmap.get(normed, None)
793 folded = self._map.dirfoldmap.get(normed, None)
796 if folded is None:
794 if folded is None:
797 if isknown:
795 if isknown:
798 folded = path
796 folded = path
799 else:
797 else:
800 # store discovered result in dirfoldmap so that future
798 # store discovered result in dirfoldmap so that future
801 # normalizefile calls don't start matching directories
799 # normalizefile calls don't start matching directories
802 folded = self._discoverpath(
800 folded = self._discoverpath(
803 path, normed, ignoremissing, exists, self._map.dirfoldmap
801 path, normed, ignoremissing, exists, self._map.dirfoldmap
804 )
802 )
805 return folded
803 return folded
806
804
807 def normalize(self, path, isknown=False, ignoremissing=False):
805 def normalize(self, path, isknown=False, ignoremissing=False):
808 """
806 """
809 normalize the case of a pathname when on a casefolding filesystem
807 normalize the case of a pathname when on a casefolding filesystem
810
808
811 isknown specifies whether the filename came from walking the
809 isknown specifies whether the filename came from walking the
812 disk, to avoid extra filesystem access.
810 disk, to avoid extra filesystem access.
813
811
814 If ignoremissing is True, missing path are returned
812 If ignoremissing is True, missing path are returned
815 unchanged. Otherwise, we try harder to normalize possibly
813 unchanged. Otherwise, we try harder to normalize possibly
816 existing path components.
814 existing path components.
817
815
818 The normalized case is determined based on the following precedence:
816 The normalized case is determined based on the following precedence:
819
817
820 - version of name already stored in the dirstate
818 - version of name already stored in the dirstate
821 - version of name stored on disk
819 - version of name stored on disk
822 - version provided via command arguments
820 - version provided via command arguments
823 """
821 """
824
822
825 if self._checkcase:
823 if self._checkcase:
826 return self._normalize(path, isknown, ignoremissing)
824 return self._normalize(path, isknown, ignoremissing)
827 return path
825 return path
828
826
829 def clear(self):
827 def clear(self):
830 self._map.clear()
828 self._map.clear()
831 self._lastnormaltime = 0
829 self._lastnormaltime = 0
832 self._updatedfiles.clear()
830 self._updatedfiles.clear()
833 self._dirty = True
831 self._dirty = True
834
832
835 def rebuild(self, parent, allfiles, changedfiles=None):
833 def rebuild(self, parent, allfiles, changedfiles=None):
836 if changedfiles is None:
834 if changedfiles is None:
837 # Rebuild entire dirstate
835 # Rebuild entire dirstate
838 to_lookup = allfiles
836 to_lookup = allfiles
839 to_drop = []
837 to_drop = []
840 lastnormaltime = self._lastnormaltime
838 lastnormaltime = self._lastnormaltime
841 self.clear()
839 self.clear()
842 self._lastnormaltime = lastnormaltime
840 self._lastnormaltime = lastnormaltime
843 elif len(changedfiles) < 10:
841 elif len(changedfiles) < 10:
844 # Avoid turning allfiles into a set, which can be expensive if it's
842 # Avoid turning allfiles into a set, which can be expensive if it's
845 # large.
843 # large.
846 to_lookup = []
844 to_lookup = []
847 to_drop = []
845 to_drop = []
848 for f in changedfiles:
846 for f in changedfiles:
849 if f in allfiles:
847 if f in allfiles:
850 to_lookup.append(f)
848 to_lookup.append(f)
851 else:
849 else:
852 to_drop.append(f)
850 to_drop.append(f)
853 else:
851 else:
854 changedfilesset = set(changedfiles)
852 changedfilesset = set(changedfiles)
855 to_lookup = changedfilesset & set(allfiles)
853 to_lookup = changedfilesset & set(allfiles)
856 to_drop = changedfilesset - to_lookup
854 to_drop = changedfilesset - to_lookup
857
855
858 if self._origpl is None:
856 if self._origpl is None:
859 self._origpl = self._pl
857 self._origpl = self._pl
860 self._map.setparents(parent, self._nodeconstants.nullid)
858 self._map.setparents(parent, self._nodeconstants.nullid)
861
859
862 for f in to_lookup:
860 for f in to_lookup:
863 self._normallookup(f)
861 self._normallookup(f)
864 for f in to_drop:
862 for f in to_drop:
865 self._drop(f)
863 self._drop(f)
866
864
867 self._dirty = True
865 self._dirty = True
868
866
869 def identity(self):
867 def identity(self):
870 """Return identity of dirstate itself to detect changing in storage
868 """Return identity of dirstate itself to detect changing in storage
871
869
872 If identity of previous dirstate is equal to this, writing
870 If identity of previous dirstate is equal to this, writing
873 changes based on the former dirstate out can keep consistency.
871 changes based on the former dirstate out can keep consistency.
874 """
872 """
875 return self._map.identity
873 return self._map.identity
876
874
877 def write(self, tr):
875 def write(self, tr):
878 if not self._dirty:
876 if not self._dirty:
879 return
877 return
880
878
881 filename = self._filename
879 filename = self._filename
882 if tr:
880 if tr:
883 # 'dirstate.write()' is not only for writing in-memory
881 # 'dirstate.write()' is not only for writing in-memory
884 # changes out, but also for dropping ambiguous timestamp.
882 # changes out, but also for dropping ambiguous timestamp.
885 # delayed writing re-raise "ambiguous timestamp issue".
883 # delayed writing re-raise "ambiguous timestamp issue".
886 # See also the wiki page below for detail:
884 # See also the wiki page below for detail:
887 # https://www.mercurial-scm.org/wiki/DirstateTransactionPlan
885 # https://www.mercurial-scm.org/wiki/DirstateTransactionPlan
888
886
889 # emulate dropping timestamp in 'parsers.pack_dirstate'
887 # emulate dropping timestamp in 'parsers.pack_dirstate'
890 now = _getfsnow(self._opener)
888 now = _getfsnow(self._opener)
891 self._map.clearambiguoustimes(self._updatedfiles, now)
889 self._map.clearambiguoustimes(self._updatedfiles, now)
892
890
893 # emulate that all 'dirstate.normal' results are written out
891 # emulate that all 'dirstate.normal' results are written out
894 self._lastnormaltime = 0
892 self._lastnormaltime = 0
895 self._updatedfiles.clear()
893 self._updatedfiles.clear()
896
894
897 # delay writing in-memory changes out
895 # delay writing in-memory changes out
898 tr.addfilegenerator(
896 tr.addfilegenerator(
899 b'dirstate',
897 b'dirstate',
900 (self._filename,),
898 (self._filename,),
901 lambda f: self._writedirstate(tr, f),
899 lambda f: self._writedirstate(tr, f),
902 location=b'plain',
900 location=b'plain',
903 )
901 )
904 return
902 return
905
903
906 st = self._opener(filename, b"w", atomictemp=True, checkambig=True)
904 st = self._opener(filename, b"w", atomictemp=True, checkambig=True)
907 self._writedirstate(tr, st)
905 self._writedirstate(tr, st)
908
906
909 def addparentchangecallback(self, category, callback):
907 def addparentchangecallback(self, category, callback):
910 """add a callback to be called when the wd parents are changed
908 """add a callback to be called when the wd parents are changed
911
909
912 Callback will be called with the following arguments:
910 Callback will be called with the following arguments:
913 dirstate, (oldp1, oldp2), (newp1, newp2)
911 dirstate, (oldp1, oldp2), (newp1, newp2)
914
912
915 Category is a unique identifier to allow overwriting an old callback
913 Category is a unique identifier to allow overwriting an old callback
916 with a newer callback.
914 with a newer callback.
917 """
915 """
918 self._plchangecallbacks[category] = callback
916 self._plchangecallbacks[category] = callback
919
917
920 def _writedirstate(self, tr, st):
918 def _writedirstate(self, tr, st):
921 # notify callbacks about parents change
919 # notify callbacks about parents change
922 if self._origpl is not None and self._origpl != self._pl:
920 if self._origpl is not None and self._origpl != self._pl:
923 for c, callback in sorted(
921 for c, callback in sorted(
924 pycompat.iteritems(self._plchangecallbacks)
922 pycompat.iteritems(self._plchangecallbacks)
925 ):
923 ):
926 callback(self, self._origpl, self._pl)
924 callback(self, self._origpl, self._pl)
927 self._origpl = None
925 self._origpl = None
928 # use the modification time of the newly created temporary file as the
926 # use the modification time of the newly created temporary file as the
929 # filesystem's notion of 'now'
927 # filesystem's notion of 'now'
930 now = util.fstat(st)[stat.ST_MTIME] & _rangemask
928 now = util.fstat(st)[stat.ST_MTIME] & _rangemask
931
929
932 # enough 'delaywrite' prevents 'pack_dirstate' from dropping
930 # enough 'delaywrite' prevents 'pack_dirstate' from dropping
933 # timestamp of each entries in dirstate, because of 'now > mtime'
931 # timestamp of each entries in dirstate, because of 'now > mtime'
934 delaywrite = self._ui.configint(b'debug', b'dirstate.delaywrite')
932 delaywrite = self._ui.configint(b'debug', b'dirstate.delaywrite')
935 if delaywrite > 0:
933 if delaywrite > 0:
936 # do we have any files to delay for?
934 # do we have any files to delay for?
937 for f, e in pycompat.iteritems(self._map):
935 for f, e in pycompat.iteritems(self._map):
938 if e.need_delay(now):
936 if e.need_delay(now):
939 import time # to avoid useless import
937 import time # to avoid useless import
940
938
941 # rather than sleep n seconds, sleep until the next
939 # rather than sleep n seconds, sleep until the next
942 # multiple of n seconds
940 # multiple of n seconds
943 clock = time.time()
941 clock = time.time()
944 start = int(clock) - (int(clock) % delaywrite)
942 start = int(clock) - (int(clock) % delaywrite)
945 end = start + delaywrite
943 end = start + delaywrite
946 time.sleep(end - clock)
944 time.sleep(end - clock)
947 now = end # trust our estimate that the end is near now
945 now = end # trust our estimate that the end is near now
948 break
946 break
949
947
950 self._map.write(tr, st, now)
948 self._map.write(tr, st, now)
951 self._lastnormaltime = 0
949 self._lastnormaltime = 0
952 self._dirty = False
950 self._dirty = False
953
951
954 def _dirignore(self, f):
952 def _dirignore(self, f):
955 if self._ignore(f):
953 if self._ignore(f):
956 return True
954 return True
957 for p in pathutil.finddirs(f):
955 for p in pathutil.finddirs(f):
958 if self._ignore(p):
956 if self._ignore(p):
959 return True
957 return True
960 return False
958 return False
961
959
962 def _ignorefiles(self):
960 def _ignorefiles(self):
963 files = []
961 files = []
964 if os.path.exists(self._join(b'.hgignore')):
962 if os.path.exists(self._join(b'.hgignore')):
965 files.append(self._join(b'.hgignore'))
963 files.append(self._join(b'.hgignore'))
966 for name, path in self._ui.configitems(b"ui"):
964 for name, path in self._ui.configitems(b"ui"):
967 if name == b'ignore' or name.startswith(b'ignore.'):
965 if name == b'ignore' or name.startswith(b'ignore.'):
968 # we need to use os.path.join here rather than self._join
966 # we need to use os.path.join here rather than self._join
969 # because path is arbitrary and user-specified
967 # because path is arbitrary and user-specified
970 files.append(os.path.join(self._rootdir, util.expandpath(path)))
968 files.append(os.path.join(self._rootdir, util.expandpath(path)))
971 return files
969 return files
972
970
973 def _ignorefileandline(self, f):
971 def _ignorefileandline(self, f):
974 files = collections.deque(self._ignorefiles())
972 files = collections.deque(self._ignorefiles())
975 visited = set()
973 visited = set()
976 while files:
974 while files:
977 i = files.popleft()
975 i = files.popleft()
978 patterns = matchmod.readpatternfile(
976 patterns = matchmod.readpatternfile(
979 i, self._ui.warn, sourceinfo=True
977 i, self._ui.warn, sourceinfo=True
980 )
978 )
981 for pattern, lineno, line in patterns:
979 for pattern, lineno, line in patterns:
982 kind, p = matchmod._patsplit(pattern, b'glob')
980 kind, p = matchmod._patsplit(pattern, b'glob')
983 if kind == b"subinclude":
981 if kind == b"subinclude":
984 if p not in visited:
982 if p not in visited:
985 files.append(p)
983 files.append(p)
986 continue
984 continue
987 m = matchmod.match(
985 m = matchmod.match(
988 self._root, b'', [], [pattern], warn=self._ui.warn
986 self._root, b'', [], [pattern], warn=self._ui.warn
989 )
987 )
990 if m(f):
988 if m(f):
991 return (i, lineno, line)
989 return (i, lineno, line)
992 visited.add(i)
990 visited.add(i)
993 return (None, -1, b"")
991 return (None, -1, b"")
994
992
995 def _walkexplicit(self, match, subrepos):
993 def _walkexplicit(self, match, subrepos):
996 """Get stat data about the files explicitly specified by match.
994 """Get stat data about the files explicitly specified by match.
997
995
998 Return a triple (results, dirsfound, dirsnotfound).
996 Return a triple (results, dirsfound, dirsnotfound).
999 - results is a mapping from filename to stat result. It also contains
997 - results is a mapping from filename to stat result. It also contains
1000 listings mapping subrepos and .hg to None.
998 listings mapping subrepos and .hg to None.
1001 - dirsfound is a list of files found to be directories.
999 - dirsfound is a list of files found to be directories.
1002 - dirsnotfound is a list of files that the dirstate thinks are
1000 - dirsnotfound is a list of files that the dirstate thinks are
1003 directories and that were not found."""
1001 directories and that were not found."""
1004
1002
1005 def badtype(mode):
1003 def badtype(mode):
1006 kind = _(b'unknown')
1004 kind = _(b'unknown')
1007 if stat.S_ISCHR(mode):
1005 if stat.S_ISCHR(mode):
1008 kind = _(b'character device')
1006 kind = _(b'character device')
1009 elif stat.S_ISBLK(mode):
1007 elif stat.S_ISBLK(mode):
1010 kind = _(b'block device')
1008 kind = _(b'block device')
1011 elif stat.S_ISFIFO(mode):
1009 elif stat.S_ISFIFO(mode):
1012 kind = _(b'fifo')
1010 kind = _(b'fifo')
1013 elif stat.S_ISSOCK(mode):
1011 elif stat.S_ISSOCK(mode):
1014 kind = _(b'socket')
1012 kind = _(b'socket')
1015 elif stat.S_ISDIR(mode):
1013 elif stat.S_ISDIR(mode):
1016 kind = _(b'directory')
1014 kind = _(b'directory')
1017 return _(b'unsupported file type (type is %s)') % kind
1015 return _(b'unsupported file type (type is %s)') % kind
1018
1016
1019 badfn = match.bad
1017 badfn = match.bad
1020 dmap = self._map
1018 dmap = self._map
1021 lstat = os.lstat
1019 lstat = os.lstat
1022 getkind = stat.S_IFMT
1020 getkind = stat.S_IFMT
1023 dirkind = stat.S_IFDIR
1021 dirkind = stat.S_IFDIR
1024 regkind = stat.S_IFREG
1022 regkind = stat.S_IFREG
1025 lnkkind = stat.S_IFLNK
1023 lnkkind = stat.S_IFLNK
1026 join = self._join
1024 join = self._join
1027 dirsfound = []
1025 dirsfound = []
1028 foundadd = dirsfound.append
1026 foundadd = dirsfound.append
1029 dirsnotfound = []
1027 dirsnotfound = []
1030 notfoundadd = dirsnotfound.append
1028 notfoundadd = dirsnotfound.append
1031
1029
1032 if not match.isexact() and self._checkcase:
1030 if not match.isexact() and self._checkcase:
1033 normalize = self._normalize
1031 normalize = self._normalize
1034 else:
1032 else:
1035 normalize = None
1033 normalize = None
1036
1034
1037 files = sorted(match.files())
1035 files = sorted(match.files())
1038 subrepos.sort()
1036 subrepos.sort()
1039 i, j = 0, 0
1037 i, j = 0, 0
1040 while i < len(files) and j < len(subrepos):
1038 while i < len(files) and j < len(subrepos):
1041 subpath = subrepos[j] + b"/"
1039 subpath = subrepos[j] + b"/"
1042 if files[i] < subpath:
1040 if files[i] < subpath:
1043 i += 1
1041 i += 1
1044 continue
1042 continue
1045 while i < len(files) and files[i].startswith(subpath):
1043 while i < len(files) and files[i].startswith(subpath):
1046 del files[i]
1044 del files[i]
1047 j += 1
1045 j += 1
1048
1046
1049 if not files or b'' in files:
1047 if not files or b'' in files:
1050 files = [b'']
1048 files = [b'']
1051 # constructing the foldmap is expensive, so don't do it for the
1049 # constructing the foldmap is expensive, so don't do it for the
1052 # common case where files is ['']
1050 # common case where files is ['']
1053 normalize = None
1051 normalize = None
1054 results = dict.fromkeys(subrepos)
1052 results = dict.fromkeys(subrepos)
1055 results[b'.hg'] = None
1053 results[b'.hg'] = None
1056
1054
1057 for ff in files:
1055 for ff in files:
1058 if normalize:
1056 if normalize:
1059 nf = normalize(ff, False, True)
1057 nf = normalize(ff, False, True)
1060 else:
1058 else:
1061 nf = ff
1059 nf = ff
1062 if nf in results:
1060 if nf in results:
1063 continue
1061 continue
1064
1062
1065 try:
1063 try:
1066 st = lstat(join(nf))
1064 st = lstat(join(nf))
1067 kind = getkind(st.st_mode)
1065 kind = getkind(st.st_mode)
1068 if kind == dirkind:
1066 if kind == dirkind:
1069 if nf in dmap:
1067 if nf in dmap:
1070 # file replaced by dir on disk but still in dirstate
1068 # file replaced by dir on disk but still in dirstate
1071 results[nf] = None
1069 results[nf] = None
1072 foundadd((nf, ff))
1070 foundadd((nf, ff))
1073 elif kind == regkind or kind == lnkkind:
1071 elif kind == regkind or kind == lnkkind:
1074 results[nf] = st
1072 results[nf] = st
1075 else:
1073 else:
1076 badfn(ff, badtype(kind))
1074 badfn(ff, badtype(kind))
1077 if nf in dmap:
1075 if nf in dmap:
1078 results[nf] = None
1076 results[nf] = None
1079 except OSError as inst: # nf not found on disk - it is dirstate only
1077 except OSError as inst: # nf not found on disk - it is dirstate only
1080 if nf in dmap: # does it exactly match a missing file?
1078 if nf in dmap: # does it exactly match a missing file?
1081 results[nf] = None
1079 results[nf] = None
1082 else: # does it match a missing directory?
1080 else: # does it match a missing directory?
1083 if self._map.hasdir(nf):
1081 if self._map.hasdir(nf):
1084 notfoundadd(nf)
1082 notfoundadd(nf)
1085 else:
1083 else:
1086 badfn(ff, encoding.strtolocal(inst.strerror))
1084 badfn(ff, encoding.strtolocal(inst.strerror))
1087
1085
1088 # match.files() may contain explicitly-specified paths that shouldn't
1086 # match.files() may contain explicitly-specified paths that shouldn't
1089 # be taken; drop them from the list of files found. dirsfound/notfound
1087 # be taken; drop them from the list of files found. dirsfound/notfound
1090 # aren't filtered here because they will be tested later.
1088 # aren't filtered here because they will be tested later.
1091 if match.anypats():
1089 if match.anypats():
1092 for f in list(results):
1090 for f in list(results):
1093 if f == b'.hg' or f in subrepos:
1091 if f == b'.hg' or f in subrepos:
1094 # keep sentinel to disable further out-of-repo walks
1092 # keep sentinel to disable further out-of-repo walks
1095 continue
1093 continue
1096 if not match(f):
1094 if not match(f):
1097 del results[f]
1095 del results[f]
1098
1096
1099 # Case insensitive filesystems cannot rely on lstat() failing to detect
1097 # Case insensitive filesystems cannot rely on lstat() failing to detect
1100 # a case-only rename. Prune the stat object for any file that does not
1098 # a case-only rename. Prune the stat object for any file that does not
1101 # match the case in the filesystem, if there are multiple files that
1099 # match the case in the filesystem, if there are multiple files that
1102 # normalize to the same path.
1100 # normalize to the same path.
1103 if match.isexact() and self._checkcase:
1101 if match.isexact() and self._checkcase:
1104 normed = {}
1102 normed = {}
1105
1103
1106 for f, st in pycompat.iteritems(results):
1104 for f, st in pycompat.iteritems(results):
1107 if st is None:
1105 if st is None:
1108 continue
1106 continue
1109
1107
1110 nc = util.normcase(f)
1108 nc = util.normcase(f)
1111 paths = normed.get(nc)
1109 paths = normed.get(nc)
1112
1110
1113 if paths is None:
1111 if paths is None:
1114 paths = set()
1112 paths = set()
1115 normed[nc] = paths
1113 normed[nc] = paths
1116
1114
1117 paths.add(f)
1115 paths.add(f)
1118
1116
1119 for norm, paths in pycompat.iteritems(normed):
1117 for norm, paths in pycompat.iteritems(normed):
1120 if len(paths) > 1:
1118 if len(paths) > 1:
1121 for path in paths:
1119 for path in paths:
1122 folded = self._discoverpath(
1120 folded = self._discoverpath(
1123 path, norm, True, None, self._map.dirfoldmap
1121 path, norm, True, None, self._map.dirfoldmap
1124 )
1122 )
1125 if path != folded:
1123 if path != folded:
1126 results[path] = None
1124 results[path] = None
1127
1125
1128 return results, dirsfound, dirsnotfound
1126 return results, dirsfound, dirsnotfound
1129
1127
1130 def walk(self, match, subrepos, unknown, ignored, full=True):
1128 def walk(self, match, subrepos, unknown, ignored, full=True):
1131 """
1129 """
1132 Walk recursively through the directory tree, finding all files
1130 Walk recursively through the directory tree, finding all files
1133 matched by match.
1131 matched by match.
1134
1132
1135 If full is False, maybe skip some known-clean files.
1133 If full is False, maybe skip some known-clean files.
1136
1134
1137 Return a dict mapping filename to stat-like object (either
1135 Return a dict mapping filename to stat-like object (either
1138 mercurial.osutil.stat instance or return value of os.stat()).
1136 mercurial.osutil.stat instance or return value of os.stat()).
1139
1137
1140 """
1138 """
1141 # full is a flag that extensions that hook into walk can use -- this
1139 # full is a flag that extensions that hook into walk can use -- this
1142 # implementation doesn't use it at all. This satisfies the contract
1140 # implementation doesn't use it at all. This satisfies the contract
1143 # because we only guarantee a "maybe".
1141 # because we only guarantee a "maybe".
1144
1142
1145 if ignored:
1143 if ignored:
1146 ignore = util.never
1144 ignore = util.never
1147 dirignore = util.never
1145 dirignore = util.never
1148 elif unknown:
1146 elif unknown:
1149 ignore = self._ignore
1147 ignore = self._ignore
1150 dirignore = self._dirignore
1148 dirignore = self._dirignore
1151 else:
1149 else:
1152 # if not unknown and not ignored, drop dir recursion and step 2
1150 # if not unknown and not ignored, drop dir recursion and step 2
1153 ignore = util.always
1151 ignore = util.always
1154 dirignore = util.always
1152 dirignore = util.always
1155
1153
1156 matchfn = match.matchfn
1154 matchfn = match.matchfn
1157 matchalways = match.always()
1155 matchalways = match.always()
1158 matchtdir = match.traversedir
1156 matchtdir = match.traversedir
1159 dmap = self._map
1157 dmap = self._map
1160 listdir = util.listdir
1158 listdir = util.listdir
1161 lstat = os.lstat
1159 lstat = os.lstat
1162 dirkind = stat.S_IFDIR
1160 dirkind = stat.S_IFDIR
1163 regkind = stat.S_IFREG
1161 regkind = stat.S_IFREG
1164 lnkkind = stat.S_IFLNK
1162 lnkkind = stat.S_IFLNK
1165 join = self._join
1163 join = self._join
1166
1164
1167 exact = skipstep3 = False
1165 exact = skipstep3 = False
1168 if match.isexact(): # match.exact
1166 if match.isexact(): # match.exact
1169 exact = True
1167 exact = True
1170 dirignore = util.always # skip step 2
1168 dirignore = util.always # skip step 2
1171 elif match.prefix(): # match.match, no patterns
1169 elif match.prefix(): # match.match, no patterns
1172 skipstep3 = True
1170 skipstep3 = True
1173
1171
1174 if not exact and self._checkcase:
1172 if not exact and self._checkcase:
1175 normalize = self._normalize
1173 normalize = self._normalize
1176 normalizefile = self._normalizefile
1174 normalizefile = self._normalizefile
1177 skipstep3 = False
1175 skipstep3 = False
1178 else:
1176 else:
1179 normalize = self._normalize
1177 normalize = self._normalize
1180 normalizefile = None
1178 normalizefile = None
1181
1179
1182 # step 1: find all explicit files
1180 # step 1: find all explicit files
1183 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1181 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
1184 if matchtdir:
1182 if matchtdir:
1185 for d in work:
1183 for d in work:
1186 matchtdir(d[0])
1184 matchtdir(d[0])
1187 for d in dirsnotfound:
1185 for d in dirsnotfound:
1188 matchtdir(d)
1186 matchtdir(d)
1189
1187
1190 skipstep3 = skipstep3 and not (work or dirsnotfound)
1188 skipstep3 = skipstep3 and not (work or dirsnotfound)
1191 work = [d for d in work if not dirignore(d[0])]
1189 work = [d for d in work if not dirignore(d[0])]
1192
1190
1193 # step 2: visit subdirectories
1191 # step 2: visit subdirectories
1194 def traverse(work, alreadynormed):
1192 def traverse(work, alreadynormed):
1195 wadd = work.append
1193 wadd = work.append
1196 while work:
1194 while work:
1197 tracing.counter('dirstate.walk work', len(work))
1195 tracing.counter('dirstate.walk work', len(work))
1198 nd = work.pop()
1196 nd = work.pop()
1199 visitentries = match.visitchildrenset(nd)
1197 visitentries = match.visitchildrenset(nd)
1200 if not visitentries:
1198 if not visitentries:
1201 continue
1199 continue
1202 if visitentries == b'this' or visitentries == b'all':
1200 if visitentries == b'this' or visitentries == b'all':
1203 visitentries = None
1201 visitentries = None
1204 skip = None
1202 skip = None
1205 if nd != b'':
1203 if nd != b'':
1206 skip = b'.hg'
1204 skip = b'.hg'
1207 try:
1205 try:
1208 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1206 with tracing.log('dirstate.walk.traverse listdir %s', nd):
1209 entries = listdir(join(nd), stat=True, skip=skip)
1207 entries = listdir(join(nd), stat=True, skip=skip)
1210 except OSError as inst:
1208 except OSError as inst:
1211 if inst.errno in (errno.EACCES, errno.ENOENT):
1209 if inst.errno in (errno.EACCES, errno.ENOENT):
1212 match.bad(
1210 match.bad(
1213 self.pathto(nd), encoding.strtolocal(inst.strerror)
1211 self.pathto(nd), encoding.strtolocal(inst.strerror)
1214 )
1212 )
1215 continue
1213 continue
1216 raise
1214 raise
1217 for f, kind, st in entries:
1215 for f, kind, st in entries:
1218 # Some matchers may return files in the visitentries set,
1216 # Some matchers may return files in the visitentries set,
1219 # instead of 'this', if the matcher explicitly mentions them
1217 # instead of 'this', if the matcher explicitly mentions them
1220 # and is not an exactmatcher. This is acceptable; we do not
1218 # and is not an exactmatcher. This is acceptable; we do not
1221 # make any hard assumptions about file-or-directory below
1219 # make any hard assumptions about file-or-directory below
1222 # based on the presence of `f` in visitentries. If
1220 # based on the presence of `f` in visitentries. If
1223 # visitchildrenset returned a set, we can always skip the
1221 # visitchildrenset returned a set, we can always skip the
1224 # entries *not* in the set it provided regardless of whether
1222 # entries *not* in the set it provided regardless of whether
1225 # they're actually a file or a directory.
1223 # they're actually a file or a directory.
1226 if visitentries and f not in visitentries:
1224 if visitentries and f not in visitentries:
1227 continue
1225 continue
1228 if normalizefile:
1226 if normalizefile:
1229 # even though f might be a directory, we're only
1227 # even though f might be a directory, we're only
1230 # interested in comparing it to files currently in the
1228 # interested in comparing it to files currently in the
1231 # dmap -- therefore normalizefile is enough
1229 # dmap -- therefore normalizefile is enough
1232 nf = normalizefile(
1230 nf = normalizefile(
1233 nd and (nd + b"/" + f) or f, True, True
1231 nd and (nd + b"/" + f) or f, True, True
1234 )
1232 )
1235 else:
1233 else:
1236 nf = nd and (nd + b"/" + f) or f
1234 nf = nd and (nd + b"/" + f) or f
1237 if nf not in results:
1235 if nf not in results:
1238 if kind == dirkind:
1236 if kind == dirkind:
1239 if not ignore(nf):
1237 if not ignore(nf):
1240 if matchtdir:
1238 if matchtdir:
1241 matchtdir(nf)
1239 matchtdir(nf)
1242 wadd(nf)
1240 wadd(nf)
1243 if nf in dmap and (matchalways or matchfn(nf)):
1241 if nf in dmap and (matchalways or matchfn(nf)):
1244 results[nf] = None
1242 results[nf] = None
1245 elif kind == regkind or kind == lnkkind:
1243 elif kind == regkind or kind == lnkkind:
1246 if nf in dmap:
1244 if nf in dmap:
1247 if matchalways or matchfn(nf):
1245 if matchalways or matchfn(nf):
1248 results[nf] = st
1246 results[nf] = st
1249 elif (matchalways or matchfn(nf)) and not ignore(
1247 elif (matchalways or matchfn(nf)) and not ignore(
1250 nf
1248 nf
1251 ):
1249 ):
1252 # unknown file -- normalize if necessary
1250 # unknown file -- normalize if necessary
1253 if not alreadynormed:
1251 if not alreadynormed:
1254 nf = normalize(nf, False, True)
1252 nf = normalize(nf, False, True)
1255 results[nf] = st
1253 results[nf] = st
1256 elif nf in dmap and (matchalways or matchfn(nf)):
1254 elif nf in dmap and (matchalways or matchfn(nf)):
1257 results[nf] = None
1255 results[nf] = None
1258
1256
1259 for nd, d in work:
1257 for nd, d in work:
1260 # alreadynormed means that processwork doesn't have to do any
1258 # alreadynormed means that processwork doesn't have to do any
1261 # expensive directory normalization
1259 # expensive directory normalization
1262 alreadynormed = not normalize or nd == d
1260 alreadynormed = not normalize or nd == d
1263 traverse([d], alreadynormed)
1261 traverse([d], alreadynormed)
1264
1262
1265 for s in subrepos:
1263 for s in subrepos:
1266 del results[s]
1264 del results[s]
1267 del results[b'.hg']
1265 del results[b'.hg']
1268
1266
1269 # step 3: visit remaining files from dmap
1267 # step 3: visit remaining files from dmap
1270 if not skipstep3 and not exact:
1268 if not skipstep3 and not exact:
1271 # If a dmap file is not in results yet, it was either
1269 # If a dmap file is not in results yet, it was either
1272 # a) not matching matchfn b) ignored, c) missing, or d) under a
1270 # a) not matching matchfn b) ignored, c) missing, or d) under a
1273 # symlink directory.
1271 # symlink directory.
1274 if not results and matchalways:
1272 if not results and matchalways:
1275 visit = [f for f in dmap]
1273 visit = [f for f in dmap]
1276 else:
1274 else:
1277 visit = [f for f in dmap if f not in results and matchfn(f)]
1275 visit = [f for f in dmap if f not in results and matchfn(f)]
1278 visit.sort()
1276 visit.sort()
1279
1277
1280 if unknown:
1278 if unknown:
1281 # unknown == True means we walked all dirs under the roots
1279 # unknown == True means we walked all dirs under the roots
1282 # that wasn't ignored, and everything that matched was stat'ed
1280 # that wasn't ignored, and everything that matched was stat'ed
1283 # and is already in results.
1281 # and is already in results.
1284 # The rest must thus be ignored or under a symlink.
1282 # The rest must thus be ignored or under a symlink.
1285 audit_path = pathutil.pathauditor(self._root, cached=True)
1283 audit_path = pathutil.pathauditor(self._root, cached=True)
1286
1284
1287 for nf in iter(visit):
1285 for nf in iter(visit):
1288 # If a stat for the same file was already added with a
1286 # If a stat for the same file was already added with a
1289 # different case, don't add one for this, since that would
1287 # different case, don't add one for this, since that would
1290 # make it appear as if the file exists under both names
1288 # make it appear as if the file exists under both names
1291 # on disk.
1289 # on disk.
1292 if (
1290 if (
1293 normalizefile
1291 normalizefile
1294 and normalizefile(nf, True, True) in results
1292 and normalizefile(nf, True, True) in results
1295 ):
1293 ):
1296 results[nf] = None
1294 results[nf] = None
1297 # Report ignored items in the dmap as long as they are not
1295 # Report ignored items in the dmap as long as they are not
1298 # under a symlink directory.
1296 # under a symlink directory.
1299 elif audit_path.check(nf):
1297 elif audit_path.check(nf):
1300 try:
1298 try:
1301 results[nf] = lstat(join(nf))
1299 results[nf] = lstat(join(nf))
1302 # file was just ignored, no links, and exists
1300 # file was just ignored, no links, and exists
1303 except OSError:
1301 except OSError:
1304 # file doesn't exist
1302 # file doesn't exist
1305 results[nf] = None
1303 results[nf] = None
1306 else:
1304 else:
1307 # It's either missing or under a symlink directory
1305 # It's either missing or under a symlink directory
1308 # which we in this case report as missing
1306 # which we in this case report as missing
1309 results[nf] = None
1307 results[nf] = None
1310 else:
1308 else:
1311 # We may not have walked the full directory tree above,
1309 # We may not have walked the full directory tree above,
1312 # so stat and check everything we missed.
1310 # so stat and check everything we missed.
1313 iv = iter(visit)
1311 iv = iter(visit)
1314 for st in util.statfiles([join(i) for i in visit]):
1312 for st in util.statfiles([join(i) for i in visit]):
1315 results[next(iv)] = st
1313 results[next(iv)] = st
1316 return results
1314 return results
1317
1315
1318 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1316 def _rust_status(self, matcher, list_clean, list_ignored, list_unknown):
1319 # Force Rayon (Rust parallelism library) to respect the number of
1317 # Force Rayon (Rust parallelism library) to respect the number of
1320 # workers. This is a temporary workaround until Rust code knows
1318 # workers. This is a temporary workaround until Rust code knows
1321 # how to read the config file.
1319 # how to read the config file.
1322 numcpus = self._ui.configint(b"worker", b"numcpus")
1320 numcpus = self._ui.configint(b"worker", b"numcpus")
1323 if numcpus is not None:
1321 if numcpus is not None:
1324 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1322 encoding.environ.setdefault(b'RAYON_NUM_THREADS', b'%d' % numcpus)
1325
1323
1326 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1324 workers_enabled = self._ui.configbool(b"worker", b"enabled", True)
1327 if not workers_enabled:
1325 if not workers_enabled:
1328 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1326 encoding.environ[b"RAYON_NUM_THREADS"] = b"1"
1329
1327
1330 (
1328 (
1331 lookup,
1329 lookup,
1332 modified,
1330 modified,
1333 added,
1331 added,
1334 removed,
1332 removed,
1335 deleted,
1333 deleted,
1336 clean,
1334 clean,
1337 ignored,
1335 ignored,
1338 unknown,
1336 unknown,
1339 warnings,
1337 warnings,
1340 bad,
1338 bad,
1341 traversed,
1339 traversed,
1342 dirty,
1340 dirty,
1343 ) = rustmod.status(
1341 ) = rustmod.status(
1344 self._map._rustmap,
1342 self._map._rustmap,
1345 matcher,
1343 matcher,
1346 self._rootdir,
1344 self._rootdir,
1347 self._ignorefiles(),
1345 self._ignorefiles(),
1348 self._checkexec,
1346 self._checkexec,
1349 self._lastnormaltime,
1347 self._lastnormaltime,
1350 bool(list_clean),
1348 bool(list_clean),
1351 bool(list_ignored),
1349 bool(list_ignored),
1352 bool(list_unknown),
1350 bool(list_unknown),
1353 bool(matcher.traversedir),
1351 bool(matcher.traversedir),
1354 )
1352 )
1355
1353
1356 self._dirty |= dirty
1354 self._dirty |= dirty
1357
1355
1358 if matcher.traversedir:
1356 if matcher.traversedir:
1359 for dir in traversed:
1357 for dir in traversed:
1360 matcher.traversedir(dir)
1358 matcher.traversedir(dir)
1361
1359
1362 if self._ui.warn:
1360 if self._ui.warn:
1363 for item in warnings:
1361 for item in warnings:
1364 if isinstance(item, tuple):
1362 if isinstance(item, tuple):
1365 file_path, syntax = item
1363 file_path, syntax = item
1366 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1364 msg = _(b"%s: ignoring invalid syntax '%s'\n") % (
1367 file_path,
1365 file_path,
1368 syntax,
1366 syntax,
1369 )
1367 )
1370 self._ui.warn(msg)
1368 self._ui.warn(msg)
1371 else:
1369 else:
1372 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1370 msg = _(b"skipping unreadable pattern file '%s': %s\n")
1373 self._ui.warn(
1371 self._ui.warn(
1374 msg
1372 msg
1375 % (
1373 % (
1376 pathutil.canonpath(
1374 pathutil.canonpath(
1377 self._rootdir, self._rootdir, item
1375 self._rootdir, self._rootdir, item
1378 ),
1376 ),
1379 b"No such file or directory",
1377 b"No such file or directory",
1380 )
1378 )
1381 )
1379 )
1382
1380
1383 for (fn, message) in bad:
1381 for (fn, message) in bad:
1384 matcher.bad(fn, encoding.strtolocal(message))
1382 matcher.bad(fn, encoding.strtolocal(message))
1385
1383
1386 status = scmutil.status(
1384 status = scmutil.status(
1387 modified=modified,
1385 modified=modified,
1388 added=added,
1386 added=added,
1389 removed=removed,
1387 removed=removed,
1390 deleted=deleted,
1388 deleted=deleted,
1391 unknown=unknown,
1389 unknown=unknown,
1392 ignored=ignored,
1390 ignored=ignored,
1393 clean=clean,
1391 clean=clean,
1394 )
1392 )
1395 return (lookup, status)
1393 return (lookup, status)
1396
1394
1397 def status(self, match, subrepos, ignored, clean, unknown):
1395 def status(self, match, subrepos, ignored, clean, unknown):
1398 """Determine the status of the working copy relative to the
1396 """Determine the status of the working copy relative to the
1399 dirstate and return a pair of (unsure, status), where status is of type
1397 dirstate and return a pair of (unsure, status), where status is of type
1400 scmutil.status and:
1398 scmutil.status and:
1401
1399
1402 unsure:
1400 unsure:
1403 files that might have been modified since the dirstate was
1401 files that might have been modified since the dirstate was
1404 written, but need to be read to be sure (size is the same
1402 written, but need to be read to be sure (size is the same
1405 but mtime differs)
1403 but mtime differs)
1406 status.modified:
1404 status.modified:
1407 files that have definitely been modified since the dirstate
1405 files that have definitely been modified since the dirstate
1408 was written (different size or mode)
1406 was written (different size or mode)
1409 status.clean:
1407 status.clean:
1410 files that have definitely not been modified since the
1408 files that have definitely not been modified since the
1411 dirstate was written
1409 dirstate was written
1412 """
1410 """
1413 listignored, listclean, listunknown = ignored, clean, unknown
1411 listignored, listclean, listunknown = ignored, clean, unknown
1414 lookup, modified, added, unknown, ignored = [], [], [], [], []
1412 lookup, modified, added, unknown, ignored = [], [], [], [], []
1415 removed, deleted, clean = [], [], []
1413 removed, deleted, clean = [], [], []
1416
1414
1417 dmap = self._map
1415 dmap = self._map
1418 dmap.preload()
1416 dmap.preload()
1419
1417
1420 use_rust = True
1418 use_rust = True
1421
1419
1422 allowed_matchers = (
1420 allowed_matchers = (
1423 matchmod.alwaysmatcher,
1421 matchmod.alwaysmatcher,
1424 matchmod.exactmatcher,
1422 matchmod.exactmatcher,
1425 matchmod.includematcher,
1423 matchmod.includematcher,
1426 )
1424 )
1427
1425
1428 if rustmod is None:
1426 if rustmod is None:
1429 use_rust = False
1427 use_rust = False
1430 elif self._checkcase:
1428 elif self._checkcase:
1431 # Case-insensitive filesystems are not handled yet
1429 # Case-insensitive filesystems are not handled yet
1432 use_rust = False
1430 use_rust = False
1433 elif subrepos:
1431 elif subrepos:
1434 use_rust = False
1432 use_rust = False
1435 elif sparse.enabled:
1433 elif sparse.enabled:
1436 use_rust = False
1434 use_rust = False
1437 elif not isinstance(match, allowed_matchers):
1435 elif not isinstance(match, allowed_matchers):
1438 # Some matchers have yet to be implemented
1436 # Some matchers have yet to be implemented
1439 use_rust = False
1437 use_rust = False
1440
1438
1441 if use_rust:
1439 if use_rust:
1442 try:
1440 try:
1443 return self._rust_status(
1441 return self._rust_status(
1444 match, listclean, listignored, listunknown
1442 match, listclean, listignored, listunknown
1445 )
1443 )
1446 except rustmod.FallbackError:
1444 except rustmod.FallbackError:
1447 pass
1445 pass
1448
1446
1449 def noop(f):
1447 def noop(f):
1450 pass
1448 pass
1451
1449
1452 dcontains = dmap.__contains__
1450 dcontains = dmap.__contains__
1453 dget = dmap.__getitem__
1451 dget = dmap.__getitem__
1454 ladd = lookup.append # aka "unsure"
1452 ladd = lookup.append # aka "unsure"
1455 madd = modified.append
1453 madd = modified.append
1456 aadd = added.append
1454 aadd = added.append
1457 uadd = unknown.append if listunknown else noop
1455 uadd = unknown.append if listunknown else noop
1458 iadd = ignored.append if listignored else noop
1456 iadd = ignored.append if listignored else noop
1459 radd = removed.append
1457 radd = removed.append
1460 dadd = deleted.append
1458 dadd = deleted.append
1461 cadd = clean.append if listclean else noop
1459 cadd = clean.append if listclean else noop
1462 mexact = match.exact
1460 mexact = match.exact
1463 dirignore = self._dirignore
1461 dirignore = self._dirignore
1464 checkexec = self._checkexec
1462 checkexec = self._checkexec
1465 copymap = self._map.copymap
1463 copymap = self._map.copymap
1466 lastnormaltime = self._lastnormaltime
1464 lastnormaltime = self._lastnormaltime
1467
1465
1468 # We need to do full walks when either
1466 # We need to do full walks when either
1469 # - we're listing all clean files, or
1467 # - we're listing all clean files, or
1470 # - match.traversedir does something, because match.traversedir should
1468 # - match.traversedir does something, because match.traversedir should
1471 # be called for every dir in the working dir
1469 # be called for every dir in the working dir
1472 full = listclean or match.traversedir is not None
1470 full = listclean or match.traversedir is not None
1473 for fn, st in pycompat.iteritems(
1471 for fn, st in pycompat.iteritems(
1474 self.walk(match, subrepos, listunknown, listignored, full=full)
1472 self.walk(match, subrepos, listunknown, listignored, full=full)
1475 ):
1473 ):
1476 if not dcontains(fn):
1474 if not dcontains(fn):
1477 if (listignored or mexact(fn)) and dirignore(fn):
1475 if (listignored or mexact(fn)) and dirignore(fn):
1478 if listignored:
1476 if listignored:
1479 iadd(fn)
1477 iadd(fn)
1480 else:
1478 else:
1481 uadd(fn)
1479 uadd(fn)
1482 continue
1480 continue
1483
1481
1484 # This is equivalent to 'state, mode, size, time = dmap[fn]' but not
1482 # This is equivalent to 'state, mode, size, time = dmap[fn]' but not
1485 # written like that for performance reasons. dmap[fn] is not a
1483 # written like that for performance reasons. dmap[fn] is not a
1486 # Python tuple in compiled builds. The CPython UNPACK_SEQUENCE
1484 # Python tuple in compiled builds. The CPython UNPACK_SEQUENCE
1487 # opcode has fast paths when the value to be unpacked is a tuple or
1485 # opcode has fast paths when the value to be unpacked is a tuple or
1488 # a list, but falls back to creating a full-fledged iterator in
1486 # a list, but falls back to creating a full-fledged iterator in
1489 # general. That is much slower than simply accessing and storing the
1487 # general. That is much slower than simply accessing and storing the
1490 # tuple members one by one.
1488 # tuple members one by one.
1491 t = dget(fn)
1489 t = dget(fn)
1492 mode = t.mode
1490 mode = t.mode
1493 size = t.size
1491 size = t.size
1494 time = t.mtime
1492 time = t.mtime
1495
1493
1496 if not st and t.tracked:
1494 if not st and t.tracked:
1497 dadd(fn)
1495 dadd(fn)
1498 elif t.merged:
1496 elif t.merged:
1499 madd(fn)
1497 madd(fn)
1500 elif t.added:
1498 elif t.added:
1501 aadd(fn)
1499 aadd(fn)
1502 elif t.removed:
1500 elif t.removed:
1503 radd(fn)
1501 radd(fn)
1504 elif t.tracked:
1502 elif t.tracked:
1505 if (
1503 if (
1506 size >= 0
1504 size >= 0
1507 and (
1505 and (
1508 (size != st.st_size and size != st.st_size & _rangemask)
1506 (size != st.st_size and size != st.st_size & _rangemask)
1509 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1507 or ((mode ^ st.st_mode) & 0o100 and checkexec)
1510 )
1508 )
1511 or t.from_p2
1509 or t.from_p2
1512 or fn in copymap
1510 or fn in copymap
1513 ):
1511 ):
1514 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1512 if stat.S_ISLNK(st.st_mode) and size != st.st_size:
1515 # issue6456: Size returned may be longer due to
1513 # issue6456: Size returned may be longer due to
1516 # encryption on EXT-4 fscrypt, undecided.
1514 # encryption on EXT-4 fscrypt, undecided.
1517 ladd(fn)
1515 ladd(fn)
1518 else:
1516 else:
1519 madd(fn)
1517 madd(fn)
1520 elif (
1518 elif (
1521 time != st[stat.ST_MTIME]
1519 time != st[stat.ST_MTIME]
1522 and time != st[stat.ST_MTIME] & _rangemask
1520 and time != st[stat.ST_MTIME] & _rangemask
1523 ):
1521 ):
1524 ladd(fn)
1522 ladd(fn)
1525 elif st[stat.ST_MTIME] == lastnormaltime:
1523 elif st[stat.ST_MTIME] == lastnormaltime:
1526 # fn may have just been marked as normal and it may have
1524 # fn may have just been marked as normal and it may have
1527 # changed in the same second without changing its size.
1525 # changed in the same second without changing its size.
1528 # This can happen if we quickly do multiple commits.
1526 # This can happen if we quickly do multiple commits.
1529 # Force lookup, so we don't miss such a racy file change.
1527 # Force lookup, so we don't miss such a racy file change.
1530 ladd(fn)
1528 ladd(fn)
1531 elif listclean:
1529 elif listclean:
1532 cadd(fn)
1530 cadd(fn)
1533 status = scmutil.status(
1531 status = scmutil.status(
1534 modified, added, removed, deleted, unknown, ignored, clean
1532 modified, added, removed, deleted, unknown, ignored, clean
1535 )
1533 )
1536 return (lookup, status)
1534 return (lookup, status)
1537
1535
1538 def matches(self, match):
1536 def matches(self, match):
1539 """
1537 """
1540 return files in the dirstate (in whatever state) filtered by match
1538 return files in the dirstate (in whatever state) filtered by match
1541 """
1539 """
1542 dmap = self._map
1540 dmap = self._map
1543 if rustmod is not None:
1541 if rustmod is not None:
1544 dmap = self._map._rustmap
1542 dmap = self._map._rustmap
1545
1543
1546 if match.always():
1544 if match.always():
1547 return dmap.keys()
1545 return dmap.keys()
1548 files = match.files()
1546 files = match.files()
1549 if match.isexact():
1547 if match.isexact():
1550 # fast path -- filter the other way around, since typically files is
1548 # fast path -- filter the other way around, since typically files is
1551 # much smaller than dmap
1549 # much smaller than dmap
1552 return [f for f in files if f in dmap]
1550 return [f for f in files if f in dmap]
1553 if match.prefix() and all(fn in dmap for fn in files):
1551 if match.prefix() and all(fn in dmap for fn in files):
1554 # fast path -- all the values are known to be files, so just return
1552 # fast path -- all the values are known to be files, so just return
1555 # that
1553 # that
1556 return list(files)
1554 return list(files)
1557 return [f for f in dmap if match(f)]
1555 return [f for f in dmap if match(f)]
1558
1556
1559 def _actualfilename(self, tr):
1557 def _actualfilename(self, tr):
1560 if tr:
1558 if tr:
1561 return self._pendingfilename
1559 return self._pendingfilename
1562 else:
1560 else:
1563 return self._filename
1561 return self._filename
1564
1562
1565 def savebackup(self, tr, backupname):
1563 def savebackup(self, tr, backupname):
1566 '''Save current dirstate into backup file'''
1564 '''Save current dirstate into backup file'''
1567 filename = self._actualfilename(tr)
1565 filename = self._actualfilename(tr)
1568 assert backupname != filename
1566 assert backupname != filename
1569
1567
1570 # use '_writedirstate' instead of 'write' to write changes certainly,
1568 # use '_writedirstate' instead of 'write' to write changes certainly,
1571 # because the latter omits writing out if transaction is running.
1569 # because the latter omits writing out if transaction is running.
1572 # output file will be used to create backup of dirstate at this point.
1570 # output file will be used to create backup of dirstate at this point.
1573 if self._dirty or not self._opener.exists(filename):
1571 if self._dirty or not self._opener.exists(filename):
1574 self._writedirstate(
1572 self._writedirstate(
1575 tr,
1573 tr,
1576 self._opener(filename, b"w", atomictemp=True, checkambig=True),
1574 self._opener(filename, b"w", atomictemp=True, checkambig=True),
1577 )
1575 )
1578
1576
1579 if tr:
1577 if tr:
1580 # ensure that subsequent tr.writepending returns True for
1578 # ensure that subsequent tr.writepending returns True for
1581 # changes written out above, even if dirstate is never
1579 # changes written out above, even if dirstate is never
1582 # changed after this
1580 # changed after this
1583 tr.addfilegenerator(
1581 tr.addfilegenerator(
1584 b'dirstate',
1582 b'dirstate',
1585 (self._filename,),
1583 (self._filename,),
1586 lambda f: self._writedirstate(tr, f),
1584 lambda f: self._writedirstate(tr, f),
1587 location=b'plain',
1585 location=b'plain',
1588 )
1586 )
1589
1587
1590 # ensure that pending file written above is unlinked at
1588 # ensure that pending file written above is unlinked at
1591 # failure, even if tr.writepending isn't invoked until the
1589 # failure, even if tr.writepending isn't invoked until the
1592 # end of this transaction
1590 # end of this transaction
1593 tr.registertmp(filename, location=b'plain')
1591 tr.registertmp(filename, location=b'plain')
1594
1592
1595 self._opener.tryunlink(backupname)
1593 self._opener.tryunlink(backupname)
1596 # hardlink backup is okay because _writedirstate is always called
1594 # hardlink backup is okay because _writedirstate is always called
1597 # with an "atomictemp=True" file.
1595 # with an "atomictemp=True" file.
1598 util.copyfile(
1596 util.copyfile(
1599 self._opener.join(filename),
1597 self._opener.join(filename),
1600 self._opener.join(backupname),
1598 self._opener.join(backupname),
1601 hardlink=True,
1599 hardlink=True,
1602 )
1600 )
1603
1601
1604 def restorebackup(self, tr, backupname):
1602 def restorebackup(self, tr, backupname):
1605 '''Restore dirstate by backup file'''
1603 '''Restore dirstate by backup file'''
1606 # this "invalidate()" prevents "wlock.release()" from writing
1604 # this "invalidate()" prevents "wlock.release()" from writing
1607 # changes of dirstate out after restoring from backup file
1605 # changes of dirstate out after restoring from backup file
1608 self.invalidate()
1606 self.invalidate()
1609 filename = self._actualfilename(tr)
1607 filename = self._actualfilename(tr)
1610 o = self._opener
1608 o = self._opener
1611 if util.samefile(o.join(backupname), o.join(filename)):
1609 if util.samefile(o.join(backupname), o.join(filename)):
1612 o.unlink(backupname)
1610 o.unlink(backupname)
1613 else:
1611 else:
1614 o.rename(backupname, filename, checkambig=True)
1612 o.rename(backupname, filename, checkambig=True)
1615
1613
1616 def clearbackup(self, tr, backupname):
1614 def clearbackup(self, tr, backupname):
1617 '''Clear backup file'''
1615 '''Clear backup file'''
1618 self._opener.unlink(backupname)
1616 self._opener.unlink(backupname)
General Comments 0
You need to be logged in to leave comments. Login now