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