##// END OF EJS Templates
workingctx: move setparents() logic from localrepo to mirror overlayworkingctx...
Martin von Zweigbergk -
r44504:b74270da default
parent child Browse files
Show More
@@ -1,3034 +1,3051 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import filecmp
11 import filecmp
12 import os
12 import os
13 import stat
13 import stat
14
14
15 from .i18n import _
15 from .i18n import _
16 from .node import (
16 from .node import (
17 addednodeid,
17 addednodeid,
18 hex,
18 hex,
19 modifiednodeid,
19 modifiednodeid,
20 nullid,
20 nullid,
21 nullrev,
21 nullrev,
22 short,
22 short,
23 wdirfilenodeids,
23 wdirfilenodeids,
24 wdirhex,
24 wdirhex,
25 )
25 )
26 from .pycompat import (
26 from .pycompat import (
27 getattr,
27 getattr,
28 open,
28 open,
29 )
29 )
30 from . import (
30 from . import (
31 copies,
31 copies,
32 dagop,
32 dagop,
33 encoding,
33 encoding,
34 error,
34 error,
35 fileset,
35 fileset,
36 match as matchmod,
36 match as matchmod,
37 obsolete as obsmod,
37 obsolete as obsmod,
38 patch,
38 patch,
39 pathutil,
39 pathutil,
40 phases,
40 phases,
41 pycompat,
41 pycompat,
42 repoview,
42 repoview,
43 scmutil,
43 scmutil,
44 sparse,
44 sparse,
45 subrepo,
45 subrepo,
46 subrepoutil,
46 subrepoutil,
47 util,
47 util,
48 )
48 )
49 from .utils import (
49 from .utils import (
50 dateutil,
50 dateutil,
51 stringutil,
51 stringutil,
52 )
52 )
53
53
54 propertycache = util.propertycache
54 propertycache = util.propertycache
55
55
56
56
57 class basectx(object):
57 class basectx(object):
58 """A basectx object represents the common logic for its children:
58 """A basectx object represents the common logic for its children:
59 changectx: read-only context that is already present in the repo,
59 changectx: read-only context that is already present in the repo,
60 workingctx: a context that represents the working directory and can
60 workingctx: a context that represents the working directory and can
61 be committed,
61 be committed,
62 memctx: a context that represents changes in-memory and can also
62 memctx: a context that represents changes in-memory and can also
63 be committed."""
63 be committed."""
64
64
65 def __init__(self, repo):
65 def __init__(self, repo):
66 self._repo = repo
66 self._repo = repo
67
67
68 def __bytes__(self):
68 def __bytes__(self):
69 return short(self.node())
69 return short(self.node())
70
70
71 __str__ = encoding.strmethod(__bytes__)
71 __str__ = encoding.strmethod(__bytes__)
72
72
73 def __repr__(self):
73 def __repr__(self):
74 return "<%s %s>" % (type(self).__name__, str(self))
74 return "<%s %s>" % (type(self).__name__, str(self))
75
75
76 def __eq__(self, other):
76 def __eq__(self, other):
77 try:
77 try:
78 return type(self) == type(other) and self._rev == other._rev
78 return type(self) == type(other) and self._rev == other._rev
79 except AttributeError:
79 except AttributeError:
80 return False
80 return False
81
81
82 def __ne__(self, other):
82 def __ne__(self, other):
83 return not (self == other)
83 return not (self == other)
84
84
85 def __contains__(self, key):
85 def __contains__(self, key):
86 return key in self._manifest
86 return key in self._manifest
87
87
88 def __getitem__(self, key):
88 def __getitem__(self, key):
89 return self.filectx(key)
89 return self.filectx(key)
90
90
91 def __iter__(self):
91 def __iter__(self):
92 return iter(self._manifest)
92 return iter(self._manifest)
93
93
94 def _buildstatusmanifest(self, status):
94 def _buildstatusmanifest(self, status):
95 """Builds a manifest that includes the given status results, if this is
95 """Builds a manifest that includes the given status results, if this is
96 a working copy context. For non-working copy contexts, it just returns
96 a working copy context. For non-working copy contexts, it just returns
97 the normal manifest."""
97 the normal manifest."""
98 return self.manifest()
98 return self.manifest()
99
99
100 def _matchstatus(self, other, match):
100 def _matchstatus(self, other, match):
101 """This internal method provides a way for child objects to override the
101 """This internal method provides a way for child objects to override the
102 match operator.
102 match operator.
103 """
103 """
104 return match
104 return match
105
105
106 def _buildstatus(
106 def _buildstatus(
107 self, other, s, match, listignored, listclean, listunknown
107 self, other, s, match, listignored, listclean, listunknown
108 ):
108 ):
109 """build a status with respect to another context"""
109 """build a status with respect to another context"""
110 # Load earliest manifest first for caching reasons. More specifically,
110 # Load earliest manifest first for caching reasons. More specifically,
111 # if you have revisions 1000 and 1001, 1001 is probably stored as a
111 # if you have revisions 1000 and 1001, 1001 is probably stored as a
112 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
112 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
113 # 1000 and cache it so that when you read 1001, we just need to apply a
113 # 1000 and cache it so that when you read 1001, we just need to apply a
114 # delta to what's in the cache. So that's one full reconstruction + one
114 # delta to what's in the cache. So that's one full reconstruction + one
115 # delta application.
115 # delta application.
116 mf2 = None
116 mf2 = None
117 if self.rev() is not None and self.rev() < other.rev():
117 if self.rev() is not None and self.rev() < other.rev():
118 mf2 = self._buildstatusmanifest(s)
118 mf2 = self._buildstatusmanifest(s)
119 mf1 = other._buildstatusmanifest(s)
119 mf1 = other._buildstatusmanifest(s)
120 if mf2 is None:
120 if mf2 is None:
121 mf2 = self._buildstatusmanifest(s)
121 mf2 = self._buildstatusmanifest(s)
122
122
123 modified, added = [], []
123 modified, added = [], []
124 removed = []
124 removed = []
125 clean = []
125 clean = []
126 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
126 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
127 deletedset = set(deleted)
127 deletedset = set(deleted)
128 d = mf1.diff(mf2, match=match, clean=listclean)
128 d = mf1.diff(mf2, match=match, clean=listclean)
129 for fn, value in pycompat.iteritems(d):
129 for fn, value in pycompat.iteritems(d):
130 if fn in deletedset:
130 if fn in deletedset:
131 continue
131 continue
132 if value is None:
132 if value is None:
133 clean.append(fn)
133 clean.append(fn)
134 continue
134 continue
135 (node1, flag1), (node2, flag2) = value
135 (node1, flag1), (node2, flag2) = value
136 if node1 is None:
136 if node1 is None:
137 added.append(fn)
137 added.append(fn)
138 elif node2 is None:
138 elif node2 is None:
139 removed.append(fn)
139 removed.append(fn)
140 elif flag1 != flag2:
140 elif flag1 != flag2:
141 modified.append(fn)
141 modified.append(fn)
142 elif node2 not in wdirfilenodeids:
142 elif node2 not in wdirfilenodeids:
143 # When comparing files between two commits, we save time by
143 # When comparing files between two commits, we save time by
144 # not comparing the file contents when the nodeids differ.
144 # not comparing the file contents when the nodeids differ.
145 # Note that this means we incorrectly report a reverted change
145 # Note that this means we incorrectly report a reverted change
146 # to a file as a modification.
146 # to a file as a modification.
147 modified.append(fn)
147 modified.append(fn)
148 elif self[fn].cmp(other[fn]):
148 elif self[fn].cmp(other[fn]):
149 modified.append(fn)
149 modified.append(fn)
150 else:
150 else:
151 clean.append(fn)
151 clean.append(fn)
152
152
153 if removed:
153 if removed:
154 # need to filter files if they are already reported as removed
154 # need to filter files if they are already reported as removed
155 unknown = [
155 unknown = [
156 fn
156 fn
157 for fn in unknown
157 for fn in unknown
158 if fn not in mf1 and (not match or match(fn))
158 if fn not in mf1 and (not match or match(fn))
159 ]
159 ]
160 ignored = [
160 ignored = [
161 fn
161 fn
162 for fn in ignored
162 for fn in ignored
163 if fn not in mf1 and (not match or match(fn))
163 if fn not in mf1 and (not match or match(fn))
164 ]
164 ]
165 # if they're deleted, don't report them as removed
165 # if they're deleted, don't report them as removed
166 removed = [fn for fn in removed if fn not in deletedset]
166 removed = [fn for fn in removed if fn not in deletedset]
167
167
168 return scmutil.status(
168 return scmutil.status(
169 modified, added, removed, deleted, unknown, ignored, clean
169 modified, added, removed, deleted, unknown, ignored, clean
170 )
170 )
171
171
172 @propertycache
172 @propertycache
173 def substate(self):
173 def substate(self):
174 return subrepoutil.state(self, self._repo.ui)
174 return subrepoutil.state(self, self._repo.ui)
175
175
176 def subrev(self, subpath):
176 def subrev(self, subpath):
177 return self.substate[subpath][1]
177 return self.substate[subpath][1]
178
178
179 def rev(self):
179 def rev(self):
180 return self._rev
180 return self._rev
181
181
182 def node(self):
182 def node(self):
183 return self._node
183 return self._node
184
184
185 def hex(self):
185 def hex(self):
186 return hex(self.node())
186 return hex(self.node())
187
187
188 def manifest(self):
188 def manifest(self):
189 return self._manifest
189 return self._manifest
190
190
191 def manifestctx(self):
191 def manifestctx(self):
192 return self._manifestctx
192 return self._manifestctx
193
193
194 def repo(self):
194 def repo(self):
195 return self._repo
195 return self._repo
196
196
197 def phasestr(self):
197 def phasestr(self):
198 return phases.phasenames[self.phase()]
198 return phases.phasenames[self.phase()]
199
199
200 def mutable(self):
200 def mutable(self):
201 return self.phase() > phases.public
201 return self.phase() > phases.public
202
202
203 def matchfileset(self, cwd, expr, badfn=None):
203 def matchfileset(self, cwd, expr, badfn=None):
204 return fileset.match(self, cwd, expr, badfn=badfn)
204 return fileset.match(self, cwd, expr, badfn=badfn)
205
205
206 def obsolete(self):
206 def obsolete(self):
207 """True if the changeset is obsolete"""
207 """True if the changeset is obsolete"""
208 return self.rev() in obsmod.getrevs(self._repo, b'obsolete')
208 return self.rev() in obsmod.getrevs(self._repo, b'obsolete')
209
209
210 def extinct(self):
210 def extinct(self):
211 """True if the changeset is extinct"""
211 """True if the changeset is extinct"""
212 return self.rev() in obsmod.getrevs(self._repo, b'extinct')
212 return self.rev() in obsmod.getrevs(self._repo, b'extinct')
213
213
214 def orphan(self):
214 def orphan(self):
215 """True if the changeset is not obsolete, but its ancestor is"""
215 """True if the changeset is not obsolete, but its ancestor is"""
216 return self.rev() in obsmod.getrevs(self._repo, b'orphan')
216 return self.rev() in obsmod.getrevs(self._repo, b'orphan')
217
217
218 def phasedivergent(self):
218 def phasedivergent(self):
219 """True if the changeset tries to be a successor of a public changeset
219 """True if the changeset tries to be a successor of a public changeset
220
220
221 Only non-public and non-obsolete changesets may be phase-divergent.
221 Only non-public and non-obsolete changesets may be phase-divergent.
222 """
222 """
223 return self.rev() in obsmod.getrevs(self._repo, b'phasedivergent')
223 return self.rev() in obsmod.getrevs(self._repo, b'phasedivergent')
224
224
225 def contentdivergent(self):
225 def contentdivergent(self):
226 """Is a successor of a changeset with multiple possible successor sets
226 """Is a successor of a changeset with multiple possible successor sets
227
227
228 Only non-public and non-obsolete changesets may be content-divergent.
228 Only non-public and non-obsolete changesets may be content-divergent.
229 """
229 """
230 return self.rev() in obsmod.getrevs(self._repo, b'contentdivergent')
230 return self.rev() in obsmod.getrevs(self._repo, b'contentdivergent')
231
231
232 def isunstable(self):
232 def isunstable(self):
233 """True if the changeset is either orphan, phase-divergent or
233 """True if the changeset is either orphan, phase-divergent or
234 content-divergent"""
234 content-divergent"""
235 return self.orphan() or self.phasedivergent() or self.contentdivergent()
235 return self.orphan() or self.phasedivergent() or self.contentdivergent()
236
236
237 def instabilities(self):
237 def instabilities(self):
238 """return the list of instabilities affecting this changeset.
238 """return the list of instabilities affecting this changeset.
239
239
240 Instabilities are returned as strings. possible values are:
240 Instabilities are returned as strings. possible values are:
241 - orphan,
241 - orphan,
242 - phase-divergent,
242 - phase-divergent,
243 - content-divergent.
243 - content-divergent.
244 """
244 """
245 instabilities = []
245 instabilities = []
246 if self.orphan():
246 if self.orphan():
247 instabilities.append(b'orphan')
247 instabilities.append(b'orphan')
248 if self.phasedivergent():
248 if self.phasedivergent():
249 instabilities.append(b'phase-divergent')
249 instabilities.append(b'phase-divergent')
250 if self.contentdivergent():
250 if self.contentdivergent():
251 instabilities.append(b'content-divergent')
251 instabilities.append(b'content-divergent')
252 return instabilities
252 return instabilities
253
253
254 def parents(self):
254 def parents(self):
255 """return contexts for each parent changeset"""
255 """return contexts for each parent changeset"""
256 return self._parents
256 return self._parents
257
257
258 def p1(self):
258 def p1(self):
259 return self._parents[0]
259 return self._parents[0]
260
260
261 def p2(self):
261 def p2(self):
262 parents = self._parents
262 parents = self._parents
263 if len(parents) == 2:
263 if len(parents) == 2:
264 return parents[1]
264 return parents[1]
265 return self._repo[nullrev]
265 return self._repo[nullrev]
266
266
267 def _fileinfo(self, path):
267 def _fileinfo(self, path):
268 if '_manifest' in self.__dict__:
268 if '_manifest' in self.__dict__:
269 try:
269 try:
270 return self._manifest[path], self._manifest.flags(path)
270 return self._manifest[path], self._manifest.flags(path)
271 except KeyError:
271 except KeyError:
272 raise error.ManifestLookupError(
272 raise error.ManifestLookupError(
273 self._node, path, _(b'not found in manifest')
273 self._node, path, _(b'not found in manifest')
274 )
274 )
275 if '_manifestdelta' in self.__dict__ or path in self.files():
275 if '_manifestdelta' in self.__dict__ or path in self.files():
276 if path in self._manifestdelta:
276 if path in self._manifestdelta:
277 return (
277 return (
278 self._manifestdelta[path],
278 self._manifestdelta[path],
279 self._manifestdelta.flags(path),
279 self._manifestdelta.flags(path),
280 )
280 )
281 mfl = self._repo.manifestlog
281 mfl = self._repo.manifestlog
282 try:
282 try:
283 node, flag = mfl[self._changeset.manifest].find(path)
283 node, flag = mfl[self._changeset.manifest].find(path)
284 except KeyError:
284 except KeyError:
285 raise error.ManifestLookupError(
285 raise error.ManifestLookupError(
286 self._node, path, _(b'not found in manifest')
286 self._node, path, _(b'not found in manifest')
287 )
287 )
288
288
289 return node, flag
289 return node, flag
290
290
291 def filenode(self, path):
291 def filenode(self, path):
292 return self._fileinfo(path)[0]
292 return self._fileinfo(path)[0]
293
293
294 def flags(self, path):
294 def flags(self, path):
295 try:
295 try:
296 return self._fileinfo(path)[1]
296 return self._fileinfo(path)[1]
297 except error.LookupError:
297 except error.LookupError:
298 return b''
298 return b''
299
299
300 @propertycache
300 @propertycache
301 def _copies(self):
301 def _copies(self):
302 return copies.computechangesetcopies(self)
302 return copies.computechangesetcopies(self)
303
303
304 def p1copies(self):
304 def p1copies(self):
305 return self._copies[0]
305 return self._copies[0]
306
306
307 def p2copies(self):
307 def p2copies(self):
308 return self._copies[1]
308 return self._copies[1]
309
309
310 def sub(self, path, allowcreate=True):
310 def sub(self, path, allowcreate=True):
311 '''return a subrepo for the stored revision of path, never wdir()'''
311 '''return a subrepo for the stored revision of path, never wdir()'''
312 return subrepo.subrepo(self, path, allowcreate=allowcreate)
312 return subrepo.subrepo(self, path, allowcreate=allowcreate)
313
313
314 def nullsub(self, path, pctx):
314 def nullsub(self, path, pctx):
315 return subrepo.nullsubrepo(self, path, pctx)
315 return subrepo.nullsubrepo(self, path, pctx)
316
316
317 def workingsub(self, path):
317 def workingsub(self, path):
318 '''return a subrepo for the stored revision, or wdir if this is a wdir
318 '''return a subrepo for the stored revision, or wdir if this is a wdir
319 context.
319 context.
320 '''
320 '''
321 return subrepo.subrepo(self, path, allowwdir=True)
321 return subrepo.subrepo(self, path, allowwdir=True)
322
322
323 def match(
323 def match(
324 self,
324 self,
325 pats=None,
325 pats=None,
326 include=None,
326 include=None,
327 exclude=None,
327 exclude=None,
328 default=b'glob',
328 default=b'glob',
329 listsubrepos=False,
329 listsubrepos=False,
330 badfn=None,
330 badfn=None,
331 cwd=None,
331 cwd=None,
332 ):
332 ):
333 r = self._repo
333 r = self._repo
334 if not cwd:
334 if not cwd:
335 cwd = r.getcwd()
335 cwd = r.getcwd()
336 return matchmod.match(
336 return matchmod.match(
337 r.root,
337 r.root,
338 cwd,
338 cwd,
339 pats,
339 pats,
340 include,
340 include,
341 exclude,
341 exclude,
342 default,
342 default,
343 auditor=r.nofsauditor,
343 auditor=r.nofsauditor,
344 ctx=self,
344 ctx=self,
345 listsubrepos=listsubrepos,
345 listsubrepos=listsubrepos,
346 badfn=badfn,
346 badfn=badfn,
347 )
347 )
348
348
349 def diff(
349 def diff(
350 self,
350 self,
351 ctx2=None,
351 ctx2=None,
352 match=None,
352 match=None,
353 changes=None,
353 changes=None,
354 opts=None,
354 opts=None,
355 losedatafn=None,
355 losedatafn=None,
356 pathfn=None,
356 pathfn=None,
357 copy=None,
357 copy=None,
358 copysourcematch=None,
358 copysourcematch=None,
359 hunksfilterfn=None,
359 hunksfilterfn=None,
360 ):
360 ):
361 """Returns a diff generator for the given contexts and matcher"""
361 """Returns a diff generator for the given contexts and matcher"""
362 if ctx2 is None:
362 if ctx2 is None:
363 ctx2 = self.p1()
363 ctx2 = self.p1()
364 if ctx2 is not None:
364 if ctx2 is not None:
365 ctx2 = self._repo[ctx2]
365 ctx2 = self._repo[ctx2]
366 return patch.diff(
366 return patch.diff(
367 self._repo,
367 self._repo,
368 ctx2,
368 ctx2,
369 self,
369 self,
370 match=match,
370 match=match,
371 changes=changes,
371 changes=changes,
372 opts=opts,
372 opts=opts,
373 losedatafn=losedatafn,
373 losedatafn=losedatafn,
374 pathfn=pathfn,
374 pathfn=pathfn,
375 copy=copy,
375 copy=copy,
376 copysourcematch=copysourcematch,
376 copysourcematch=copysourcematch,
377 hunksfilterfn=hunksfilterfn,
377 hunksfilterfn=hunksfilterfn,
378 )
378 )
379
379
380 def dirs(self):
380 def dirs(self):
381 return self._manifest.dirs()
381 return self._manifest.dirs()
382
382
383 def hasdir(self, dir):
383 def hasdir(self, dir):
384 return self._manifest.hasdir(dir)
384 return self._manifest.hasdir(dir)
385
385
386 def status(
386 def status(
387 self,
387 self,
388 other=None,
388 other=None,
389 match=None,
389 match=None,
390 listignored=False,
390 listignored=False,
391 listclean=False,
391 listclean=False,
392 listunknown=False,
392 listunknown=False,
393 listsubrepos=False,
393 listsubrepos=False,
394 ):
394 ):
395 """return status of files between two nodes or node and working
395 """return status of files between two nodes or node and working
396 directory.
396 directory.
397
397
398 If other is None, compare this node with working directory.
398 If other is None, compare this node with working directory.
399
399
400 returns (modified, added, removed, deleted, unknown, ignored, clean)
400 returns (modified, added, removed, deleted, unknown, ignored, clean)
401 """
401 """
402
402
403 ctx1 = self
403 ctx1 = self
404 ctx2 = self._repo[other]
404 ctx2 = self._repo[other]
405
405
406 # This next code block is, admittedly, fragile logic that tests for
406 # This next code block is, admittedly, fragile logic that tests for
407 # reversing the contexts and wouldn't need to exist if it weren't for
407 # reversing the contexts and wouldn't need to exist if it weren't for
408 # the fast (and common) code path of comparing the working directory
408 # the fast (and common) code path of comparing the working directory
409 # with its first parent.
409 # with its first parent.
410 #
410 #
411 # What we're aiming for here is the ability to call:
411 # What we're aiming for here is the ability to call:
412 #
412 #
413 # workingctx.status(parentctx)
413 # workingctx.status(parentctx)
414 #
414 #
415 # If we always built the manifest for each context and compared those,
415 # If we always built the manifest for each context and compared those,
416 # then we'd be done. But the special case of the above call means we
416 # then we'd be done. But the special case of the above call means we
417 # just copy the manifest of the parent.
417 # just copy the manifest of the parent.
418 reversed = False
418 reversed = False
419 if not isinstance(ctx1, changectx) and isinstance(ctx2, changectx):
419 if not isinstance(ctx1, changectx) and isinstance(ctx2, changectx):
420 reversed = True
420 reversed = True
421 ctx1, ctx2 = ctx2, ctx1
421 ctx1, ctx2 = ctx2, ctx1
422
422
423 match = self._repo.narrowmatch(match)
423 match = self._repo.narrowmatch(match)
424 match = ctx2._matchstatus(ctx1, match)
424 match = ctx2._matchstatus(ctx1, match)
425 r = scmutil.status([], [], [], [], [], [], [])
425 r = scmutil.status([], [], [], [], [], [], [])
426 r = ctx2._buildstatus(
426 r = ctx2._buildstatus(
427 ctx1, r, match, listignored, listclean, listunknown
427 ctx1, r, match, listignored, listclean, listunknown
428 )
428 )
429
429
430 if reversed:
430 if reversed:
431 # Reverse added and removed. Clear deleted, unknown and ignored as
431 # Reverse added and removed. Clear deleted, unknown and ignored as
432 # these make no sense to reverse.
432 # these make no sense to reverse.
433 r = scmutil.status(
433 r = scmutil.status(
434 r.modified, r.removed, r.added, [], [], [], r.clean
434 r.modified, r.removed, r.added, [], [], [], r.clean
435 )
435 )
436
436
437 if listsubrepos:
437 if listsubrepos:
438 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
438 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
439 try:
439 try:
440 rev2 = ctx2.subrev(subpath)
440 rev2 = ctx2.subrev(subpath)
441 except KeyError:
441 except KeyError:
442 # A subrepo that existed in node1 was deleted between
442 # A subrepo that existed in node1 was deleted between
443 # node1 and node2 (inclusive). Thus, ctx2's substate
443 # node1 and node2 (inclusive). Thus, ctx2's substate
444 # won't contain that subpath. The best we can do ignore it.
444 # won't contain that subpath. The best we can do ignore it.
445 rev2 = None
445 rev2 = None
446 submatch = matchmod.subdirmatcher(subpath, match)
446 submatch = matchmod.subdirmatcher(subpath, match)
447 s = sub.status(
447 s = sub.status(
448 rev2,
448 rev2,
449 match=submatch,
449 match=submatch,
450 ignored=listignored,
450 ignored=listignored,
451 clean=listclean,
451 clean=listclean,
452 unknown=listunknown,
452 unknown=listunknown,
453 listsubrepos=True,
453 listsubrepos=True,
454 )
454 )
455 for k in (
455 for k in (
456 'modified',
456 'modified',
457 'added',
457 'added',
458 'removed',
458 'removed',
459 'deleted',
459 'deleted',
460 'unknown',
460 'unknown',
461 'ignored',
461 'ignored',
462 'clean',
462 'clean',
463 ):
463 ):
464 rfiles, sfiles = getattr(r, k), getattr(s, k)
464 rfiles, sfiles = getattr(r, k), getattr(s, k)
465 rfiles.extend(b"%s/%s" % (subpath, f) for f in sfiles)
465 rfiles.extend(b"%s/%s" % (subpath, f) for f in sfiles)
466
466
467 r.modified.sort()
467 r.modified.sort()
468 r.added.sort()
468 r.added.sort()
469 r.removed.sort()
469 r.removed.sort()
470 r.deleted.sort()
470 r.deleted.sort()
471 r.unknown.sort()
471 r.unknown.sort()
472 r.ignored.sort()
472 r.ignored.sort()
473 r.clean.sort()
473 r.clean.sort()
474
474
475 return r
475 return r
476
476
477
477
478 class changectx(basectx):
478 class changectx(basectx):
479 """A changecontext object makes access to data related to a particular
479 """A changecontext object makes access to data related to a particular
480 changeset convenient. It represents a read-only context already present in
480 changeset convenient. It represents a read-only context already present in
481 the repo."""
481 the repo."""
482
482
483 def __init__(self, repo, rev, node, maybe_filtered=True):
483 def __init__(self, repo, rev, node, maybe_filtered=True):
484 super(changectx, self).__init__(repo)
484 super(changectx, self).__init__(repo)
485 self._rev = rev
485 self._rev = rev
486 self._node = node
486 self._node = node
487 # When maybe_filtered is True, the revision might be affected by
487 # When maybe_filtered is True, the revision might be affected by
488 # changelog filtering and operation through the filtered changelog must be used.
488 # changelog filtering and operation through the filtered changelog must be used.
489 #
489 #
490 # When maybe_filtered is False, the revision has already been checked
490 # When maybe_filtered is False, the revision has already been checked
491 # against filtering and is not filtered. Operation through the
491 # against filtering and is not filtered. Operation through the
492 # unfiltered changelog might be used in some case.
492 # unfiltered changelog might be used in some case.
493 self._maybe_filtered = maybe_filtered
493 self._maybe_filtered = maybe_filtered
494
494
495 def __hash__(self):
495 def __hash__(self):
496 try:
496 try:
497 return hash(self._rev)
497 return hash(self._rev)
498 except AttributeError:
498 except AttributeError:
499 return id(self)
499 return id(self)
500
500
501 def __nonzero__(self):
501 def __nonzero__(self):
502 return self._rev != nullrev
502 return self._rev != nullrev
503
503
504 __bool__ = __nonzero__
504 __bool__ = __nonzero__
505
505
506 @propertycache
506 @propertycache
507 def _changeset(self):
507 def _changeset(self):
508 if self._maybe_filtered:
508 if self._maybe_filtered:
509 repo = self._repo
509 repo = self._repo
510 else:
510 else:
511 repo = self._repo.unfiltered()
511 repo = self._repo.unfiltered()
512 return repo.changelog.changelogrevision(self.rev())
512 return repo.changelog.changelogrevision(self.rev())
513
513
514 @propertycache
514 @propertycache
515 def _manifest(self):
515 def _manifest(self):
516 return self._manifestctx.read()
516 return self._manifestctx.read()
517
517
518 @property
518 @property
519 def _manifestctx(self):
519 def _manifestctx(self):
520 return self._repo.manifestlog[self._changeset.manifest]
520 return self._repo.manifestlog[self._changeset.manifest]
521
521
522 @propertycache
522 @propertycache
523 def _manifestdelta(self):
523 def _manifestdelta(self):
524 return self._manifestctx.readdelta()
524 return self._manifestctx.readdelta()
525
525
526 @propertycache
526 @propertycache
527 def _parents(self):
527 def _parents(self):
528 repo = self._repo
528 repo = self._repo
529 if self._maybe_filtered:
529 if self._maybe_filtered:
530 cl = repo.changelog
530 cl = repo.changelog
531 else:
531 else:
532 cl = repo.unfiltered().changelog
532 cl = repo.unfiltered().changelog
533
533
534 p1, p2 = cl.parentrevs(self._rev)
534 p1, p2 = cl.parentrevs(self._rev)
535 if p2 == nullrev:
535 if p2 == nullrev:
536 return [repo[p1]]
536 return [repo[p1]]
537 return [repo[p1], repo[p2]]
537 return [repo[p1], repo[p2]]
538
538
539 def changeset(self):
539 def changeset(self):
540 c = self._changeset
540 c = self._changeset
541 return (
541 return (
542 c.manifest,
542 c.manifest,
543 c.user,
543 c.user,
544 c.date,
544 c.date,
545 c.files,
545 c.files,
546 c.description,
546 c.description,
547 c.extra,
547 c.extra,
548 )
548 )
549
549
550 def manifestnode(self):
550 def manifestnode(self):
551 return self._changeset.manifest
551 return self._changeset.manifest
552
552
553 def user(self):
553 def user(self):
554 return self._changeset.user
554 return self._changeset.user
555
555
556 def date(self):
556 def date(self):
557 return self._changeset.date
557 return self._changeset.date
558
558
559 def files(self):
559 def files(self):
560 return self._changeset.files
560 return self._changeset.files
561
561
562 def filesmodified(self):
562 def filesmodified(self):
563 modified = set(self.files())
563 modified = set(self.files())
564 modified.difference_update(self.filesadded())
564 modified.difference_update(self.filesadded())
565 modified.difference_update(self.filesremoved())
565 modified.difference_update(self.filesremoved())
566 return sorted(modified)
566 return sorted(modified)
567
567
568 def filesadded(self):
568 def filesadded(self):
569 filesadded = self._changeset.filesadded
569 filesadded = self._changeset.filesadded
570 compute_on_none = True
570 compute_on_none = True
571 if self._repo.filecopiesmode == b'changeset-sidedata':
571 if self._repo.filecopiesmode == b'changeset-sidedata':
572 compute_on_none = False
572 compute_on_none = False
573 else:
573 else:
574 source = self._repo.ui.config(b'experimental', b'copies.read-from')
574 source = self._repo.ui.config(b'experimental', b'copies.read-from')
575 if source == b'changeset-only':
575 if source == b'changeset-only':
576 compute_on_none = False
576 compute_on_none = False
577 elif source != b'compatibility':
577 elif source != b'compatibility':
578 # filelog mode, ignore any changelog content
578 # filelog mode, ignore any changelog content
579 filesadded = None
579 filesadded = None
580 if filesadded is None:
580 if filesadded is None:
581 if compute_on_none:
581 if compute_on_none:
582 filesadded = copies.computechangesetfilesadded(self)
582 filesadded = copies.computechangesetfilesadded(self)
583 else:
583 else:
584 filesadded = []
584 filesadded = []
585 return filesadded
585 return filesadded
586
586
587 def filesremoved(self):
587 def filesremoved(self):
588 filesremoved = self._changeset.filesremoved
588 filesremoved = self._changeset.filesremoved
589 compute_on_none = True
589 compute_on_none = True
590 if self._repo.filecopiesmode == b'changeset-sidedata':
590 if self._repo.filecopiesmode == b'changeset-sidedata':
591 compute_on_none = False
591 compute_on_none = False
592 else:
592 else:
593 source = self._repo.ui.config(b'experimental', b'copies.read-from')
593 source = self._repo.ui.config(b'experimental', b'copies.read-from')
594 if source == b'changeset-only':
594 if source == b'changeset-only':
595 compute_on_none = False
595 compute_on_none = False
596 elif source != b'compatibility':
596 elif source != b'compatibility':
597 # filelog mode, ignore any changelog content
597 # filelog mode, ignore any changelog content
598 filesremoved = None
598 filesremoved = None
599 if filesremoved is None:
599 if filesremoved is None:
600 if compute_on_none:
600 if compute_on_none:
601 filesremoved = copies.computechangesetfilesremoved(self)
601 filesremoved = copies.computechangesetfilesremoved(self)
602 else:
602 else:
603 filesremoved = []
603 filesremoved = []
604 return filesremoved
604 return filesremoved
605
605
606 @propertycache
606 @propertycache
607 def _copies(self):
607 def _copies(self):
608 p1copies = self._changeset.p1copies
608 p1copies = self._changeset.p1copies
609 p2copies = self._changeset.p2copies
609 p2copies = self._changeset.p2copies
610 compute_on_none = True
610 compute_on_none = True
611 if self._repo.filecopiesmode == b'changeset-sidedata':
611 if self._repo.filecopiesmode == b'changeset-sidedata':
612 compute_on_none = False
612 compute_on_none = False
613 else:
613 else:
614 source = self._repo.ui.config(b'experimental', b'copies.read-from')
614 source = self._repo.ui.config(b'experimental', b'copies.read-from')
615 # If config says to get copy metadata only from changeset, then
615 # If config says to get copy metadata only from changeset, then
616 # return that, defaulting to {} if there was no copy metadata. In
616 # return that, defaulting to {} if there was no copy metadata. In
617 # compatibility mode, we return copy data from the changeset if it
617 # compatibility mode, we return copy data from the changeset if it
618 # was recorded there, and otherwise we fall back to getting it from
618 # was recorded there, and otherwise we fall back to getting it from
619 # the filelogs (below).
619 # the filelogs (below).
620 #
620 #
621 # If we are in compatiblity mode and there is not data in the
621 # If we are in compatiblity mode and there is not data in the
622 # changeset), we get the copy metadata from the filelogs.
622 # changeset), we get the copy metadata from the filelogs.
623 #
623 #
624 # otherwise, when config said to read only from filelog, we get the
624 # otherwise, when config said to read only from filelog, we get the
625 # copy metadata from the filelogs.
625 # copy metadata from the filelogs.
626 if source == b'changeset-only':
626 if source == b'changeset-only':
627 compute_on_none = False
627 compute_on_none = False
628 elif source != b'compatibility':
628 elif source != b'compatibility':
629 # filelog mode, ignore any changelog content
629 # filelog mode, ignore any changelog content
630 p1copies = p2copies = None
630 p1copies = p2copies = None
631 if p1copies is None:
631 if p1copies is None:
632 if compute_on_none:
632 if compute_on_none:
633 p1copies, p2copies = super(changectx, self)._copies
633 p1copies, p2copies = super(changectx, self)._copies
634 else:
634 else:
635 if p1copies is None:
635 if p1copies is None:
636 p1copies = {}
636 p1copies = {}
637 if p2copies is None:
637 if p2copies is None:
638 p2copies = {}
638 p2copies = {}
639 return p1copies, p2copies
639 return p1copies, p2copies
640
640
641 def description(self):
641 def description(self):
642 return self._changeset.description
642 return self._changeset.description
643
643
644 def branch(self):
644 def branch(self):
645 return encoding.tolocal(self._changeset.extra.get(b"branch"))
645 return encoding.tolocal(self._changeset.extra.get(b"branch"))
646
646
647 def closesbranch(self):
647 def closesbranch(self):
648 return b'close' in self._changeset.extra
648 return b'close' in self._changeset.extra
649
649
650 def extra(self):
650 def extra(self):
651 """Return a dict of extra information."""
651 """Return a dict of extra information."""
652 return self._changeset.extra
652 return self._changeset.extra
653
653
654 def tags(self):
654 def tags(self):
655 """Return a list of byte tag names"""
655 """Return a list of byte tag names"""
656 return self._repo.nodetags(self._node)
656 return self._repo.nodetags(self._node)
657
657
658 def bookmarks(self):
658 def bookmarks(self):
659 """Return a list of byte bookmark names."""
659 """Return a list of byte bookmark names."""
660 return self._repo.nodebookmarks(self._node)
660 return self._repo.nodebookmarks(self._node)
661
661
662 def phase(self):
662 def phase(self):
663 return self._repo._phasecache.phase(self._repo, self._rev)
663 return self._repo._phasecache.phase(self._repo, self._rev)
664
664
665 def hidden(self):
665 def hidden(self):
666 return self._rev in repoview.filterrevs(self._repo, b'visible')
666 return self._rev in repoview.filterrevs(self._repo, b'visible')
667
667
668 def isinmemory(self):
668 def isinmemory(self):
669 return False
669 return False
670
670
671 def children(self):
671 def children(self):
672 """return list of changectx contexts for each child changeset.
672 """return list of changectx contexts for each child changeset.
673
673
674 This returns only the immediate child changesets. Use descendants() to
674 This returns only the immediate child changesets. Use descendants() to
675 recursively walk children.
675 recursively walk children.
676 """
676 """
677 c = self._repo.changelog.children(self._node)
677 c = self._repo.changelog.children(self._node)
678 return [self._repo[x] for x in c]
678 return [self._repo[x] for x in c]
679
679
680 def ancestors(self):
680 def ancestors(self):
681 for a in self._repo.changelog.ancestors([self._rev]):
681 for a in self._repo.changelog.ancestors([self._rev]):
682 yield self._repo[a]
682 yield self._repo[a]
683
683
684 def descendants(self):
684 def descendants(self):
685 """Recursively yield all children of the changeset.
685 """Recursively yield all children of the changeset.
686
686
687 For just the immediate children, use children()
687 For just the immediate children, use children()
688 """
688 """
689 for d in self._repo.changelog.descendants([self._rev]):
689 for d in self._repo.changelog.descendants([self._rev]):
690 yield self._repo[d]
690 yield self._repo[d]
691
691
692 def filectx(self, path, fileid=None, filelog=None):
692 def filectx(self, path, fileid=None, filelog=None):
693 """get a file context from this changeset"""
693 """get a file context from this changeset"""
694 if fileid is None:
694 if fileid is None:
695 fileid = self.filenode(path)
695 fileid = self.filenode(path)
696 return filectx(
696 return filectx(
697 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
697 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
698 )
698 )
699
699
700 def ancestor(self, c2, warn=False):
700 def ancestor(self, c2, warn=False):
701 """return the "best" ancestor context of self and c2
701 """return the "best" ancestor context of self and c2
702
702
703 If there are multiple candidates, it will show a message and check
703 If there are multiple candidates, it will show a message and check
704 merge.preferancestor configuration before falling back to the
704 merge.preferancestor configuration before falling back to the
705 revlog ancestor."""
705 revlog ancestor."""
706 # deal with workingctxs
706 # deal with workingctxs
707 n2 = c2._node
707 n2 = c2._node
708 if n2 is None:
708 if n2 is None:
709 n2 = c2._parents[0]._node
709 n2 = c2._parents[0]._node
710 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
710 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
711 if not cahs:
711 if not cahs:
712 anc = nullid
712 anc = nullid
713 elif len(cahs) == 1:
713 elif len(cahs) == 1:
714 anc = cahs[0]
714 anc = cahs[0]
715 else:
715 else:
716 # experimental config: merge.preferancestor
716 # experimental config: merge.preferancestor
717 for r in self._repo.ui.configlist(b'merge', b'preferancestor'):
717 for r in self._repo.ui.configlist(b'merge', b'preferancestor'):
718 try:
718 try:
719 ctx = scmutil.revsymbol(self._repo, r)
719 ctx = scmutil.revsymbol(self._repo, r)
720 except error.RepoLookupError:
720 except error.RepoLookupError:
721 continue
721 continue
722 anc = ctx.node()
722 anc = ctx.node()
723 if anc in cahs:
723 if anc in cahs:
724 break
724 break
725 else:
725 else:
726 anc = self._repo.changelog.ancestor(self._node, n2)
726 anc = self._repo.changelog.ancestor(self._node, n2)
727 if warn:
727 if warn:
728 self._repo.ui.status(
728 self._repo.ui.status(
729 (
729 (
730 _(b"note: using %s as ancestor of %s and %s\n")
730 _(b"note: using %s as ancestor of %s and %s\n")
731 % (short(anc), short(self._node), short(n2))
731 % (short(anc), short(self._node), short(n2))
732 )
732 )
733 + b''.join(
733 + b''.join(
734 _(
734 _(
735 b" alternatively, use --config "
735 b" alternatively, use --config "
736 b"merge.preferancestor=%s\n"
736 b"merge.preferancestor=%s\n"
737 )
737 )
738 % short(n)
738 % short(n)
739 for n in sorted(cahs)
739 for n in sorted(cahs)
740 if n != anc
740 if n != anc
741 )
741 )
742 )
742 )
743 return self._repo[anc]
743 return self._repo[anc]
744
744
745 def isancestorof(self, other):
745 def isancestorof(self, other):
746 """True if this changeset is an ancestor of other"""
746 """True if this changeset is an ancestor of other"""
747 return self._repo.changelog.isancestorrev(self._rev, other._rev)
747 return self._repo.changelog.isancestorrev(self._rev, other._rev)
748
748
749 def walk(self, match):
749 def walk(self, match):
750 '''Generates matching file names.'''
750 '''Generates matching file names.'''
751
751
752 # Wrap match.bad method to have message with nodeid
752 # Wrap match.bad method to have message with nodeid
753 def bad(fn, msg):
753 def bad(fn, msg):
754 # The manifest doesn't know about subrepos, so don't complain about
754 # The manifest doesn't know about subrepos, so don't complain about
755 # paths into valid subrepos.
755 # paths into valid subrepos.
756 if any(fn == s or fn.startswith(s + b'/') for s in self.substate):
756 if any(fn == s or fn.startswith(s + b'/') for s in self.substate):
757 return
757 return
758 match.bad(fn, _(b'no such file in rev %s') % self)
758 match.bad(fn, _(b'no such file in rev %s') % self)
759
759
760 m = matchmod.badmatch(self._repo.narrowmatch(match), bad)
760 m = matchmod.badmatch(self._repo.narrowmatch(match), bad)
761 return self._manifest.walk(m)
761 return self._manifest.walk(m)
762
762
763 def matches(self, match):
763 def matches(self, match):
764 return self.walk(match)
764 return self.walk(match)
765
765
766
766
767 class basefilectx(object):
767 class basefilectx(object):
768 """A filecontext object represents the common logic for its children:
768 """A filecontext object represents the common logic for its children:
769 filectx: read-only access to a filerevision that is already present
769 filectx: read-only access to a filerevision that is already present
770 in the repo,
770 in the repo,
771 workingfilectx: a filecontext that represents files from the working
771 workingfilectx: a filecontext that represents files from the working
772 directory,
772 directory,
773 memfilectx: a filecontext that represents files in-memory,
773 memfilectx: a filecontext that represents files in-memory,
774 """
774 """
775
775
776 @propertycache
776 @propertycache
777 def _filelog(self):
777 def _filelog(self):
778 return self._repo.file(self._path)
778 return self._repo.file(self._path)
779
779
780 @propertycache
780 @propertycache
781 def _changeid(self):
781 def _changeid(self):
782 if '_changectx' in self.__dict__:
782 if '_changectx' in self.__dict__:
783 return self._changectx.rev()
783 return self._changectx.rev()
784 elif '_descendantrev' in self.__dict__:
784 elif '_descendantrev' in self.__dict__:
785 # this file context was created from a revision with a known
785 # this file context was created from a revision with a known
786 # descendant, we can (lazily) correct for linkrev aliases
786 # descendant, we can (lazily) correct for linkrev aliases
787 return self._adjustlinkrev(self._descendantrev)
787 return self._adjustlinkrev(self._descendantrev)
788 else:
788 else:
789 return self._filelog.linkrev(self._filerev)
789 return self._filelog.linkrev(self._filerev)
790
790
791 @propertycache
791 @propertycache
792 def _filenode(self):
792 def _filenode(self):
793 if '_fileid' in self.__dict__:
793 if '_fileid' in self.__dict__:
794 return self._filelog.lookup(self._fileid)
794 return self._filelog.lookup(self._fileid)
795 else:
795 else:
796 return self._changectx.filenode(self._path)
796 return self._changectx.filenode(self._path)
797
797
798 @propertycache
798 @propertycache
799 def _filerev(self):
799 def _filerev(self):
800 return self._filelog.rev(self._filenode)
800 return self._filelog.rev(self._filenode)
801
801
802 @propertycache
802 @propertycache
803 def _repopath(self):
803 def _repopath(self):
804 return self._path
804 return self._path
805
805
806 def __nonzero__(self):
806 def __nonzero__(self):
807 try:
807 try:
808 self._filenode
808 self._filenode
809 return True
809 return True
810 except error.LookupError:
810 except error.LookupError:
811 # file is missing
811 # file is missing
812 return False
812 return False
813
813
814 __bool__ = __nonzero__
814 __bool__ = __nonzero__
815
815
816 def __bytes__(self):
816 def __bytes__(self):
817 try:
817 try:
818 return b"%s@%s" % (self.path(), self._changectx)
818 return b"%s@%s" % (self.path(), self._changectx)
819 except error.LookupError:
819 except error.LookupError:
820 return b"%s@???" % self.path()
820 return b"%s@???" % self.path()
821
821
822 __str__ = encoding.strmethod(__bytes__)
822 __str__ = encoding.strmethod(__bytes__)
823
823
824 def __repr__(self):
824 def __repr__(self):
825 return "<%s %s>" % (type(self).__name__, str(self))
825 return "<%s %s>" % (type(self).__name__, str(self))
826
826
827 def __hash__(self):
827 def __hash__(self):
828 try:
828 try:
829 return hash((self._path, self._filenode))
829 return hash((self._path, self._filenode))
830 except AttributeError:
830 except AttributeError:
831 return id(self)
831 return id(self)
832
832
833 def __eq__(self, other):
833 def __eq__(self, other):
834 try:
834 try:
835 return (
835 return (
836 type(self) == type(other)
836 type(self) == type(other)
837 and self._path == other._path
837 and self._path == other._path
838 and self._filenode == other._filenode
838 and self._filenode == other._filenode
839 )
839 )
840 except AttributeError:
840 except AttributeError:
841 return False
841 return False
842
842
843 def __ne__(self, other):
843 def __ne__(self, other):
844 return not (self == other)
844 return not (self == other)
845
845
846 def filerev(self):
846 def filerev(self):
847 return self._filerev
847 return self._filerev
848
848
849 def filenode(self):
849 def filenode(self):
850 return self._filenode
850 return self._filenode
851
851
852 @propertycache
852 @propertycache
853 def _flags(self):
853 def _flags(self):
854 return self._changectx.flags(self._path)
854 return self._changectx.flags(self._path)
855
855
856 def flags(self):
856 def flags(self):
857 return self._flags
857 return self._flags
858
858
859 def filelog(self):
859 def filelog(self):
860 return self._filelog
860 return self._filelog
861
861
862 def rev(self):
862 def rev(self):
863 return self._changeid
863 return self._changeid
864
864
865 def linkrev(self):
865 def linkrev(self):
866 return self._filelog.linkrev(self._filerev)
866 return self._filelog.linkrev(self._filerev)
867
867
868 def node(self):
868 def node(self):
869 return self._changectx.node()
869 return self._changectx.node()
870
870
871 def hex(self):
871 def hex(self):
872 return self._changectx.hex()
872 return self._changectx.hex()
873
873
874 def user(self):
874 def user(self):
875 return self._changectx.user()
875 return self._changectx.user()
876
876
877 def date(self):
877 def date(self):
878 return self._changectx.date()
878 return self._changectx.date()
879
879
880 def files(self):
880 def files(self):
881 return self._changectx.files()
881 return self._changectx.files()
882
882
883 def description(self):
883 def description(self):
884 return self._changectx.description()
884 return self._changectx.description()
885
885
886 def branch(self):
886 def branch(self):
887 return self._changectx.branch()
887 return self._changectx.branch()
888
888
889 def extra(self):
889 def extra(self):
890 return self._changectx.extra()
890 return self._changectx.extra()
891
891
892 def phase(self):
892 def phase(self):
893 return self._changectx.phase()
893 return self._changectx.phase()
894
894
895 def phasestr(self):
895 def phasestr(self):
896 return self._changectx.phasestr()
896 return self._changectx.phasestr()
897
897
898 def obsolete(self):
898 def obsolete(self):
899 return self._changectx.obsolete()
899 return self._changectx.obsolete()
900
900
901 def instabilities(self):
901 def instabilities(self):
902 return self._changectx.instabilities()
902 return self._changectx.instabilities()
903
903
904 def manifest(self):
904 def manifest(self):
905 return self._changectx.manifest()
905 return self._changectx.manifest()
906
906
907 def changectx(self):
907 def changectx(self):
908 return self._changectx
908 return self._changectx
909
909
910 def renamed(self):
910 def renamed(self):
911 return self._copied
911 return self._copied
912
912
913 def copysource(self):
913 def copysource(self):
914 return self._copied and self._copied[0]
914 return self._copied and self._copied[0]
915
915
916 def repo(self):
916 def repo(self):
917 return self._repo
917 return self._repo
918
918
919 def size(self):
919 def size(self):
920 return len(self.data())
920 return len(self.data())
921
921
922 def path(self):
922 def path(self):
923 return self._path
923 return self._path
924
924
925 def isbinary(self):
925 def isbinary(self):
926 try:
926 try:
927 return stringutil.binary(self.data())
927 return stringutil.binary(self.data())
928 except IOError:
928 except IOError:
929 return False
929 return False
930
930
931 def isexec(self):
931 def isexec(self):
932 return b'x' in self.flags()
932 return b'x' in self.flags()
933
933
934 def islink(self):
934 def islink(self):
935 return b'l' in self.flags()
935 return b'l' in self.flags()
936
936
937 def isabsent(self):
937 def isabsent(self):
938 """whether this filectx represents a file not in self._changectx
938 """whether this filectx represents a file not in self._changectx
939
939
940 This is mainly for merge code to detect change/delete conflicts. This is
940 This is mainly for merge code to detect change/delete conflicts. This is
941 expected to be True for all subclasses of basectx."""
941 expected to be True for all subclasses of basectx."""
942 return False
942 return False
943
943
944 _customcmp = False
944 _customcmp = False
945
945
946 def cmp(self, fctx):
946 def cmp(self, fctx):
947 """compare with other file context
947 """compare with other file context
948
948
949 returns True if different than fctx.
949 returns True if different than fctx.
950 """
950 """
951 if fctx._customcmp:
951 if fctx._customcmp:
952 return fctx.cmp(self)
952 return fctx.cmp(self)
953
953
954 if self._filenode is None:
954 if self._filenode is None:
955 raise error.ProgrammingError(
955 raise error.ProgrammingError(
956 b'filectx.cmp() must be reimplemented if not backed by revlog'
956 b'filectx.cmp() must be reimplemented if not backed by revlog'
957 )
957 )
958
958
959 if fctx._filenode is None:
959 if fctx._filenode is None:
960 if self._repo._encodefilterpats:
960 if self._repo._encodefilterpats:
961 # can't rely on size() because wdir content may be decoded
961 # can't rely on size() because wdir content may be decoded
962 return self._filelog.cmp(self._filenode, fctx.data())
962 return self._filelog.cmp(self._filenode, fctx.data())
963 if self.size() - 4 == fctx.size():
963 if self.size() - 4 == fctx.size():
964 # size() can match:
964 # size() can match:
965 # if file data starts with '\1\n', empty metadata block is
965 # if file data starts with '\1\n', empty metadata block is
966 # prepended, which adds 4 bytes to filelog.size().
966 # prepended, which adds 4 bytes to filelog.size().
967 return self._filelog.cmp(self._filenode, fctx.data())
967 return self._filelog.cmp(self._filenode, fctx.data())
968 if self.size() == fctx.size():
968 if self.size() == fctx.size():
969 # size() matches: need to compare content
969 # size() matches: need to compare content
970 return self._filelog.cmp(self._filenode, fctx.data())
970 return self._filelog.cmp(self._filenode, fctx.data())
971
971
972 # size() differs
972 # size() differs
973 return True
973 return True
974
974
975 def _adjustlinkrev(self, srcrev, inclusive=False, stoprev=None):
975 def _adjustlinkrev(self, srcrev, inclusive=False, stoprev=None):
976 """return the first ancestor of <srcrev> introducing <fnode>
976 """return the first ancestor of <srcrev> introducing <fnode>
977
977
978 If the linkrev of the file revision does not point to an ancestor of
978 If the linkrev of the file revision does not point to an ancestor of
979 srcrev, we'll walk down the ancestors until we find one introducing
979 srcrev, we'll walk down the ancestors until we find one introducing
980 this file revision.
980 this file revision.
981
981
982 :srcrev: the changeset revision we search ancestors from
982 :srcrev: the changeset revision we search ancestors from
983 :inclusive: if true, the src revision will also be checked
983 :inclusive: if true, the src revision will also be checked
984 :stoprev: an optional revision to stop the walk at. If no introduction
984 :stoprev: an optional revision to stop the walk at. If no introduction
985 of this file content could be found before this floor
985 of this file content could be found before this floor
986 revision, the function will returns "None" and stops its
986 revision, the function will returns "None" and stops its
987 iteration.
987 iteration.
988 """
988 """
989 repo = self._repo
989 repo = self._repo
990 cl = repo.unfiltered().changelog
990 cl = repo.unfiltered().changelog
991 mfl = repo.manifestlog
991 mfl = repo.manifestlog
992 # fetch the linkrev
992 # fetch the linkrev
993 lkr = self.linkrev()
993 lkr = self.linkrev()
994 if srcrev == lkr:
994 if srcrev == lkr:
995 return lkr
995 return lkr
996 # hack to reuse ancestor computation when searching for renames
996 # hack to reuse ancestor computation when searching for renames
997 memberanc = getattr(self, '_ancestrycontext', None)
997 memberanc = getattr(self, '_ancestrycontext', None)
998 iteranc = None
998 iteranc = None
999 if srcrev is None:
999 if srcrev is None:
1000 # wctx case, used by workingfilectx during mergecopy
1000 # wctx case, used by workingfilectx during mergecopy
1001 revs = [p.rev() for p in self._repo[None].parents()]
1001 revs = [p.rev() for p in self._repo[None].parents()]
1002 inclusive = True # we skipped the real (revless) source
1002 inclusive = True # we skipped the real (revless) source
1003 else:
1003 else:
1004 revs = [srcrev]
1004 revs = [srcrev]
1005 if memberanc is None:
1005 if memberanc is None:
1006 memberanc = iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1006 memberanc = iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1007 # check if this linkrev is an ancestor of srcrev
1007 # check if this linkrev is an ancestor of srcrev
1008 if lkr not in memberanc:
1008 if lkr not in memberanc:
1009 if iteranc is None:
1009 if iteranc is None:
1010 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1010 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1011 fnode = self._filenode
1011 fnode = self._filenode
1012 path = self._path
1012 path = self._path
1013 for a in iteranc:
1013 for a in iteranc:
1014 if stoprev is not None and a < stoprev:
1014 if stoprev is not None and a < stoprev:
1015 return None
1015 return None
1016 ac = cl.read(a) # get changeset data (we avoid object creation)
1016 ac = cl.read(a) # get changeset data (we avoid object creation)
1017 if path in ac[3]: # checking the 'files' field.
1017 if path in ac[3]: # checking the 'files' field.
1018 # The file has been touched, check if the content is
1018 # The file has been touched, check if the content is
1019 # similar to the one we search for.
1019 # similar to the one we search for.
1020 if fnode == mfl[ac[0]].readfast().get(path):
1020 if fnode == mfl[ac[0]].readfast().get(path):
1021 return a
1021 return a
1022 # In theory, we should never get out of that loop without a result.
1022 # In theory, we should never get out of that loop without a result.
1023 # But if manifest uses a buggy file revision (not children of the
1023 # But if manifest uses a buggy file revision (not children of the
1024 # one it replaces) we could. Such a buggy situation will likely
1024 # one it replaces) we could. Such a buggy situation will likely
1025 # result is crash somewhere else at to some point.
1025 # result is crash somewhere else at to some point.
1026 return lkr
1026 return lkr
1027
1027
1028 def isintroducedafter(self, changelogrev):
1028 def isintroducedafter(self, changelogrev):
1029 """True if a filectx has been introduced after a given floor revision
1029 """True if a filectx has been introduced after a given floor revision
1030 """
1030 """
1031 if self.linkrev() >= changelogrev:
1031 if self.linkrev() >= changelogrev:
1032 return True
1032 return True
1033 introrev = self._introrev(stoprev=changelogrev)
1033 introrev = self._introrev(stoprev=changelogrev)
1034 if introrev is None:
1034 if introrev is None:
1035 return False
1035 return False
1036 return introrev >= changelogrev
1036 return introrev >= changelogrev
1037
1037
1038 def introrev(self):
1038 def introrev(self):
1039 """return the rev of the changeset which introduced this file revision
1039 """return the rev of the changeset which introduced this file revision
1040
1040
1041 This method is different from linkrev because it take into account the
1041 This method is different from linkrev because it take into account the
1042 changeset the filectx was created from. It ensures the returned
1042 changeset the filectx was created from. It ensures the returned
1043 revision is one of its ancestors. This prevents bugs from
1043 revision is one of its ancestors. This prevents bugs from
1044 'linkrev-shadowing' when a file revision is used by multiple
1044 'linkrev-shadowing' when a file revision is used by multiple
1045 changesets.
1045 changesets.
1046 """
1046 """
1047 return self._introrev()
1047 return self._introrev()
1048
1048
1049 def _introrev(self, stoprev=None):
1049 def _introrev(self, stoprev=None):
1050 """
1050 """
1051 Same as `introrev` but, with an extra argument to limit changelog
1051 Same as `introrev` but, with an extra argument to limit changelog
1052 iteration range in some internal usecase.
1052 iteration range in some internal usecase.
1053
1053
1054 If `stoprev` is set, the `introrev` will not be searched past that
1054 If `stoprev` is set, the `introrev` will not be searched past that
1055 `stoprev` revision and "None" might be returned. This is useful to
1055 `stoprev` revision and "None" might be returned. This is useful to
1056 limit the iteration range.
1056 limit the iteration range.
1057 """
1057 """
1058 toprev = None
1058 toprev = None
1059 attrs = vars(self)
1059 attrs = vars(self)
1060 if '_changeid' in attrs:
1060 if '_changeid' in attrs:
1061 # We have a cached value already
1061 # We have a cached value already
1062 toprev = self._changeid
1062 toprev = self._changeid
1063 elif '_changectx' in attrs:
1063 elif '_changectx' in attrs:
1064 # We know which changelog entry we are coming from
1064 # We know which changelog entry we are coming from
1065 toprev = self._changectx.rev()
1065 toprev = self._changectx.rev()
1066
1066
1067 if toprev is not None:
1067 if toprev is not None:
1068 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1068 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1069 elif '_descendantrev' in attrs:
1069 elif '_descendantrev' in attrs:
1070 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1070 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1071 # be nice and cache the result of the computation
1071 # be nice and cache the result of the computation
1072 if introrev is not None:
1072 if introrev is not None:
1073 self._changeid = introrev
1073 self._changeid = introrev
1074 return introrev
1074 return introrev
1075 else:
1075 else:
1076 return self.linkrev()
1076 return self.linkrev()
1077
1077
1078 def introfilectx(self):
1078 def introfilectx(self):
1079 """Return filectx having identical contents, but pointing to the
1079 """Return filectx having identical contents, but pointing to the
1080 changeset revision where this filectx was introduced"""
1080 changeset revision where this filectx was introduced"""
1081 introrev = self.introrev()
1081 introrev = self.introrev()
1082 if self.rev() == introrev:
1082 if self.rev() == introrev:
1083 return self
1083 return self
1084 return self.filectx(self.filenode(), changeid=introrev)
1084 return self.filectx(self.filenode(), changeid=introrev)
1085
1085
1086 def _parentfilectx(self, path, fileid, filelog):
1086 def _parentfilectx(self, path, fileid, filelog):
1087 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1087 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1088 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1088 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1089 if '_changeid' in vars(self) or '_changectx' in vars(self):
1089 if '_changeid' in vars(self) or '_changectx' in vars(self):
1090 # If self is associated with a changeset (probably explicitly
1090 # If self is associated with a changeset (probably explicitly
1091 # fed), ensure the created filectx is associated with a
1091 # fed), ensure the created filectx is associated with a
1092 # changeset that is an ancestor of self.changectx.
1092 # changeset that is an ancestor of self.changectx.
1093 # This lets us later use _adjustlinkrev to get a correct link.
1093 # This lets us later use _adjustlinkrev to get a correct link.
1094 fctx._descendantrev = self.rev()
1094 fctx._descendantrev = self.rev()
1095 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1095 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1096 elif '_descendantrev' in vars(self):
1096 elif '_descendantrev' in vars(self):
1097 # Otherwise propagate _descendantrev if we have one associated.
1097 # Otherwise propagate _descendantrev if we have one associated.
1098 fctx._descendantrev = self._descendantrev
1098 fctx._descendantrev = self._descendantrev
1099 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1099 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1100 return fctx
1100 return fctx
1101
1101
1102 def parents(self):
1102 def parents(self):
1103 _path = self._path
1103 _path = self._path
1104 fl = self._filelog
1104 fl = self._filelog
1105 parents = self._filelog.parents(self._filenode)
1105 parents = self._filelog.parents(self._filenode)
1106 pl = [(_path, node, fl) for node in parents if node != nullid]
1106 pl = [(_path, node, fl) for node in parents if node != nullid]
1107
1107
1108 r = fl.renamed(self._filenode)
1108 r = fl.renamed(self._filenode)
1109 if r:
1109 if r:
1110 # - In the simple rename case, both parent are nullid, pl is empty.
1110 # - In the simple rename case, both parent are nullid, pl is empty.
1111 # - In case of merge, only one of the parent is null id and should
1111 # - In case of merge, only one of the parent is null id and should
1112 # be replaced with the rename information. This parent is -always-
1112 # be replaced with the rename information. This parent is -always-
1113 # the first one.
1113 # the first one.
1114 #
1114 #
1115 # As null id have always been filtered out in the previous list
1115 # As null id have always been filtered out in the previous list
1116 # comprehension, inserting to 0 will always result in "replacing
1116 # comprehension, inserting to 0 will always result in "replacing
1117 # first nullid parent with rename information.
1117 # first nullid parent with rename information.
1118 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
1118 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
1119
1119
1120 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
1120 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
1121
1121
1122 def p1(self):
1122 def p1(self):
1123 return self.parents()[0]
1123 return self.parents()[0]
1124
1124
1125 def p2(self):
1125 def p2(self):
1126 p = self.parents()
1126 p = self.parents()
1127 if len(p) == 2:
1127 if len(p) == 2:
1128 return p[1]
1128 return p[1]
1129 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
1129 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
1130
1130
1131 def annotate(self, follow=False, skiprevs=None, diffopts=None):
1131 def annotate(self, follow=False, skiprevs=None, diffopts=None):
1132 """Returns a list of annotateline objects for each line in the file
1132 """Returns a list of annotateline objects for each line in the file
1133
1133
1134 - line.fctx is the filectx of the node where that line was last changed
1134 - line.fctx is the filectx of the node where that line was last changed
1135 - line.lineno is the line number at the first appearance in the managed
1135 - line.lineno is the line number at the first appearance in the managed
1136 file
1136 file
1137 - line.text is the data on that line (including newline character)
1137 - line.text is the data on that line (including newline character)
1138 """
1138 """
1139 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
1139 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
1140
1140
1141 def parents(f):
1141 def parents(f):
1142 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
1142 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
1143 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1143 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1144 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1144 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1145 # isn't an ancestor of the srcrev.
1145 # isn't an ancestor of the srcrev.
1146 f._changeid
1146 f._changeid
1147 pl = f.parents()
1147 pl = f.parents()
1148
1148
1149 # Don't return renamed parents if we aren't following.
1149 # Don't return renamed parents if we aren't following.
1150 if not follow:
1150 if not follow:
1151 pl = [p for p in pl if p.path() == f.path()]
1151 pl = [p for p in pl if p.path() == f.path()]
1152
1152
1153 # renamed filectx won't have a filelog yet, so set it
1153 # renamed filectx won't have a filelog yet, so set it
1154 # from the cache to save time
1154 # from the cache to save time
1155 for p in pl:
1155 for p in pl:
1156 if not '_filelog' in p.__dict__:
1156 if not '_filelog' in p.__dict__:
1157 p._filelog = getlog(p.path())
1157 p._filelog = getlog(p.path())
1158
1158
1159 return pl
1159 return pl
1160
1160
1161 # use linkrev to find the first changeset where self appeared
1161 # use linkrev to find the first changeset where self appeared
1162 base = self.introfilectx()
1162 base = self.introfilectx()
1163 if getattr(base, '_ancestrycontext', None) is None:
1163 if getattr(base, '_ancestrycontext', None) is None:
1164 cl = self._repo.changelog
1164 cl = self._repo.changelog
1165 if base.rev() is None:
1165 if base.rev() is None:
1166 # wctx is not inclusive, but works because _ancestrycontext
1166 # wctx is not inclusive, but works because _ancestrycontext
1167 # is used to test filelog revisions
1167 # is used to test filelog revisions
1168 ac = cl.ancestors(
1168 ac = cl.ancestors(
1169 [p.rev() for p in base.parents()], inclusive=True
1169 [p.rev() for p in base.parents()], inclusive=True
1170 )
1170 )
1171 else:
1171 else:
1172 ac = cl.ancestors([base.rev()], inclusive=True)
1172 ac = cl.ancestors([base.rev()], inclusive=True)
1173 base._ancestrycontext = ac
1173 base._ancestrycontext = ac
1174
1174
1175 return dagop.annotate(
1175 return dagop.annotate(
1176 base, parents, skiprevs=skiprevs, diffopts=diffopts
1176 base, parents, skiprevs=skiprevs, diffopts=diffopts
1177 )
1177 )
1178
1178
1179 def ancestors(self, followfirst=False):
1179 def ancestors(self, followfirst=False):
1180 visit = {}
1180 visit = {}
1181 c = self
1181 c = self
1182 if followfirst:
1182 if followfirst:
1183 cut = 1
1183 cut = 1
1184 else:
1184 else:
1185 cut = None
1185 cut = None
1186
1186
1187 while True:
1187 while True:
1188 for parent in c.parents()[:cut]:
1188 for parent in c.parents()[:cut]:
1189 visit[(parent.linkrev(), parent.filenode())] = parent
1189 visit[(parent.linkrev(), parent.filenode())] = parent
1190 if not visit:
1190 if not visit:
1191 break
1191 break
1192 c = visit.pop(max(visit))
1192 c = visit.pop(max(visit))
1193 yield c
1193 yield c
1194
1194
1195 def decodeddata(self):
1195 def decodeddata(self):
1196 """Returns `data()` after running repository decoding filters.
1196 """Returns `data()` after running repository decoding filters.
1197
1197
1198 This is often equivalent to how the data would be expressed on disk.
1198 This is often equivalent to how the data would be expressed on disk.
1199 """
1199 """
1200 return self._repo.wwritedata(self.path(), self.data())
1200 return self._repo.wwritedata(self.path(), self.data())
1201
1201
1202
1202
1203 class filectx(basefilectx):
1203 class filectx(basefilectx):
1204 """A filecontext object makes access to data related to a particular
1204 """A filecontext object makes access to data related to a particular
1205 filerevision convenient."""
1205 filerevision convenient."""
1206
1206
1207 def __init__(
1207 def __init__(
1208 self,
1208 self,
1209 repo,
1209 repo,
1210 path,
1210 path,
1211 changeid=None,
1211 changeid=None,
1212 fileid=None,
1212 fileid=None,
1213 filelog=None,
1213 filelog=None,
1214 changectx=None,
1214 changectx=None,
1215 ):
1215 ):
1216 """changeid must be a revision number, if specified.
1216 """changeid must be a revision number, if specified.
1217 fileid can be a file revision or node."""
1217 fileid can be a file revision or node."""
1218 self._repo = repo
1218 self._repo = repo
1219 self._path = path
1219 self._path = path
1220
1220
1221 assert (
1221 assert (
1222 changeid is not None or fileid is not None or changectx is not None
1222 changeid is not None or fileid is not None or changectx is not None
1223 ), (
1223 ), (
1224 b"bad args: changeid=%r, fileid=%r, changectx=%r"
1224 b"bad args: changeid=%r, fileid=%r, changectx=%r"
1225 % (changeid, fileid, changectx,)
1225 % (changeid, fileid, changectx,)
1226 )
1226 )
1227
1227
1228 if filelog is not None:
1228 if filelog is not None:
1229 self._filelog = filelog
1229 self._filelog = filelog
1230
1230
1231 if changeid is not None:
1231 if changeid is not None:
1232 self._changeid = changeid
1232 self._changeid = changeid
1233 if changectx is not None:
1233 if changectx is not None:
1234 self._changectx = changectx
1234 self._changectx = changectx
1235 if fileid is not None:
1235 if fileid is not None:
1236 self._fileid = fileid
1236 self._fileid = fileid
1237
1237
1238 @propertycache
1238 @propertycache
1239 def _changectx(self):
1239 def _changectx(self):
1240 try:
1240 try:
1241 return self._repo[self._changeid]
1241 return self._repo[self._changeid]
1242 except error.FilteredRepoLookupError:
1242 except error.FilteredRepoLookupError:
1243 # Linkrev may point to any revision in the repository. When the
1243 # Linkrev may point to any revision in the repository. When the
1244 # repository is filtered this may lead to `filectx` trying to build
1244 # repository is filtered this may lead to `filectx` trying to build
1245 # `changectx` for filtered revision. In such case we fallback to
1245 # `changectx` for filtered revision. In such case we fallback to
1246 # creating `changectx` on the unfiltered version of the reposition.
1246 # creating `changectx` on the unfiltered version of the reposition.
1247 # This fallback should not be an issue because `changectx` from
1247 # This fallback should not be an issue because `changectx` from
1248 # `filectx` are not used in complex operations that care about
1248 # `filectx` are not used in complex operations that care about
1249 # filtering.
1249 # filtering.
1250 #
1250 #
1251 # This fallback is a cheap and dirty fix that prevent several
1251 # This fallback is a cheap and dirty fix that prevent several
1252 # crashes. It does not ensure the behavior is correct. However the
1252 # crashes. It does not ensure the behavior is correct. However the
1253 # behavior was not correct before filtering either and "incorrect
1253 # behavior was not correct before filtering either and "incorrect
1254 # behavior" is seen as better as "crash"
1254 # behavior" is seen as better as "crash"
1255 #
1255 #
1256 # Linkrevs have several serious troubles with filtering that are
1256 # Linkrevs have several serious troubles with filtering that are
1257 # complicated to solve. Proper handling of the issue here should be
1257 # complicated to solve. Proper handling of the issue here should be
1258 # considered when solving linkrev issue are on the table.
1258 # considered when solving linkrev issue are on the table.
1259 return self._repo.unfiltered()[self._changeid]
1259 return self._repo.unfiltered()[self._changeid]
1260
1260
1261 def filectx(self, fileid, changeid=None):
1261 def filectx(self, fileid, changeid=None):
1262 '''opens an arbitrary revision of the file without
1262 '''opens an arbitrary revision of the file without
1263 opening a new filelog'''
1263 opening a new filelog'''
1264 return filectx(
1264 return filectx(
1265 self._repo,
1265 self._repo,
1266 self._path,
1266 self._path,
1267 fileid=fileid,
1267 fileid=fileid,
1268 filelog=self._filelog,
1268 filelog=self._filelog,
1269 changeid=changeid,
1269 changeid=changeid,
1270 )
1270 )
1271
1271
1272 def rawdata(self):
1272 def rawdata(self):
1273 return self._filelog.rawdata(self._filenode)
1273 return self._filelog.rawdata(self._filenode)
1274
1274
1275 def rawflags(self):
1275 def rawflags(self):
1276 """low-level revlog flags"""
1276 """low-level revlog flags"""
1277 return self._filelog.flags(self._filerev)
1277 return self._filelog.flags(self._filerev)
1278
1278
1279 def data(self):
1279 def data(self):
1280 try:
1280 try:
1281 return self._filelog.read(self._filenode)
1281 return self._filelog.read(self._filenode)
1282 except error.CensoredNodeError:
1282 except error.CensoredNodeError:
1283 if self._repo.ui.config(b"censor", b"policy") == b"ignore":
1283 if self._repo.ui.config(b"censor", b"policy") == b"ignore":
1284 return b""
1284 return b""
1285 raise error.Abort(
1285 raise error.Abort(
1286 _(b"censored node: %s") % short(self._filenode),
1286 _(b"censored node: %s") % short(self._filenode),
1287 hint=_(b"set censor.policy to ignore errors"),
1287 hint=_(b"set censor.policy to ignore errors"),
1288 )
1288 )
1289
1289
1290 def size(self):
1290 def size(self):
1291 return self._filelog.size(self._filerev)
1291 return self._filelog.size(self._filerev)
1292
1292
1293 @propertycache
1293 @propertycache
1294 def _copied(self):
1294 def _copied(self):
1295 """check if file was actually renamed in this changeset revision
1295 """check if file was actually renamed in this changeset revision
1296
1296
1297 If rename logged in file revision, we report copy for changeset only
1297 If rename logged in file revision, we report copy for changeset only
1298 if file revisions linkrev points back to the changeset in question
1298 if file revisions linkrev points back to the changeset in question
1299 or both changeset parents contain different file revisions.
1299 or both changeset parents contain different file revisions.
1300 """
1300 """
1301
1301
1302 renamed = self._filelog.renamed(self._filenode)
1302 renamed = self._filelog.renamed(self._filenode)
1303 if not renamed:
1303 if not renamed:
1304 return None
1304 return None
1305
1305
1306 if self.rev() == self.linkrev():
1306 if self.rev() == self.linkrev():
1307 return renamed
1307 return renamed
1308
1308
1309 name = self.path()
1309 name = self.path()
1310 fnode = self._filenode
1310 fnode = self._filenode
1311 for p in self._changectx.parents():
1311 for p in self._changectx.parents():
1312 try:
1312 try:
1313 if fnode == p.filenode(name):
1313 if fnode == p.filenode(name):
1314 return None
1314 return None
1315 except error.LookupError:
1315 except error.LookupError:
1316 pass
1316 pass
1317 return renamed
1317 return renamed
1318
1318
1319 def children(self):
1319 def children(self):
1320 # hard for renames
1320 # hard for renames
1321 c = self._filelog.children(self._filenode)
1321 c = self._filelog.children(self._filenode)
1322 return [
1322 return [
1323 filectx(self._repo, self._path, fileid=x, filelog=self._filelog)
1323 filectx(self._repo, self._path, fileid=x, filelog=self._filelog)
1324 for x in c
1324 for x in c
1325 ]
1325 ]
1326
1326
1327
1327
1328 class committablectx(basectx):
1328 class committablectx(basectx):
1329 """A committablectx object provides common functionality for a context that
1329 """A committablectx object provides common functionality for a context that
1330 wants the ability to commit, e.g. workingctx or memctx."""
1330 wants the ability to commit, e.g. workingctx or memctx."""
1331
1331
1332 def __init__(
1332 def __init__(
1333 self,
1333 self,
1334 repo,
1334 repo,
1335 text=b"",
1335 text=b"",
1336 user=None,
1336 user=None,
1337 date=None,
1337 date=None,
1338 extra=None,
1338 extra=None,
1339 changes=None,
1339 changes=None,
1340 branch=None,
1340 branch=None,
1341 ):
1341 ):
1342 super(committablectx, self).__init__(repo)
1342 super(committablectx, self).__init__(repo)
1343 self._rev = None
1343 self._rev = None
1344 self._node = None
1344 self._node = None
1345 self._text = text
1345 self._text = text
1346 if date:
1346 if date:
1347 self._date = dateutil.parsedate(date)
1347 self._date = dateutil.parsedate(date)
1348 if user:
1348 if user:
1349 self._user = user
1349 self._user = user
1350 if changes:
1350 if changes:
1351 self._status = changes
1351 self._status = changes
1352
1352
1353 self._extra = {}
1353 self._extra = {}
1354 if extra:
1354 if extra:
1355 self._extra = extra.copy()
1355 self._extra = extra.copy()
1356 if branch is not None:
1356 if branch is not None:
1357 self._extra[b'branch'] = encoding.fromlocal(branch)
1357 self._extra[b'branch'] = encoding.fromlocal(branch)
1358 if not self._extra.get(b'branch'):
1358 if not self._extra.get(b'branch'):
1359 self._extra[b'branch'] = b'default'
1359 self._extra[b'branch'] = b'default'
1360
1360
1361 def __bytes__(self):
1361 def __bytes__(self):
1362 return bytes(self._parents[0]) + b"+"
1362 return bytes(self._parents[0]) + b"+"
1363
1363
1364 __str__ = encoding.strmethod(__bytes__)
1364 __str__ = encoding.strmethod(__bytes__)
1365
1365
1366 def __nonzero__(self):
1366 def __nonzero__(self):
1367 return True
1367 return True
1368
1368
1369 __bool__ = __nonzero__
1369 __bool__ = __nonzero__
1370
1370
1371 @propertycache
1371 @propertycache
1372 def _status(self):
1372 def _status(self):
1373 return self._repo.status()
1373 return self._repo.status()
1374
1374
1375 @propertycache
1375 @propertycache
1376 def _user(self):
1376 def _user(self):
1377 return self._repo.ui.username()
1377 return self._repo.ui.username()
1378
1378
1379 @propertycache
1379 @propertycache
1380 def _date(self):
1380 def _date(self):
1381 ui = self._repo.ui
1381 ui = self._repo.ui
1382 date = ui.configdate(b'devel', b'default-date')
1382 date = ui.configdate(b'devel', b'default-date')
1383 if date is None:
1383 if date is None:
1384 date = dateutil.makedate()
1384 date = dateutil.makedate()
1385 return date
1385 return date
1386
1386
1387 def subrev(self, subpath):
1387 def subrev(self, subpath):
1388 return None
1388 return None
1389
1389
1390 def manifestnode(self):
1390 def manifestnode(self):
1391 return None
1391 return None
1392
1392
1393 def user(self):
1393 def user(self):
1394 return self._user or self._repo.ui.username()
1394 return self._user or self._repo.ui.username()
1395
1395
1396 def date(self):
1396 def date(self):
1397 return self._date
1397 return self._date
1398
1398
1399 def description(self):
1399 def description(self):
1400 return self._text
1400 return self._text
1401
1401
1402 def files(self):
1402 def files(self):
1403 return sorted(
1403 return sorted(
1404 self._status.modified + self._status.added + self._status.removed
1404 self._status.modified + self._status.added + self._status.removed
1405 )
1405 )
1406
1406
1407 def modified(self):
1407 def modified(self):
1408 return self._status.modified
1408 return self._status.modified
1409
1409
1410 def added(self):
1410 def added(self):
1411 return self._status.added
1411 return self._status.added
1412
1412
1413 def removed(self):
1413 def removed(self):
1414 return self._status.removed
1414 return self._status.removed
1415
1415
1416 def deleted(self):
1416 def deleted(self):
1417 return self._status.deleted
1417 return self._status.deleted
1418
1418
1419 filesmodified = modified
1419 filesmodified = modified
1420 filesadded = added
1420 filesadded = added
1421 filesremoved = removed
1421 filesremoved = removed
1422
1422
1423 def branch(self):
1423 def branch(self):
1424 return encoding.tolocal(self._extra[b'branch'])
1424 return encoding.tolocal(self._extra[b'branch'])
1425
1425
1426 def closesbranch(self):
1426 def closesbranch(self):
1427 return b'close' in self._extra
1427 return b'close' in self._extra
1428
1428
1429 def extra(self):
1429 def extra(self):
1430 return self._extra
1430 return self._extra
1431
1431
1432 def isinmemory(self):
1432 def isinmemory(self):
1433 return False
1433 return False
1434
1434
1435 def tags(self):
1435 def tags(self):
1436 return []
1436 return []
1437
1437
1438 def bookmarks(self):
1438 def bookmarks(self):
1439 b = []
1439 b = []
1440 for p in self.parents():
1440 for p in self.parents():
1441 b.extend(p.bookmarks())
1441 b.extend(p.bookmarks())
1442 return b
1442 return b
1443
1443
1444 def phase(self):
1444 def phase(self):
1445 phase = phases.newcommitphase(self._repo.ui)
1445 phase = phases.newcommitphase(self._repo.ui)
1446 for p in self.parents():
1446 for p in self.parents():
1447 phase = max(phase, p.phase())
1447 phase = max(phase, p.phase())
1448 return phase
1448 return phase
1449
1449
1450 def hidden(self):
1450 def hidden(self):
1451 return False
1451 return False
1452
1452
1453 def children(self):
1453 def children(self):
1454 return []
1454 return []
1455
1455
1456 def ancestor(self, c2):
1456 def ancestor(self, c2):
1457 """return the "best" ancestor context of self and c2"""
1457 """return the "best" ancestor context of self and c2"""
1458 return self._parents[0].ancestor(c2) # punt on two parents for now
1458 return self._parents[0].ancestor(c2) # punt on two parents for now
1459
1459
1460 def ancestors(self):
1460 def ancestors(self):
1461 for p in self._parents:
1461 for p in self._parents:
1462 yield p
1462 yield p
1463 for a in self._repo.changelog.ancestors(
1463 for a in self._repo.changelog.ancestors(
1464 [p.rev() for p in self._parents]
1464 [p.rev() for p in self._parents]
1465 ):
1465 ):
1466 yield self._repo[a]
1466 yield self._repo[a]
1467
1467
1468 def markcommitted(self, node):
1468 def markcommitted(self, node):
1469 """Perform post-commit cleanup necessary after committing this ctx
1469 """Perform post-commit cleanup necessary after committing this ctx
1470
1470
1471 Specifically, this updates backing stores this working context
1471 Specifically, this updates backing stores this working context
1472 wraps to reflect the fact that the changes reflected by this
1472 wraps to reflect the fact that the changes reflected by this
1473 workingctx have been committed. For example, it marks
1473 workingctx have been committed. For example, it marks
1474 modified and added files as normal in the dirstate.
1474 modified and added files as normal in the dirstate.
1475
1475
1476 """
1476 """
1477
1477
1478 def dirty(self, missing=False, merge=True, branch=True):
1478 def dirty(self, missing=False, merge=True, branch=True):
1479 return False
1479 return False
1480
1480
1481
1481
1482 class workingctx(committablectx):
1482 class workingctx(committablectx):
1483 """A workingctx object makes access to data related to
1483 """A workingctx object makes access to data related to
1484 the current working directory convenient.
1484 the current working directory convenient.
1485 date - any valid date string or (unixtime, offset), or None.
1485 date - any valid date string or (unixtime, offset), or None.
1486 user - username string, or None.
1486 user - username string, or None.
1487 extra - a dictionary of extra values, or None.
1487 extra - a dictionary of extra values, or None.
1488 changes - a list of file lists as returned by localrepo.status()
1488 changes - a list of file lists as returned by localrepo.status()
1489 or None to use the repository status.
1489 or None to use the repository status.
1490 """
1490 """
1491
1491
1492 def __init__(
1492 def __init__(
1493 self, repo, text=b"", user=None, date=None, extra=None, changes=None
1493 self, repo, text=b"", user=None, date=None, extra=None, changes=None
1494 ):
1494 ):
1495 branch = None
1495 branch = None
1496 if not extra or b'branch' not in extra:
1496 if not extra or b'branch' not in extra:
1497 try:
1497 try:
1498 branch = repo.dirstate.branch()
1498 branch = repo.dirstate.branch()
1499 except UnicodeDecodeError:
1499 except UnicodeDecodeError:
1500 raise error.Abort(_(b'branch name not in UTF-8!'))
1500 raise error.Abort(_(b'branch name not in UTF-8!'))
1501 super(workingctx, self).__init__(
1501 super(workingctx, self).__init__(
1502 repo, text, user, date, extra, changes, branch=branch
1502 repo, text, user, date, extra, changes, branch=branch
1503 )
1503 )
1504
1504
1505 def __iter__(self):
1505 def __iter__(self):
1506 d = self._repo.dirstate
1506 d = self._repo.dirstate
1507 for f in d:
1507 for f in d:
1508 if d[f] != b'r':
1508 if d[f] != b'r':
1509 yield f
1509 yield f
1510
1510
1511 def __contains__(self, key):
1511 def __contains__(self, key):
1512 return self._repo.dirstate[key] not in b"?r"
1512 return self._repo.dirstate[key] not in b"?r"
1513
1513
1514 def hex(self):
1514 def hex(self):
1515 return wdirhex
1515 return wdirhex
1516
1516
1517 @propertycache
1517 @propertycache
1518 def _parents(self):
1518 def _parents(self):
1519 p = self._repo.dirstate.parents()
1519 p = self._repo.dirstate.parents()
1520 if p[1] == nullid:
1520 if p[1] == nullid:
1521 p = p[:-1]
1521 p = p[:-1]
1522 # use unfiltered repo to delay/avoid loading obsmarkers
1522 # use unfiltered repo to delay/avoid loading obsmarkers
1523 unfi = self._repo.unfiltered()
1523 unfi = self._repo.unfiltered()
1524 return [
1524 return [
1525 changectx(
1525 changectx(
1526 self._repo, unfi.changelog.rev(n), n, maybe_filtered=False
1526 self._repo, unfi.changelog.rev(n), n, maybe_filtered=False
1527 )
1527 )
1528 for n in p
1528 for n in p
1529 ]
1529 ]
1530
1530
1531 def setparents(self, p1node, p2node=nullid):
1532 dirstate = self._repo.dirstate
1533 with dirstate.parentchange():
1534 copies = dirstate.setparents(p1node, p2node)
1535 pctx = self._repo[p1node]
1536 if copies:
1537 # Adjust copy records, the dirstate cannot do it, it
1538 # requires access to parents manifests. Preserve them
1539 # only for entries added to first parent.
1540 for f in copies:
1541 if f not in pctx and copies[f] in pctx:
1542 dirstate.copy(copies[f], f)
1543 if p2node == nullid:
1544 for f, s in sorted(dirstate.copies().items()):
1545 if f not in pctx and s not in pctx:
1546 dirstate.copy(None, f)
1547
1531 def _fileinfo(self, path):
1548 def _fileinfo(self, path):
1532 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1549 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1533 self._manifest
1550 self._manifest
1534 return super(workingctx, self)._fileinfo(path)
1551 return super(workingctx, self)._fileinfo(path)
1535
1552
1536 def _buildflagfunc(self):
1553 def _buildflagfunc(self):
1537 # Create a fallback function for getting file flags when the
1554 # Create a fallback function for getting file flags when the
1538 # filesystem doesn't support them
1555 # filesystem doesn't support them
1539
1556
1540 copiesget = self._repo.dirstate.copies().get
1557 copiesget = self._repo.dirstate.copies().get
1541 parents = self.parents()
1558 parents = self.parents()
1542 if len(parents) < 2:
1559 if len(parents) < 2:
1543 # when we have one parent, it's easy: copy from parent
1560 # when we have one parent, it's easy: copy from parent
1544 man = parents[0].manifest()
1561 man = parents[0].manifest()
1545
1562
1546 def func(f):
1563 def func(f):
1547 f = copiesget(f, f)
1564 f = copiesget(f, f)
1548 return man.flags(f)
1565 return man.flags(f)
1549
1566
1550 else:
1567 else:
1551 # merges are tricky: we try to reconstruct the unstored
1568 # merges are tricky: we try to reconstruct the unstored
1552 # result from the merge (issue1802)
1569 # result from the merge (issue1802)
1553 p1, p2 = parents
1570 p1, p2 = parents
1554 pa = p1.ancestor(p2)
1571 pa = p1.ancestor(p2)
1555 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1572 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1556
1573
1557 def func(f):
1574 def func(f):
1558 f = copiesget(f, f) # may be wrong for merges with copies
1575 f = copiesget(f, f) # may be wrong for merges with copies
1559 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1576 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1560 if fl1 == fl2:
1577 if fl1 == fl2:
1561 return fl1
1578 return fl1
1562 if fl1 == fla:
1579 if fl1 == fla:
1563 return fl2
1580 return fl2
1564 if fl2 == fla:
1581 if fl2 == fla:
1565 return fl1
1582 return fl1
1566 return b'' # punt for conflicts
1583 return b'' # punt for conflicts
1567
1584
1568 return func
1585 return func
1569
1586
1570 @propertycache
1587 @propertycache
1571 def _flagfunc(self):
1588 def _flagfunc(self):
1572 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1589 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1573
1590
1574 def flags(self, path):
1591 def flags(self, path):
1575 if '_manifest' in self.__dict__:
1592 if '_manifest' in self.__dict__:
1576 try:
1593 try:
1577 return self._manifest.flags(path)
1594 return self._manifest.flags(path)
1578 except KeyError:
1595 except KeyError:
1579 return b''
1596 return b''
1580
1597
1581 try:
1598 try:
1582 return self._flagfunc(path)
1599 return self._flagfunc(path)
1583 except OSError:
1600 except OSError:
1584 return b''
1601 return b''
1585
1602
1586 def filectx(self, path, filelog=None):
1603 def filectx(self, path, filelog=None):
1587 """get a file context from the working directory"""
1604 """get a file context from the working directory"""
1588 return workingfilectx(
1605 return workingfilectx(
1589 self._repo, path, workingctx=self, filelog=filelog
1606 self._repo, path, workingctx=self, filelog=filelog
1590 )
1607 )
1591
1608
1592 def dirty(self, missing=False, merge=True, branch=True):
1609 def dirty(self, missing=False, merge=True, branch=True):
1593 """check whether a working directory is modified"""
1610 """check whether a working directory is modified"""
1594 # check subrepos first
1611 # check subrepos first
1595 for s in sorted(self.substate):
1612 for s in sorted(self.substate):
1596 if self.sub(s).dirty(missing=missing):
1613 if self.sub(s).dirty(missing=missing):
1597 return True
1614 return True
1598 # check current working dir
1615 # check current working dir
1599 return (
1616 return (
1600 (merge and self.p2())
1617 (merge and self.p2())
1601 or (branch and self.branch() != self.p1().branch())
1618 or (branch and self.branch() != self.p1().branch())
1602 or self.modified()
1619 or self.modified()
1603 or self.added()
1620 or self.added()
1604 or self.removed()
1621 or self.removed()
1605 or (missing and self.deleted())
1622 or (missing and self.deleted())
1606 )
1623 )
1607
1624
1608 def add(self, list, prefix=b""):
1625 def add(self, list, prefix=b""):
1609 with self._repo.wlock():
1626 with self._repo.wlock():
1610 ui, ds = self._repo.ui, self._repo.dirstate
1627 ui, ds = self._repo.ui, self._repo.dirstate
1611 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1628 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1612 rejected = []
1629 rejected = []
1613 lstat = self._repo.wvfs.lstat
1630 lstat = self._repo.wvfs.lstat
1614 for f in list:
1631 for f in list:
1615 # ds.pathto() returns an absolute file when this is invoked from
1632 # ds.pathto() returns an absolute file when this is invoked from
1616 # the keyword extension. That gets flagged as non-portable on
1633 # the keyword extension. That gets flagged as non-portable on
1617 # Windows, since it contains the drive letter and colon.
1634 # Windows, since it contains the drive letter and colon.
1618 scmutil.checkportable(ui, os.path.join(prefix, f))
1635 scmutil.checkportable(ui, os.path.join(prefix, f))
1619 try:
1636 try:
1620 st = lstat(f)
1637 st = lstat(f)
1621 except OSError:
1638 except OSError:
1622 ui.warn(_(b"%s does not exist!\n") % uipath(f))
1639 ui.warn(_(b"%s does not exist!\n") % uipath(f))
1623 rejected.append(f)
1640 rejected.append(f)
1624 continue
1641 continue
1625 limit = ui.configbytes(b'ui', b'large-file-limit')
1642 limit = ui.configbytes(b'ui', b'large-file-limit')
1626 if limit != 0 and st.st_size > limit:
1643 if limit != 0 and st.st_size > limit:
1627 ui.warn(
1644 ui.warn(
1628 _(
1645 _(
1629 b"%s: up to %d MB of RAM may be required "
1646 b"%s: up to %d MB of RAM may be required "
1630 b"to manage this file\n"
1647 b"to manage this file\n"
1631 b"(use 'hg revert %s' to cancel the "
1648 b"(use 'hg revert %s' to cancel the "
1632 b"pending addition)\n"
1649 b"pending addition)\n"
1633 )
1650 )
1634 % (f, 3 * st.st_size // 1000000, uipath(f))
1651 % (f, 3 * st.st_size // 1000000, uipath(f))
1635 )
1652 )
1636 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1653 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1637 ui.warn(
1654 ui.warn(
1638 _(
1655 _(
1639 b"%s not added: only files and symlinks "
1656 b"%s not added: only files and symlinks "
1640 b"supported currently\n"
1657 b"supported currently\n"
1641 )
1658 )
1642 % uipath(f)
1659 % uipath(f)
1643 )
1660 )
1644 rejected.append(f)
1661 rejected.append(f)
1645 elif ds[f] in b'amn':
1662 elif ds[f] in b'amn':
1646 ui.warn(_(b"%s already tracked!\n") % uipath(f))
1663 ui.warn(_(b"%s already tracked!\n") % uipath(f))
1647 elif ds[f] == b'r':
1664 elif ds[f] == b'r':
1648 ds.normallookup(f)
1665 ds.normallookup(f)
1649 else:
1666 else:
1650 ds.add(f)
1667 ds.add(f)
1651 return rejected
1668 return rejected
1652
1669
1653 def forget(self, files, prefix=b""):
1670 def forget(self, files, prefix=b""):
1654 with self._repo.wlock():
1671 with self._repo.wlock():
1655 ds = self._repo.dirstate
1672 ds = self._repo.dirstate
1656 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1673 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1657 rejected = []
1674 rejected = []
1658 for f in files:
1675 for f in files:
1659 if f not in ds:
1676 if f not in ds:
1660 self._repo.ui.warn(_(b"%s not tracked!\n") % uipath(f))
1677 self._repo.ui.warn(_(b"%s not tracked!\n") % uipath(f))
1661 rejected.append(f)
1678 rejected.append(f)
1662 elif ds[f] != b'a':
1679 elif ds[f] != b'a':
1663 ds.remove(f)
1680 ds.remove(f)
1664 else:
1681 else:
1665 ds.drop(f)
1682 ds.drop(f)
1666 return rejected
1683 return rejected
1667
1684
1668 def copy(self, source, dest):
1685 def copy(self, source, dest):
1669 try:
1686 try:
1670 st = self._repo.wvfs.lstat(dest)
1687 st = self._repo.wvfs.lstat(dest)
1671 except OSError as err:
1688 except OSError as err:
1672 if err.errno != errno.ENOENT:
1689 if err.errno != errno.ENOENT:
1673 raise
1690 raise
1674 self._repo.ui.warn(
1691 self._repo.ui.warn(
1675 _(b"%s does not exist!\n") % self._repo.dirstate.pathto(dest)
1692 _(b"%s does not exist!\n") % self._repo.dirstate.pathto(dest)
1676 )
1693 )
1677 return
1694 return
1678 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1695 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1679 self._repo.ui.warn(
1696 self._repo.ui.warn(
1680 _(b"copy failed: %s is not a file or a symbolic link\n")
1697 _(b"copy failed: %s is not a file or a symbolic link\n")
1681 % self._repo.dirstate.pathto(dest)
1698 % self._repo.dirstate.pathto(dest)
1682 )
1699 )
1683 else:
1700 else:
1684 with self._repo.wlock():
1701 with self._repo.wlock():
1685 ds = self._repo.dirstate
1702 ds = self._repo.dirstate
1686 if ds[dest] in b'?':
1703 if ds[dest] in b'?':
1687 ds.add(dest)
1704 ds.add(dest)
1688 elif ds[dest] in b'r':
1705 elif ds[dest] in b'r':
1689 ds.normallookup(dest)
1706 ds.normallookup(dest)
1690 ds.copy(source, dest)
1707 ds.copy(source, dest)
1691
1708
1692 def match(
1709 def match(
1693 self,
1710 self,
1694 pats=None,
1711 pats=None,
1695 include=None,
1712 include=None,
1696 exclude=None,
1713 exclude=None,
1697 default=b'glob',
1714 default=b'glob',
1698 listsubrepos=False,
1715 listsubrepos=False,
1699 badfn=None,
1716 badfn=None,
1700 cwd=None,
1717 cwd=None,
1701 ):
1718 ):
1702 r = self._repo
1719 r = self._repo
1703 if not cwd:
1720 if not cwd:
1704 cwd = r.getcwd()
1721 cwd = r.getcwd()
1705
1722
1706 # Only a case insensitive filesystem needs magic to translate user input
1723 # Only a case insensitive filesystem needs magic to translate user input
1707 # to actual case in the filesystem.
1724 # to actual case in the filesystem.
1708 icasefs = not util.fscasesensitive(r.root)
1725 icasefs = not util.fscasesensitive(r.root)
1709 return matchmod.match(
1726 return matchmod.match(
1710 r.root,
1727 r.root,
1711 cwd,
1728 cwd,
1712 pats,
1729 pats,
1713 include,
1730 include,
1714 exclude,
1731 exclude,
1715 default,
1732 default,
1716 auditor=r.auditor,
1733 auditor=r.auditor,
1717 ctx=self,
1734 ctx=self,
1718 listsubrepos=listsubrepos,
1735 listsubrepos=listsubrepos,
1719 badfn=badfn,
1736 badfn=badfn,
1720 icasefs=icasefs,
1737 icasefs=icasefs,
1721 )
1738 )
1722
1739
1723 def _filtersuspectsymlink(self, files):
1740 def _filtersuspectsymlink(self, files):
1724 if not files or self._repo.dirstate._checklink:
1741 if not files or self._repo.dirstate._checklink:
1725 return files
1742 return files
1726
1743
1727 # Symlink placeholders may get non-symlink-like contents
1744 # Symlink placeholders may get non-symlink-like contents
1728 # via user error or dereferencing by NFS or Samba servers,
1745 # via user error or dereferencing by NFS or Samba servers,
1729 # so we filter out any placeholders that don't look like a
1746 # so we filter out any placeholders that don't look like a
1730 # symlink
1747 # symlink
1731 sane = []
1748 sane = []
1732 for f in files:
1749 for f in files:
1733 if self.flags(f) == b'l':
1750 if self.flags(f) == b'l':
1734 d = self[f].data()
1751 d = self[f].data()
1735 if (
1752 if (
1736 d == b''
1753 d == b''
1737 or len(d) >= 1024
1754 or len(d) >= 1024
1738 or b'\n' in d
1755 or b'\n' in d
1739 or stringutil.binary(d)
1756 or stringutil.binary(d)
1740 ):
1757 ):
1741 self._repo.ui.debug(
1758 self._repo.ui.debug(
1742 b'ignoring suspect symlink placeholder "%s"\n' % f
1759 b'ignoring suspect symlink placeholder "%s"\n' % f
1743 )
1760 )
1744 continue
1761 continue
1745 sane.append(f)
1762 sane.append(f)
1746 return sane
1763 return sane
1747
1764
1748 def _checklookup(self, files):
1765 def _checklookup(self, files):
1749 # check for any possibly clean files
1766 # check for any possibly clean files
1750 if not files:
1767 if not files:
1751 return [], [], []
1768 return [], [], []
1752
1769
1753 modified = []
1770 modified = []
1754 deleted = []
1771 deleted = []
1755 fixup = []
1772 fixup = []
1756 pctx = self._parents[0]
1773 pctx = self._parents[0]
1757 # do a full compare of any files that might have changed
1774 # do a full compare of any files that might have changed
1758 for f in sorted(files):
1775 for f in sorted(files):
1759 try:
1776 try:
1760 # This will return True for a file that got replaced by a
1777 # This will return True for a file that got replaced by a
1761 # directory in the interim, but fixing that is pretty hard.
1778 # directory in the interim, but fixing that is pretty hard.
1762 if (
1779 if (
1763 f not in pctx
1780 f not in pctx
1764 or self.flags(f) != pctx.flags(f)
1781 or self.flags(f) != pctx.flags(f)
1765 or pctx[f].cmp(self[f])
1782 or pctx[f].cmp(self[f])
1766 ):
1783 ):
1767 modified.append(f)
1784 modified.append(f)
1768 else:
1785 else:
1769 fixup.append(f)
1786 fixup.append(f)
1770 except (IOError, OSError):
1787 except (IOError, OSError):
1771 # A file become inaccessible in between? Mark it as deleted,
1788 # A file become inaccessible in between? Mark it as deleted,
1772 # matching dirstate behavior (issue5584).
1789 # matching dirstate behavior (issue5584).
1773 # The dirstate has more complex behavior around whether a
1790 # The dirstate has more complex behavior around whether a
1774 # missing file matches a directory, etc, but we don't need to
1791 # missing file matches a directory, etc, but we don't need to
1775 # bother with that: if f has made it to this point, we're sure
1792 # bother with that: if f has made it to this point, we're sure
1776 # it's in the dirstate.
1793 # it's in the dirstate.
1777 deleted.append(f)
1794 deleted.append(f)
1778
1795
1779 return modified, deleted, fixup
1796 return modified, deleted, fixup
1780
1797
1781 def _poststatusfixup(self, status, fixup):
1798 def _poststatusfixup(self, status, fixup):
1782 """update dirstate for files that are actually clean"""
1799 """update dirstate for files that are actually clean"""
1783 poststatus = self._repo.postdsstatus()
1800 poststatus = self._repo.postdsstatus()
1784 if fixup or poststatus:
1801 if fixup or poststatus:
1785 try:
1802 try:
1786 oldid = self._repo.dirstate.identity()
1803 oldid = self._repo.dirstate.identity()
1787
1804
1788 # updating the dirstate is optional
1805 # updating the dirstate is optional
1789 # so we don't wait on the lock
1806 # so we don't wait on the lock
1790 # wlock can invalidate the dirstate, so cache normal _after_
1807 # wlock can invalidate the dirstate, so cache normal _after_
1791 # taking the lock
1808 # taking the lock
1792 with self._repo.wlock(False):
1809 with self._repo.wlock(False):
1793 if self._repo.dirstate.identity() == oldid:
1810 if self._repo.dirstate.identity() == oldid:
1794 if fixup:
1811 if fixup:
1795 normal = self._repo.dirstate.normal
1812 normal = self._repo.dirstate.normal
1796 for f in fixup:
1813 for f in fixup:
1797 normal(f)
1814 normal(f)
1798 # write changes out explicitly, because nesting
1815 # write changes out explicitly, because nesting
1799 # wlock at runtime may prevent 'wlock.release()'
1816 # wlock at runtime may prevent 'wlock.release()'
1800 # after this block from doing so for subsequent
1817 # after this block from doing so for subsequent
1801 # changing files
1818 # changing files
1802 tr = self._repo.currenttransaction()
1819 tr = self._repo.currenttransaction()
1803 self._repo.dirstate.write(tr)
1820 self._repo.dirstate.write(tr)
1804
1821
1805 if poststatus:
1822 if poststatus:
1806 for ps in poststatus:
1823 for ps in poststatus:
1807 ps(self, status)
1824 ps(self, status)
1808 else:
1825 else:
1809 # in this case, writing changes out breaks
1826 # in this case, writing changes out breaks
1810 # consistency, because .hg/dirstate was
1827 # consistency, because .hg/dirstate was
1811 # already changed simultaneously after last
1828 # already changed simultaneously after last
1812 # caching (see also issue5584 for detail)
1829 # caching (see also issue5584 for detail)
1813 self._repo.ui.debug(
1830 self._repo.ui.debug(
1814 b'skip updating dirstate: identity mismatch\n'
1831 b'skip updating dirstate: identity mismatch\n'
1815 )
1832 )
1816 except error.LockError:
1833 except error.LockError:
1817 pass
1834 pass
1818 finally:
1835 finally:
1819 # Even if the wlock couldn't be grabbed, clear out the list.
1836 # Even if the wlock couldn't be grabbed, clear out the list.
1820 self._repo.clearpostdsstatus()
1837 self._repo.clearpostdsstatus()
1821
1838
1822 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1839 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1823 '''Gets the status from the dirstate -- internal use only.'''
1840 '''Gets the status from the dirstate -- internal use only.'''
1824 subrepos = []
1841 subrepos = []
1825 if b'.hgsub' in self:
1842 if b'.hgsub' in self:
1826 subrepos = sorted(self.substate)
1843 subrepos = sorted(self.substate)
1827 cmp, s = self._repo.dirstate.status(
1844 cmp, s = self._repo.dirstate.status(
1828 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1845 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1829 )
1846 )
1830
1847
1831 # check for any possibly clean files
1848 # check for any possibly clean files
1832 fixup = []
1849 fixup = []
1833 if cmp:
1850 if cmp:
1834 modified2, deleted2, fixup = self._checklookup(cmp)
1851 modified2, deleted2, fixup = self._checklookup(cmp)
1835 s.modified.extend(modified2)
1852 s.modified.extend(modified2)
1836 s.deleted.extend(deleted2)
1853 s.deleted.extend(deleted2)
1837
1854
1838 if fixup and clean:
1855 if fixup and clean:
1839 s.clean.extend(fixup)
1856 s.clean.extend(fixup)
1840
1857
1841 self._poststatusfixup(s, fixup)
1858 self._poststatusfixup(s, fixup)
1842
1859
1843 if match.always():
1860 if match.always():
1844 # cache for performance
1861 # cache for performance
1845 if s.unknown or s.ignored or s.clean:
1862 if s.unknown or s.ignored or s.clean:
1846 # "_status" is cached with list*=False in the normal route
1863 # "_status" is cached with list*=False in the normal route
1847 self._status = scmutil.status(
1864 self._status = scmutil.status(
1848 s.modified, s.added, s.removed, s.deleted, [], [], []
1865 s.modified, s.added, s.removed, s.deleted, [], [], []
1849 )
1866 )
1850 else:
1867 else:
1851 self._status = s
1868 self._status = s
1852
1869
1853 return s
1870 return s
1854
1871
1855 @propertycache
1872 @propertycache
1856 def _copies(self):
1873 def _copies(self):
1857 p1copies = {}
1874 p1copies = {}
1858 p2copies = {}
1875 p2copies = {}
1859 parents = self._repo.dirstate.parents()
1876 parents = self._repo.dirstate.parents()
1860 p1manifest = self._repo[parents[0]].manifest()
1877 p1manifest = self._repo[parents[0]].manifest()
1861 p2manifest = self._repo[parents[1]].manifest()
1878 p2manifest = self._repo[parents[1]].manifest()
1862 changedset = set(self.added()) | set(self.modified())
1879 changedset = set(self.added()) | set(self.modified())
1863 narrowmatch = self._repo.narrowmatch()
1880 narrowmatch = self._repo.narrowmatch()
1864 for dst, src in self._repo.dirstate.copies().items():
1881 for dst, src in self._repo.dirstate.copies().items():
1865 if dst not in changedset or not narrowmatch(dst):
1882 if dst not in changedset or not narrowmatch(dst):
1866 continue
1883 continue
1867 if src in p1manifest:
1884 if src in p1manifest:
1868 p1copies[dst] = src
1885 p1copies[dst] = src
1869 elif src in p2manifest:
1886 elif src in p2manifest:
1870 p2copies[dst] = src
1887 p2copies[dst] = src
1871 return p1copies, p2copies
1888 return p1copies, p2copies
1872
1889
1873 @propertycache
1890 @propertycache
1874 def _manifest(self):
1891 def _manifest(self):
1875 """generate a manifest corresponding to the values in self._status
1892 """generate a manifest corresponding to the values in self._status
1876
1893
1877 This reuse the file nodeid from parent, but we use special node
1894 This reuse the file nodeid from parent, but we use special node
1878 identifiers for added and modified files. This is used by manifests
1895 identifiers for added and modified files. This is used by manifests
1879 merge to see that files are different and by update logic to avoid
1896 merge to see that files are different and by update logic to avoid
1880 deleting newly added files.
1897 deleting newly added files.
1881 """
1898 """
1882 return self._buildstatusmanifest(self._status)
1899 return self._buildstatusmanifest(self._status)
1883
1900
1884 def _buildstatusmanifest(self, status):
1901 def _buildstatusmanifest(self, status):
1885 """Builds a manifest that includes the given status results."""
1902 """Builds a manifest that includes the given status results."""
1886 parents = self.parents()
1903 parents = self.parents()
1887
1904
1888 man = parents[0].manifest().copy()
1905 man = parents[0].manifest().copy()
1889
1906
1890 ff = self._flagfunc
1907 ff = self._flagfunc
1891 for i, l in (
1908 for i, l in (
1892 (addednodeid, status.added),
1909 (addednodeid, status.added),
1893 (modifiednodeid, status.modified),
1910 (modifiednodeid, status.modified),
1894 ):
1911 ):
1895 for f in l:
1912 for f in l:
1896 man[f] = i
1913 man[f] = i
1897 try:
1914 try:
1898 man.setflag(f, ff(f))
1915 man.setflag(f, ff(f))
1899 except OSError:
1916 except OSError:
1900 pass
1917 pass
1901
1918
1902 for f in status.deleted + status.removed:
1919 for f in status.deleted + status.removed:
1903 if f in man:
1920 if f in man:
1904 del man[f]
1921 del man[f]
1905
1922
1906 return man
1923 return man
1907
1924
1908 def _buildstatus(
1925 def _buildstatus(
1909 self, other, s, match, listignored, listclean, listunknown
1926 self, other, s, match, listignored, listclean, listunknown
1910 ):
1927 ):
1911 """build a status with respect to another context
1928 """build a status with respect to another context
1912
1929
1913 This includes logic for maintaining the fast path of status when
1930 This includes logic for maintaining the fast path of status when
1914 comparing the working directory against its parent, which is to skip
1931 comparing the working directory against its parent, which is to skip
1915 building a new manifest if self (working directory) is not comparing
1932 building a new manifest if self (working directory) is not comparing
1916 against its parent (repo['.']).
1933 against its parent (repo['.']).
1917 """
1934 """
1918 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1935 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1919 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1936 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1920 # might have accidentally ended up with the entire contents of the file
1937 # might have accidentally ended up with the entire contents of the file
1921 # they are supposed to be linking to.
1938 # they are supposed to be linking to.
1922 s.modified[:] = self._filtersuspectsymlink(s.modified)
1939 s.modified[:] = self._filtersuspectsymlink(s.modified)
1923 if other != self._repo[b'.']:
1940 if other != self._repo[b'.']:
1924 s = super(workingctx, self)._buildstatus(
1941 s = super(workingctx, self)._buildstatus(
1925 other, s, match, listignored, listclean, listunknown
1942 other, s, match, listignored, listclean, listunknown
1926 )
1943 )
1927 return s
1944 return s
1928
1945
1929 def _matchstatus(self, other, match):
1946 def _matchstatus(self, other, match):
1930 """override the match method with a filter for directory patterns
1947 """override the match method with a filter for directory patterns
1931
1948
1932 We use inheritance to customize the match.bad method only in cases of
1949 We use inheritance to customize the match.bad method only in cases of
1933 workingctx since it belongs only to the working directory when
1950 workingctx since it belongs only to the working directory when
1934 comparing against the parent changeset.
1951 comparing against the parent changeset.
1935
1952
1936 If we aren't comparing against the working directory's parent, then we
1953 If we aren't comparing against the working directory's parent, then we
1937 just use the default match object sent to us.
1954 just use the default match object sent to us.
1938 """
1955 """
1939 if other != self._repo[b'.']:
1956 if other != self._repo[b'.']:
1940
1957
1941 def bad(f, msg):
1958 def bad(f, msg):
1942 # 'f' may be a directory pattern from 'match.files()',
1959 # 'f' may be a directory pattern from 'match.files()',
1943 # so 'f not in ctx1' is not enough
1960 # so 'f not in ctx1' is not enough
1944 if f not in other and not other.hasdir(f):
1961 if f not in other and not other.hasdir(f):
1945 self._repo.ui.warn(
1962 self._repo.ui.warn(
1946 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
1963 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
1947 )
1964 )
1948
1965
1949 match.bad = bad
1966 match.bad = bad
1950 return match
1967 return match
1951
1968
1952 def walk(self, match):
1969 def walk(self, match):
1953 '''Generates matching file names.'''
1970 '''Generates matching file names.'''
1954 return sorted(
1971 return sorted(
1955 self._repo.dirstate.walk(
1972 self._repo.dirstate.walk(
1956 self._repo.narrowmatch(match),
1973 self._repo.narrowmatch(match),
1957 subrepos=sorted(self.substate),
1974 subrepos=sorted(self.substate),
1958 unknown=True,
1975 unknown=True,
1959 ignored=False,
1976 ignored=False,
1960 )
1977 )
1961 )
1978 )
1962
1979
1963 def matches(self, match):
1980 def matches(self, match):
1964 match = self._repo.narrowmatch(match)
1981 match = self._repo.narrowmatch(match)
1965 ds = self._repo.dirstate
1982 ds = self._repo.dirstate
1966 return sorted(f for f in ds.matches(match) if ds[f] != b'r')
1983 return sorted(f for f in ds.matches(match) if ds[f] != b'r')
1967
1984
1968 def markcommitted(self, node):
1985 def markcommitted(self, node):
1969 with self._repo.dirstate.parentchange():
1986 with self._repo.dirstate.parentchange():
1970 for f in self.modified() + self.added():
1987 for f in self.modified() + self.added():
1971 self._repo.dirstate.normal(f)
1988 self._repo.dirstate.normal(f)
1972 for f in self.removed():
1989 for f in self.removed():
1973 self._repo.dirstate.drop(f)
1990 self._repo.dirstate.drop(f)
1974 self._repo.dirstate.setparents(node)
1991 self._repo.dirstate.setparents(node)
1975
1992
1976 # write changes out explicitly, because nesting wlock at
1993 # write changes out explicitly, because nesting wlock at
1977 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1994 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1978 # from immediately doing so for subsequent changing files
1995 # from immediately doing so for subsequent changing files
1979 self._repo.dirstate.write(self._repo.currenttransaction())
1996 self._repo.dirstate.write(self._repo.currenttransaction())
1980
1997
1981 sparse.aftercommit(self._repo, node)
1998 sparse.aftercommit(self._repo, node)
1982
1999
1983
2000
1984 class committablefilectx(basefilectx):
2001 class committablefilectx(basefilectx):
1985 """A committablefilectx provides common functionality for a file context
2002 """A committablefilectx provides common functionality for a file context
1986 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2003 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1987
2004
1988 def __init__(self, repo, path, filelog=None, ctx=None):
2005 def __init__(self, repo, path, filelog=None, ctx=None):
1989 self._repo = repo
2006 self._repo = repo
1990 self._path = path
2007 self._path = path
1991 self._changeid = None
2008 self._changeid = None
1992 self._filerev = self._filenode = None
2009 self._filerev = self._filenode = None
1993
2010
1994 if filelog is not None:
2011 if filelog is not None:
1995 self._filelog = filelog
2012 self._filelog = filelog
1996 if ctx:
2013 if ctx:
1997 self._changectx = ctx
2014 self._changectx = ctx
1998
2015
1999 def __nonzero__(self):
2016 def __nonzero__(self):
2000 return True
2017 return True
2001
2018
2002 __bool__ = __nonzero__
2019 __bool__ = __nonzero__
2003
2020
2004 def linkrev(self):
2021 def linkrev(self):
2005 # linked to self._changectx no matter if file is modified or not
2022 # linked to self._changectx no matter if file is modified or not
2006 return self.rev()
2023 return self.rev()
2007
2024
2008 def renamed(self):
2025 def renamed(self):
2009 path = self.copysource()
2026 path = self.copysource()
2010 if not path:
2027 if not path:
2011 return None
2028 return None
2012 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2029 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2013
2030
2014 def parents(self):
2031 def parents(self):
2015 '''return parent filectxs, following copies if necessary'''
2032 '''return parent filectxs, following copies if necessary'''
2016
2033
2017 def filenode(ctx, path):
2034 def filenode(ctx, path):
2018 return ctx._manifest.get(path, nullid)
2035 return ctx._manifest.get(path, nullid)
2019
2036
2020 path = self._path
2037 path = self._path
2021 fl = self._filelog
2038 fl = self._filelog
2022 pcl = self._changectx._parents
2039 pcl = self._changectx._parents
2023 renamed = self.renamed()
2040 renamed = self.renamed()
2024
2041
2025 if renamed:
2042 if renamed:
2026 pl = [renamed + (None,)]
2043 pl = [renamed + (None,)]
2027 else:
2044 else:
2028 pl = [(path, filenode(pcl[0], path), fl)]
2045 pl = [(path, filenode(pcl[0], path), fl)]
2029
2046
2030 for pc in pcl[1:]:
2047 for pc in pcl[1:]:
2031 pl.append((path, filenode(pc, path), fl))
2048 pl.append((path, filenode(pc, path), fl))
2032
2049
2033 return [
2050 return [
2034 self._parentfilectx(p, fileid=n, filelog=l)
2051 self._parentfilectx(p, fileid=n, filelog=l)
2035 for p, n, l in pl
2052 for p, n, l in pl
2036 if n != nullid
2053 if n != nullid
2037 ]
2054 ]
2038
2055
2039 def children(self):
2056 def children(self):
2040 return []
2057 return []
2041
2058
2042
2059
2043 class workingfilectx(committablefilectx):
2060 class workingfilectx(committablefilectx):
2044 """A workingfilectx object makes access to data related to a particular
2061 """A workingfilectx object makes access to data related to a particular
2045 file in the working directory convenient."""
2062 file in the working directory convenient."""
2046
2063
2047 def __init__(self, repo, path, filelog=None, workingctx=None):
2064 def __init__(self, repo, path, filelog=None, workingctx=None):
2048 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2065 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2049
2066
2050 @propertycache
2067 @propertycache
2051 def _changectx(self):
2068 def _changectx(self):
2052 return workingctx(self._repo)
2069 return workingctx(self._repo)
2053
2070
2054 def data(self):
2071 def data(self):
2055 return self._repo.wread(self._path)
2072 return self._repo.wread(self._path)
2056
2073
2057 def copysource(self):
2074 def copysource(self):
2058 return self._repo.dirstate.copied(self._path)
2075 return self._repo.dirstate.copied(self._path)
2059
2076
2060 def size(self):
2077 def size(self):
2061 return self._repo.wvfs.lstat(self._path).st_size
2078 return self._repo.wvfs.lstat(self._path).st_size
2062
2079
2063 def lstat(self):
2080 def lstat(self):
2064 return self._repo.wvfs.lstat(self._path)
2081 return self._repo.wvfs.lstat(self._path)
2065
2082
2066 def date(self):
2083 def date(self):
2067 t, tz = self._changectx.date()
2084 t, tz = self._changectx.date()
2068 try:
2085 try:
2069 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2086 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2070 except OSError as err:
2087 except OSError as err:
2071 if err.errno != errno.ENOENT:
2088 if err.errno != errno.ENOENT:
2072 raise
2089 raise
2073 return (t, tz)
2090 return (t, tz)
2074
2091
2075 def exists(self):
2092 def exists(self):
2076 return self._repo.wvfs.exists(self._path)
2093 return self._repo.wvfs.exists(self._path)
2077
2094
2078 def lexists(self):
2095 def lexists(self):
2079 return self._repo.wvfs.lexists(self._path)
2096 return self._repo.wvfs.lexists(self._path)
2080
2097
2081 def audit(self):
2098 def audit(self):
2082 return self._repo.wvfs.audit(self._path)
2099 return self._repo.wvfs.audit(self._path)
2083
2100
2084 def cmp(self, fctx):
2101 def cmp(self, fctx):
2085 """compare with other file context
2102 """compare with other file context
2086
2103
2087 returns True if different than fctx.
2104 returns True if different than fctx.
2088 """
2105 """
2089 # fctx should be a filectx (not a workingfilectx)
2106 # fctx should be a filectx (not a workingfilectx)
2090 # invert comparison to reuse the same code path
2107 # invert comparison to reuse the same code path
2091 return fctx.cmp(self)
2108 return fctx.cmp(self)
2092
2109
2093 def remove(self, ignoremissing=False):
2110 def remove(self, ignoremissing=False):
2094 """wraps unlink for a repo's working directory"""
2111 """wraps unlink for a repo's working directory"""
2095 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2112 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2096 self._repo.wvfs.unlinkpath(
2113 self._repo.wvfs.unlinkpath(
2097 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2114 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2098 )
2115 )
2099
2116
2100 def write(self, data, flags, backgroundclose=False, **kwargs):
2117 def write(self, data, flags, backgroundclose=False, **kwargs):
2101 """wraps repo.wwrite"""
2118 """wraps repo.wwrite"""
2102 return self._repo.wwrite(
2119 return self._repo.wwrite(
2103 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2120 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2104 )
2121 )
2105
2122
2106 def markcopied(self, src):
2123 def markcopied(self, src):
2107 """marks this file a copy of `src`"""
2124 """marks this file a copy of `src`"""
2108 self._repo.dirstate.copy(src, self._path)
2125 self._repo.dirstate.copy(src, self._path)
2109
2126
2110 def clearunknown(self):
2127 def clearunknown(self):
2111 """Removes conflicting items in the working directory so that
2128 """Removes conflicting items in the working directory so that
2112 ``write()`` can be called successfully.
2129 ``write()`` can be called successfully.
2113 """
2130 """
2114 wvfs = self._repo.wvfs
2131 wvfs = self._repo.wvfs
2115 f = self._path
2132 f = self._path
2116 wvfs.audit(f)
2133 wvfs.audit(f)
2117 if self._repo.ui.configbool(
2134 if self._repo.ui.configbool(
2118 b'experimental', b'merge.checkpathconflicts'
2135 b'experimental', b'merge.checkpathconflicts'
2119 ):
2136 ):
2120 # remove files under the directory as they should already be
2137 # remove files under the directory as they should already be
2121 # warned and backed up
2138 # warned and backed up
2122 if wvfs.isdir(f) and not wvfs.islink(f):
2139 if wvfs.isdir(f) and not wvfs.islink(f):
2123 wvfs.rmtree(f, forcibly=True)
2140 wvfs.rmtree(f, forcibly=True)
2124 for p in reversed(list(pathutil.finddirs(f))):
2141 for p in reversed(list(pathutil.finddirs(f))):
2125 if wvfs.isfileorlink(p):
2142 if wvfs.isfileorlink(p):
2126 wvfs.unlink(p)
2143 wvfs.unlink(p)
2127 break
2144 break
2128 else:
2145 else:
2129 # don't remove files if path conflicts are not processed
2146 # don't remove files if path conflicts are not processed
2130 if wvfs.isdir(f) and not wvfs.islink(f):
2147 if wvfs.isdir(f) and not wvfs.islink(f):
2131 wvfs.removedirs(f)
2148 wvfs.removedirs(f)
2132
2149
2133 def setflags(self, l, x):
2150 def setflags(self, l, x):
2134 self._repo.wvfs.setflags(self._path, l, x)
2151 self._repo.wvfs.setflags(self._path, l, x)
2135
2152
2136
2153
2137 class overlayworkingctx(committablectx):
2154 class overlayworkingctx(committablectx):
2138 """Wraps another mutable context with a write-back cache that can be
2155 """Wraps another mutable context with a write-back cache that can be
2139 converted into a commit context.
2156 converted into a commit context.
2140
2157
2141 self._cache[path] maps to a dict with keys: {
2158 self._cache[path] maps to a dict with keys: {
2142 'exists': bool?
2159 'exists': bool?
2143 'date': date?
2160 'date': date?
2144 'data': str?
2161 'data': str?
2145 'flags': str?
2162 'flags': str?
2146 'copied': str? (path or None)
2163 'copied': str? (path or None)
2147 }
2164 }
2148 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2165 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2149 is `False`, the file was deleted.
2166 is `False`, the file was deleted.
2150 """
2167 """
2151
2168
2152 def __init__(self, repo):
2169 def __init__(self, repo):
2153 super(overlayworkingctx, self).__init__(repo)
2170 super(overlayworkingctx, self).__init__(repo)
2154 self.clean()
2171 self.clean()
2155
2172
2156 def setbase(self, wrappedctx):
2173 def setbase(self, wrappedctx):
2157 self._wrappedctx = wrappedctx
2174 self._wrappedctx = wrappedctx
2158 self._parents = [wrappedctx]
2175 self._parents = [wrappedctx]
2159 # Drop old manifest cache as it is now out of date.
2176 # Drop old manifest cache as it is now out of date.
2160 # This is necessary when, e.g., rebasing several nodes with one
2177 # This is necessary when, e.g., rebasing several nodes with one
2161 # ``overlayworkingctx`` (e.g. with --collapse).
2178 # ``overlayworkingctx`` (e.g. with --collapse).
2162 util.clearcachedproperty(self, b'_manifest')
2179 util.clearcachedproperty(self, b'_manifest')
2163
2180
2164 def setparents(self, p1node, p2node=nullid):
2181 def setparents(self, p1node, p2node=nullid):
2165 assert p1node == self._wrappedctx.node()
2182 assert p1node == self._wrappedctx.node()
2166 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2183 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2167
2184
2168 def data(self, path):
2185 def data(self, path):
2169 if self.isdirty(path):
2186 if self.isdirty(path):
2170 if self._cache[path][b'exists']:
2187 if self._cache[path][b'exists']:
2171 if self._cache[path][b'data'] is not None:
2188 if self._cache[path][b'data'] is not None:
2172 return self._cache[path][b'data']
2189 return self._cache[path][b'data']
2173 else:
2190 else:
2174 # Must fallback here, too, because we only set flags.
2191 # Must fallback here, too, because we only set flags.
2175 return self._wrappedctx[path].data()
2192 return self._wrappedctx[path].data()
2176 else:
2193 else:
2177 raise error.ProgrammingError(
2194 raise error.ProgrammingError(
2178 b"No such file or directory: %s" % path
2195 b"No such file or directory: %s" % path
2179 )
2196 )
2180 else:
2197 else:
2181 return self._wrappedctx[path].data()
2198 return self._wrappedctx[path].data()
2182
2199
2183 @propertycache
2200 @propertycache
2184 def _manifest(self):
2201 def _manifest(self):
2185 parents = self.parents()
2202 parents = self.parents()
2186 man = parents[0].manifest().copy()
2203 man = parents[0].manifest().copy()
2187
2204
2188 flag = self._flagfunc
2205 flag = self._flagfunc
2189 for path in self.added():
2206 for path in self.added():
2190 man[path] = addednodeid
2207 man[path] = addednodeid
2191 man.setflag(path, flag(path))
2208 man.setflag(path, flag(path))
2192 for path in self.modified():
2209 for path in self.modified():
2193 man[path] = modifiednodeid
2210 man[path] = modifiednodeid
2194 man.setflag(path, flag(path))
2211 man.setflag(path, flag(path))
2195 for path in self.removed():
2212 for path in self.removed():
2196 del man[path]
2213 del man[path]
2197 return man
2214 return man
2198
2215
2199 @propertycache
2216 @propertycache
2200 def _flagfunc(self):
2217 def _flagfunc(self):
2201 def f(path):
2218 def f(path):
2202 return self._cache[path][b'flags']
2219 return self._cache[path][b'flags']
2203
2220
2204 return f
2221 return f
2205
2222
2206 def files(self):
2223 def files(self):
2207 return sorted(self.added() + self.modified() + self.removed())
2224 return sorted(self.added() + self.modified() + self.removed())
2208
2225
2209 def modified(self):
2226 def modified(self):
2210 return [
2227 return [
2211 f
2228 f
2212 for f in self._cache.keys()
2229 for f in self._cache.keys()
2213 if self._cache[f][b'exists'] and self._existsinparent(f)
2230 if self._cache[f][b'exists'] and self._existsinparent(f)
2214 ]
2231 ]
2215
2232
2216 def added(self):
2233 def added(self):
2217 return [
2234 return [
2218 f
2235 f
2219 for f in self._cache.keys()
2236 for f in self._cache.keys()
2220 if self._cache[f][b'exists'] and not self._existsinparent(f)
2237 if self._cache[f][b'exists'] and not self._existsinparent(f)
2221 ]
2238 ]
2222
2239
2223 def removed(self):
2240 def removed(self):
2224 return [
2241 return [
2225 f
2242 f
2226 for f in self._cache.keys()
2243 for f in self._cache.keys()
2227 if not self._cache[f][b'exists'] and self._existsinparent(f)
2244 if not self._cache[f][b'exists'] and self._existsinparent(f)
2228 ]
2245 ]
2229
2246
2230 def p1copies(self):
2247 def p1copies(self):
2231 copies = {}
2248 copies = {}
2232 narrowmatch = self._repo.narrowmatch()
2249 narrowmatch = self._repo.narrowmatch()
2233 for f in self._cache.keys():
2250 for f in self._cache.keys():
2234 if not narrowmatch(f):
2251 if not narrowmatch(f):
2235 continue
2252 continue
2236 copies.pop(f, None) # delete if it exists
2253 copies.pop(f, None) # delete if it exists
2237 source = self._cache[f][b'copied']
2254 source = self._cache[f][b'copied']
2238 if source:
2255 if source:
2239 copies[f] = source
2256 copies[f] = source
2240 return copies
2257 return copies
2241
2258
2242 def p2copies(self):
2259 def p2copies(self):
2243 copies = {}
2260 copies = {}
2244 narrowmatch = self._repo.narrowmatch()
2261 narrowmatch = self._repo.narrowmatch()
2245 for f in self._cache.keys():
2262 for f in self._cache.keys():
2246 if not narrowmatch(f):
2263 if not narrowmatch(f):
2247 continue
2264 continue
2248 copies.pop(f, None) # delete if it exists
2265 copies.pop(f, None) # delete if it exists
2249 source = self._cache[f][b'copied']
2266 source = self._cache[f][b'copied']
2250 if source:
2267 if source:
2251 copies[f] = source
2268 copies[f] = source
2252 return copies
2269 return copies
2253
2270
2254 def isinmemory(self):
2271 def isinmemory(self):
2255 return True
2272 return True
2256
2273
2257 def filedate(self, path):
2274 def filedate(self, path):
2258 if self.isdirty(path):
2275 if self.isdirty(path):
2259 return self._cache[path][b'date']
2276 return self._cache[path][b'date']
2260 else:
2277 else:
2261 return self._wrappedctx[path].date()
2278 return self._wrappedctx[path].date()
2262
2279
2263 def markcopied(self, path, origin):
2280 def markcopied(self, path, origin):
2264 self._markdirty(
2281 self._markdirty(
2265 path,
2282 path,
2266 exists=True,
2283 exists=True,
2267 date=self.filedate(path),
2284 date=self.filedate(path),
2268 flags=self.flags(path),
2285 flags=self.flags(path),
2269 copied=origin,
2286 copied=origin,
2270 )
2287 )
2271
2288
2272 def copydata(self, path):
2289 def copydata(self, path):
2273 if self.isdirty(path):
2290 if self.isdirty(path):
2274 return self._cache[path][b'copied']
2291 return self._cache[path][b'copied']
2275 else:
2292 else:
2276 return None
2293 return None
2277
2294
2278 def flags(self, path):
2295 def flags(self, path):
2279 if self.isdirty(path):
2296 if self.isdirty(path):
2280 if self._cache[path][b'exists']:
2297 if self._cache[path][b'exists']:
2281 return self._cache[path][b'flags']
2298 return self._cache[path][b'flags']
2282 else:
2299 else:
2283 raise error.ProgrammingError(
2300 raise error.ProgrammingError(
2284 b"No such file or directory: %s" % self._path
2301 b"No such file or directory: %s" % self._path
2285 )
2302 )
2286 else:
2303 else:
2287 return self._wrappedctx[path].flags()
2304 return self._wrappedctx[path].flags()
2288
2305
2289 def __contains__(self, key):
2306 def __contains__(self, key):
2290 if key in self._cache:
2307 if key in self._cache:
2291 return self._cache[key][b'exists']
2308 return self._cache[key][b'exists']
2292 return key in self.p1()
2309 return key in self.p1()
2293
2310
2294 def _existsinparent(self, path):
2311 def _existsinparent(self, path):
2295 try:
2312 try:
2296 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2313 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2297 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2314 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2298 # with an ``exists()`` function.
2315 # with an ``exists()`` function.
2299 self._wrappedctx[path]
2316 self._wrappedctx[path]
2300 return True
2317 return True
2301 except error.ManifestLookupError:
2318 except error.ManifestLookupError:
2302 return False
2319 return False
2303
2320
2304 def _auditconflicts(self, path):
2321 def _auditconflicts(self, path):
2305 """Replicates conflict checks done by wvfs.write().
2322 """Replicates conflict checks done by wvfs.write().
2306
2323
2307 Since we never write to the filesystem and never call `applyupdates` in
2324 Since we never write to the filesystem and never call `applyupdates` in
2308 IMM, we'll never check that a path is actually writable -- e.g., because
2325 IMM, we'll never check that a path is actually writable -- e.g., because
2309 it adds `a/foo`, but `a` is actually a file in the other commit.
2326 it adds `a/foo`, but `a` is actually a file in the other commit.
2310 """
2327 """
2311
2328
2312 def fail(path, component):
2329 def fail(path, component):
2313 # p1() is the base and we're receiving "writes" for p2()'s
2330 # p1() is the base and we're receiving "writes" for p2()'s
2314 # files.
2331 # files.
2315 if b'l' in self.p1()[component].flags():
2332 if b'l' in self.p1()[component].flags():
2316 raise error.Abort(
2333 raise error.Abort(
2317 b"error: %s conflicts with symlink %s "
2334 b"error: %s conflicts with symlink %s "
2318 b"in %d." % (path, component, self.p1().rev())
2335 b"in %d." % (path, component, self.p1().rev())
2319 )
2336 )
2320 else:
2337 else:
2321 raise error.Abort(
2338 raise error.Abort(
2322 b"error: '%s' conflicts with file '%s' in "
2339 b"error: '%s' conflicts with file '%s' in "
2323 b"%d." % (path, component, self.p1().rev())
2340 b"%d." % (path, component, self.p1().rev())
2324 )
2341 )
2325
2342
2326 # Test that each new directory to be created to write this path from p2
2343 # Test that each new directory to be created to write this path from p2
2327 # is not a file in p1.
2344 # is not a file in p1.
2328 components = path.split(b'/')
2345 components = path.split(b'/')
2329 for i in pycompat.xrange(len(components)):
2346 for i in pycompat.xrange(len(components)):
2330 component = b"/".join(components[0:i])
2347 component = b"/".join(components[0:i])
2331 if component in self:
2348 if component in self:
2332 fail(path, component)
2349 fail(path, component)
2333
2350
2334 # Test the other direction -- that this path from p2 isn't a directory
2351 # Test the other direction -- that this path from p2 isn't a directory
2335 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2352 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2336 match = self.match([path], default=b'path')
2353 match = self.match([path], default=b'path')
2337 matches = self.p1().manifest().matches(match)
2354 matches = self.p1().manifest().matches(match)
2338 mfiles = matches.keys()
2355 mfiles = matches.keys()
2339 if len(mfiles) > 0:
2356 if len(mfiles) > 0:
2340 if len(mfiles) == 1 and mfiles[0] == path:
2357 if len(mfiles) == 1 and mfiles[0] == path:
2341 return
2358 return
2342 # omit the files which are deleted in current IMM wctx
2359 # omit the files which are deleted in current IMM wctx
2343 mfiles = [m for m in mfiles if m in self]
2360 mfiles = [m for m in mfiles if m in self]
2344 if not mfiles:
2361 if not mfiles:
2345 return
2362 return
2346 raise error.Abort(
2363 raise error.Abort(
2347 b"error: file '%s' cannot be written because "
2364 b"error: file '%s' cannot be written because "
2348 b" '%s/' is a directory in %s (containing %d "
2365 b" '%s/' is a directory in %s (containing %d "
2349 b"entries: %s)"
2366 b"entries: %s)"
2350 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2367 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2351 )
2368 )
2352
2369
2353 def write(self, path, data, flags=b'', **kwargs):
2370 def write(self, path, data, flags=b'', **kwargs):
2354 if data is None:
2371 if data is None:
2355 raise error.ProgrammingError(b"data must be non-None")
2372 raise error.ProgrammingError(b"data must be non-None")
2356 self._auditconflicts(path)
2373 self._auditconflicts(path)
2357 self._markdirty(
2374 self._markdirty(
2358 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2375 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2359 )
2376 )
2360
2377
2361 def setflags(self, path, l, x):
2378 def setflags(self, path, l, x):
2362 flag = b''
2379 flag = b''
2363 if l:
2380 if l:
2364 flag = b'l'
2381 flag = b'l'
2365 elif x:
2382 elif x:
2366 flag = b'x'
2383 flag = b'x'
2367 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2384 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2368
2385
2369 def remove(self, path):
2386 def remove(self, path):
2370 self._markdirty(path, exists=False)
2387 self._markdirty(path, exists=False)
2371
2388
2372 def exists(self, path):
2389 def exists(self, path):
2373 """exists behaves like `lexists`, but needs to follow symlinks and
2390 """exists behaves like `lexists`, but needs to follow symlinks and
2374 return False if they are broken.
2391 return False if they are broken.
2375 """
2392 """
2376 if self.isdirty(path):
2393 if self.isdirty(path):
2377 # If this path exists and is a symlink, "follow" it by calling
2394 # If this path exists and is a symlink, "follow" it by calling
2378 # exists on the destination path.
2395 # exists on the destination path.
2379 if (
2396 if (
2380 self._cache[path][b'exists']
2397 self._cache[path][b'exists']
2381 and b'l' in self._cache[path][b'flags']
2398 and b'l' in self._cache[path][b'flags']
2382 ):
2399 ):
2383 return self.exists(self._cache[path][b'data'].strip())
2400 return self.exists(self._cache[path][b'data'].strip())
2384 else:
2401 else:
2385 return self._cache[path][b'exists']
2402 return self._cache[path][b'exists']
2386
2403
2387 return self._existsinparent(path)
2404 return self._existsinparent(path)
2388
2405
2389 def lexists(self, path):
2406 def lexists(self, path):
2390 """lexists returns True if the path exists"""
2407 """lexists returns True if the path exists"""
2391 if self.isdirty(path):
2408 if self.isdirty(path):
2392 return self._cache[path][b'exists']
2409 return self._cache[path][b'exists']
2393
2410
2394 return self._existsinparent(path)
2411 return self._existsinparent(path)
2395
2412
2396 def size(self, path):
2413 def size(self, path):
2397 if self.isdirty(path):
2414 if self.isdirty(path):
2398 if self._cache[path][b'exists']:
2415 if self._cache[path][b'exists']:
2399 return len(self._cache[path][b'data'])
2416 return len(self._cache[path][b'data'])
2400 else:
2417 else:
2401 raise error.ProgrammingError(
2418 raise error.ProgrammingError(
2402 b"No such file or directory: %s" % self._path
2419 b"No such file or directory: %s" % self._path
2403 )
2420 )
2404 return self._wrappedctx[path].size()
2421 return self._wrappedctx[path].size()
2405
2422
2406 def tomemctx(
2423 def tomemctx(
2407 self,
2424 self,
2408 text,
2425 text,
2409 branch=None,
2426 branch=None,
2410 extra=None,
2427 extra=None,
2411 date=None,
2428 date=None,
2412 parents=None,
2429 parents=None,
2413 user=None,
2430 user=None,
2414 editor=None,
2431 editor=None,
2415 ):
2432 ):
2416 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2433 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2417 committed.
2434 committed.
2418
2435
2419 ``text`` is the commit message.
2436 ``text`` is the commit message.
2420 ``parents`` (optional) are rev numbers.
2437 ``parents`` (optional) are rev numbers.
2421 """
2438 """
2422 # Default parents to the wrapped context if not passed.
2439 # Default parents to the wrapped context if not passed.
2423 if parents is None:
2440 if parents is None:
2424 parents = self.parents()
2441 parents = self.parents()
2425 if len(parents) == 1:
2442 if len(parents) == 1:
2426 parents = (parents[0], None)
2443 parents = (parents[0], None)
2427
2444
2428 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2445 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2429 if parents[1] is None:
2446 if parents[1] is None:
2430 parents = (self._repo[parents[0]], None)
2447 parents = (self._repo[parents[0]], None)
2431 else:
2448 else:
2432 parents = (self._repo[parents[0]], self._repo[parents[1]])
2449 parents = (self._repo[parents[0]], self._repo[parents[1]])
2433
2450
2434 files = self.files()
2451 files = self.files()
2435
2452
2436 def getfile(repo, memctx, path):
2453 def getfile(repo, memctx, path):
2437 if self._cache[path][b'exists']:
2454 if self._cache[path][b'exists']:
2438 return memfilectx(
2455 return memfilectx(
2439 repo,
2456 repo,
2440 memctx,
2457 memctx,
2441 path,
2458 path,
2442 self._cache[path][b'data'],
2459 self._cache[path][b'data'],
2443 b'l' in self._cache[path][b'flags'],
2460 b'l' in self._cache[path][b'flags'],
2444 b'x' in self._cache[path][b'flags'],
2461 b'x' in self._cache[path][b'flags'],
2445 self._cache[path][b'copied'],
2462 self._cache[path][b'copied'],
2446 )
2463 )
2447 else:
2464 else:
2448 # Returning None, but including the path in `files`, is
2465 # Returning None, but including the path in `files`, is
2449 # necessary for memctx to register a deletion.
2466 # necessary for memctx to register a deletion.
2450 return None
2467 return None
2451
2468
2452 if branch is None:
2469 if branch is None:
2453 branch = self._wrappedctx.branch()
2470 branch = self._wrappedctx.branch()
2454
2471
2455 return memctx(
2472 return memctx(
2456 self._repo,
2473 self._repo,
2457 parents,
2474 parents,
2458 text,
2475 text,
2459 files,
2476 files,
2460 getfile,
2477 getfile,
2461 date=date,
2478 date=date,
2462 extra=extra,
2479 extra=extra,
2463 user=user,
2480 user=user,
2464 branch=branch,
2481 branch=branch,
2465 editor=editor,
2482 editor=editor,
2466 )
2483 )
2467
2484
2468 def isdirty(self, path):
2485 def isdirty(self, path):
2469 return path in self._cache
2486 return path in self._cache
2470
2487
2471 def isempty(self):
2488 def isempty(self):
2472 # We need to discard any keys that are actually clean before the empty
2489 # We need to discard any keys that are actually clean before the empty
2473 # commit check.
2490 # commit check.
2474 self._compact()
2491 self._compact()
2475 return len(self._cache) == 0
2492 return len(self._cache) == 0
2476
2493
2477 def clean(self):
2494 def clean(self):
2478 self._cache = {}
2495 self._cache = {}
2479
2496
2480 def _compact(self):
2497 def _compact(self):
2481 """Removes keys from the cache that are actually clean, by comparing
2498 """Removes keys from the cache that are actually clean, by comparing
2482 them with the underlying context.
2499 them with the underlying context.
2483
2500
2484 This can occur during the merge process, e.g. by passing --tool :local
2501 This can occur during the merge process, e.g. by passing --tool :local
2485 to resolve a conflict.
2502 to resolve a conflict.
2486 """
2503 """
2487 keys = []
2504 keys = []
2488 # This won't be perfect, but can help performance significantly when
2505 # This won't be perfect, but can help performance significantly when
2489 # using things like remotefilelog.
2506 # using things like remotefilelog.
2490 scmutil.prefetchfiles(
2507 scmutil.prefetchfiles(
2491 self.repo(),
2508 self.repo(),
2492 [self.p1().rev()],
2509 [self.p1().rev()],
2493 scmutil.matchfiles(self.repo(), self._cache.keys()),
2510 scmutil.matchfiles(self.repo(), self._cache.keys()),
2494 )
2511 )
2495
2512
2496 for path in self._cache.keys():
2513 for path in self._cache.keys():
2497 cache = self._cache[path]
2514 cache = self._cache[path]
2498 try:
2515 try:
2499 underlying = self._wrappedctx[path]
2516 underlying = self._wrappedctx[path]
2500 if (
2517 if (
2501 underlying.data() == cache[b'data']
2518 underlying.data() == cache[b'data']
2502 and underlying.flags() == cache[b'flags']
2519 and underlying.flags() == cache[b'flags']
2503 ):
2520 ):
2504 keys.append(path)
2521 keys.append(path)
2505 except error.ManifestLookupError:
2522 except error.ManifestLookupError:
2506 # Path not in the underlying manifest (created).
2523 # Path not in the underlying manifest (created).
2507 continue
2524 continue
2508
2525
2509 for path in keys:
2526 for path in keys:
2510 del self._cache[path]
2527 del self._cache[path]
2511 return keys
2528 return keys
2512
2529
2513 def _markdirty(
2530 def _markdirty(
2514 self, path, exists, data=None, date=None, flags=b'', copied=None
2531 self, path, exists, data=None, date=None, flags=b'', copied=None
2515 ):
2532 ):
2516 # data not provided, let's see if we already have some; if not, let's
2533 # data not provided, let's see if we already have some; if not, let's
2517 # grab it from our underlying context, so that we always have data if
2534 # grab it from our underlying context, so that we always have data if
2518 # the file is marked as existing.
2535 # the file is marked as existing.
2519 if exists and data is None:
2536 if exists and data is None:
2520 oldentry = self._cache.get(path) or {}
2537 oldentry = self._cache.get(path) or {}
2521 data = oldentry.get(b'data')
2538 data = oldentry.get(b'data')
2522 if data is None:
2539 if data is None:
2523 data = self._wrappedctx[path].data()
2540 data = self._wrappedctx[path].data()
2524
2541
2525 self._cache[path] = {
2542 self._cache[path] = {
2526 b'exists': exists,
2543 b'exists': exists,
2527 b'data': data,
2544 b'data': data,
2528 b'date': date,
2545 b'date': date,
2529 b'flags': flags,
2546 b'flags': flags,
2530 b'copied': copied,
2547 b'copied': copied,
2531 }
2548 }
2532
2549
2533 def filectx(self, path, filelog=None):
2550 def filectx(self, path, filelog=None):
2534 return overlayworkingfilectx(
2551 return overlayworkingfilectx(
2535 self._repo, path, parent=self, filelog=filelog
2552 self._repo, path, parent=self, filelog=filelog
2536 )
2553 )
2537
2554
2538
2555
2539 class overlayworkingfilectx(committablefilectx):
2556 class overlayworkingfilectx(committablefilectx):
2540 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2557 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2541 cache, which can be flushed through later by calling ``flush()``."""
2558 cache, which can be flushed through later by calling ``flush()``."""
2542
2559
2543 def __init__(self, repo, path, filelog=None, parent=None):
2560 def __init__(self, repo, path, filelog=None, parent=None):
2544 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2561 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2545 self._repo = repo
2562 self._repo = repo
2546 self._parent = parent
2563 self._parent = parent
2547 self._path = path
2564 self._path = path
2548
2565
2549 def cmp(self, fctx):
2566 def cmp(self, fctx):
2550 return self.data() != fctx.data()
2567 return self.data() != fctx.data()
2551
2568
2552 def changectx(self):
2569 def changectx(self):
2553 return self._parent
2570 return self._parent
2554
2571
2555 def data(self):
2572 def data(self):
2556 return self._parent.data(self._path)
2573 return self._parent.data(self._path)
2557
2574
2558 def date(self):
2575 def date(self):
2559 return self._parent.filedate(self._path)
2576 return self._parent.filedate(self._path)
2560
2577
2561 def exists(self):
2578 def exists(self):
2562 return self.lexists()
2579 return self.lexists()
2563
2580
2564 def lexists(self):
2581 def lexists(self):
2565 return self._parent.exists(self._path)
2582 return self._parent.exists(self._path)
2566
2583
2567 def copysource(self):
2584 def copysource(self):
2568 return self._parent.copydata(self._path)
2585 return self._parent.copydata(self._path)
2569
2586
2570 def size(self):
2587 def size(self):
2571 return self._parent.size(self._path)
2588 return self._parent.size(self._path)
2572
2589
2573 def markcopied(self, origin):
2590 def markcopied(self, origin):
2574 self._parent.markcopied(self._path, origin)
2591 self._parent.markcopied(self._path, origin)
2575
2592
2576 def audit(self):
2593 def audit(self):
2577 pass
2594 pass
2578
2595
2579 def flags(self):
2596 def flags(self):
2580 return self._parent.flags(self._path)
2597 return self._parent.flags(self._path)
2581
2598
2582 def setflags(self, islink, isexec):
2599 def setflags(self, islink, isexec):
2583 return self._parent.setflags(self._path, islink, isexec)
2600 return self._parent.setflags(self._path, islink, isexec)
2584
2601
2585 def write(self, data, flags, backgroundclose=False, **kwargs):
2602 def write(self, data, flags, backgroundclose=False, **kwargs):
2586 return self._parent.write(self._path, data, flags, **kwargs)
2603 return self._parent.write(self._path, data, flags, **kwargs)
2587
2604
2588 def remove(self, ignoremissing=False):
2605 def remove(self, ignoremissing=False):
2589 return self._parent.remove(self._path)
2606 return self._parent.remove(self._path)
2590
2607
2591 def clearunknown(self):
2608 def clearunknown(self):
2592 pass
2609 pass
2593
2610
2594
2611
2595 class workingcommitctx(workingctx):
2612 class workingcommitctx(workingctx):
2596 """A workingcommitctx object makes access to data related to
2613 """A workingcommitctx object makes access to data related to
2597 the revision being committed convenient.
2614 the revision being committed convenient.
2598
2615
2599 This hides changes in the working directory, if they aren't
2616 This hides changes in the working directory, if they aren't
2600 committed in this context.
2617 committed in this context.
2601 """
2618 """
2602
2619
2603 def __init__(
2620 def __init__(
2604 self, repo, changes, text=b"", user=None, date=None, extra=None
2621 self, repo, changes, text=b"", user=None, date=None, extra=None
2605 ):
2622 ):
2606 super(workingcommitctx, self).__init__(
2623 super(workingcommitctx, self).__init__(
2607 repo, text, user, date, extra, changes
2624 repo, text, user, date, extra, changes
2608 )
2625 )
2609
2626
2610 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2627 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2611 """Return matched files only in ``self._status``
2628 """Return matched files only in ``self._status``
2612
2629
2613 Uncommitted files appear "clean" via this context, even if
2630 Uncommitted files appear "clean" via this context, even if
2614 they aren't actually so in the working directory.
2631 they aren't actually so in the working directory.
2615 """
2632 """
2616 if clean:
2633 if clean:
2617 clean = [f for f in self._manifest if f not in self._changedset]
2634 clean = [f for f in self._manifest if f not in self._changedset]
2618 else:
2635 else:
2619 clean = []
2636 clean = []
2620 return scmutil.status(
2637 return scmutil.status(
2621 [f for f in self._status.modified if match(f)],
2638 [f for f in self._status.modified if match(f)],
2622 [f for f in self._status.added if match(f)],
2639 [f for f in self._status.added if match(f)],
2623 [f for f in self._status.removed if match(f)],
2640 [f for f in self._status.removed if match(f)],
2624 [],
2641 [],
2625 [],
2642 [],
2626 [],
2643 [],
2627 clean,
2644 clean,
2628 )
2645 )
2629
2646
2630 @propertycache
2647 @propertycache
2631 def _changedset(self):
2648 def _changedset(self):
2632 """Return the set of files changed in this context
2649 """Return the set of files changed in this context
2633 """
2650 """
2634 changed = set(self._status.modified)
2651 changed = set(self._status.modified)
2635 changed.update(self._status.added)
2652 changed.update(self._status.added)
2636 changed.update(self._status.removed)
2653 changed.update(self._status.removed)
2637 return changed
2654 return changed
2638
2655
2639
2656
2640 def makecachingfilectxfn(func):
2657 def makecachingfilectxfn(func):
2641 """Create a filectxfn that caches based on the path.
2658 """Create a filectxfn that caches based on the path.
2642
2659
2643 We can't use util.cachefunc because it uses all arguments as the cache
2660 We can't use util.cachefunc because it uses all arguments as the cache
2644 key and this creates a cycle since the arguments include the repo and
2661 key and this creates a cycle since the arguments include the repo and
2645 memctx.
2662 memctx.
2646 """
2663 """
2647 cache = {}
2664 cache = {}
2648
2665
2649 def getfilectx(repo, memctx, path):
2666 def getfilectx(repo, memctx, path):
2650 if path not in cache:
2667 if path not in cache:
2651 cache[path] = func(repo, memctx, path)
2668 cache[path] = func(repo, memctx, path)
2652 return cache[path]
2669 return cache[path]
2653
2670
2654 return getfilectx
2671 return getfilectx
2655
2672
2656
2673
2657 def memfilefromctx(ctx):
2674 def memfilefromctx(ctx):
2658 """Given a context return a memfilectx for ctx[path]
2675 """Given a context return a memfilectx for ctx[path]
2659
2676
2660 This is a convenience method for building a memctx based on another
2677 This is a convenience method for building a memctx based on another
2661 context.
2678 context.
2662 """
2679 """
2663
2680
2664 def getfilectx(repo, memctx, path):
2681 def getfilectx(repo, memctx, path):
2665 fctx = ctx[path]
2682 fctx = ctx[path]
2666 copysource = fctx.copysource()
2683 copysource = fctx.copysource()
2667 return memfilectx(
2684 return memfilectx(
2668 repo,
2685 repo,
2669 memctx,
2686 memctx,
2670 path,
2687 path,
2671 fctx.data(),
2688 fctx.data(),
2672 islink=fctx.islink(),
2689 islink=fctx.islink(),
2673 isexec=fctx.isexec(),
2690 isexec=fctx.isexec(),
2674 copysource=copysource,
2691 copysource=copysource,
2675 )
2692 )
2676
2693
2677 return getfilectx
2694 return getfilectx
2678
2695
2679
2696
2680 def memfilefrompatch(patchstore):
2697 def memfilefrompatch(patchstore):
2681 """Given a patch (e.g. patchstore object) return a memfilectx
2698 """Given a patch (e.g. patchstore object) return a memfilectx
2682
2699
2683 This is a convenience method for building a memctx based on a patchstore.
2700 This is a convenience method for building a memctx based on a patchstore.
2684 """
2701 """
2685
2702
2686 def getfilectx(repo, memctx, path):
2703 def getfilectx(repo, memctx, path):
2687 data, mode, copysource = patchstore.getfile(path)
2704 data, mode, copysource = patchstore.getfile(path)
2688 if data is None:
2705 if data is None:
2689 return None
2706 return None
2690 islink, isexec = mode
2707 islink, isexec = mode
2691 return memfilectx(
2708 return memfilectx(
2692 repo,
2709 repo,
2693 memctx,
2710 memctx,
2694 path,
2711 path,
2695 data,
2712 data,
2696 islink=islink,
2713 islink=islink,
2697 isexec=isexec,
2714 isexec=isexec,
2698 copysource=copysource,
2715 copysource=copysource,
2699 )
2716 )
2700
2717
2701 return getfilectx
2718 return getfilectx
2702
2719
2703
2720
2704 class memctx(committablectx):
2721 class memctx(committablectx):
2705 """Use memctx to perform in-memory commits via localrepo.commitctx().
2722 """Use memctx to perform in-memory commits via localrepo.commitctx().
2706
2723
2707 Revision information is supplied at initialization time while
2724 Revision information is supplied at initialization time while
2708 related files data and is made available through a callback
2725 related files data and is made available through a callback
2709 mechanism. 'repo' is the current localrepo, 'parents' is a
2726 mechanism. 'repo' is the current localrepo, 'parents' is a
2710 sequence of two parent revisions identifiers (pass None for every
2727 sequence of two parent revisions identifiers (pass None for every
2711 missing parent), 'text' is the commit message and 'files' lists
2728 missing parent), 'text' is the commit message and 'files' lists
2712 names of files touched by the revision (normalized and relative to
2729 names of files touched by the revision (normalized and relative to
2713 repository root).
2730 repository root).
2714
2731
2715 filectxfn(repo, memctx, path) is a callable receiving the
2732 filectxfn(repo, memctx, path) is a callable receiving the
2716 repository, the current memctx object and the normalized path of
2733 repository, the current memctx object and the normalized path of
2717 requested file, relative to repository root. It is fired by the
2734 requested file, relative to repository root. It is fired by the
2718 commit function for every file in 'files', but calls order is
2735 commit function for every file in 'files', but calls order is
2719 undefined. If the file is available in the revision being
2736 undefined. If the file is available in the revision being
2720 committed (updated or added), filectxfn returns a memfilectx
2737 committed (updated or added), filectxfn returns a memfilectx
2721 object. If the file was removed, filectxfn return None for recent
2738 object. If the file was removed, filectxfn return None for recent
2722 Mercurial. Moved files are represented by marking the source file
2739 Mercurial. Moved files are represented by marking the source file
2723 removed and the new file added with copy information (see
2740 removed and the new file added with copy information (see
2724 memfilectx).
2741 memfilectx).
2725
2742
2726 user receives the committer name and defaults to current
2743 user receives the committer name and defaults to current
2727 repository username, date is the commit date in any format
2744 repository username, date is the commit date in any format
2728 supported by dateutil.parsedate() and defaults to current date, extra
2745 supported by dateutil.parsedate() and defaults to current date, extra
2729 is a dictionary of metadata or is left empty.
2746 is a dictionary of metadata or is left empty.
2730 """
2747 """
2731
2748
2732 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2749 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2733 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2750 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2734 # this field to determine what to do in filectxfn.
2751 # this field to determine what to do in filectxfn.
2735 _returnnoneformissingfiles = True
2752 _returnnoneformissingfiles = True
2736
2753
2737 def __init__(
2754 def __init__(
2738 self,
2755 self,
2739 repo,
2756 repo,
2740 parents,
2757 parents,
2741 text,
2758 text,
2742 files,
2759 files,
2743 filectxfn,
2760 filectxfn,
2744 user=None,
2761 user=None,
2745 date=None,
2762 date=None,
2746 extra=None,
2763 extra=None,
2747 branch=None,
2764 branch=None,
2748 editor=None,
2765 editor=None,
2749 ):
2766 ):
2750 super(memctx, self).__init__(
2767 super(memctx, self).__init__(
2751 repo, text, user, date, extra, branch=branch
2768 repo, text, user, date, extra, branch=branch
2752 )
2769 )
2753 self._rev = None
2770 self._rev = None
2754 self._node = None
2771 self._node = None
2755 parents = [(p or nullid) for p in parents]
2772 parents = [(p or nullid) for p in parents]
2756 p1, p2 = parents
2773 p1, p2 = parents
2757 self._parents = [self._repo[p] for p in (p1, p2)]
2774 self._parents = [self._repo[p] for p in (p1, p2)]
2758 files = sorted(set(files))
2775 files = sorted(set(files))
2759 self._files = files
2776 self._files = files
2760 self.substate = {}
2777 self.substate = {}
2761
2778
2762 if isinstance(filectxfn, patch.filestore):
2779 if isinstance(filectxfn, patch.filestore):
2763 filectxfn = memfilefrompatch(filectxfn)
2780 filectxfn = memfilefrompatch(filectxfn)
2764 elif not callable(filectxfn):
2781 elif not callable(filectxfn):
2765 # if store is not callable, wrap it in a function
2782 # if store is not callable, wrap it in a function
2766 filectxfn = memfilefromctx(filectxfn)
2783 filectxfn = memfilefromctx(filectxfn)
2767
2784
2768 # memoizing increases performance for e.g. vcs convert scenarios.
2785 # memoizing increases performance for e.g. vcs convert scenarios.
2769 self._filectxfn = makecachingfilectxfn(filectxfn)
2786 self._filectxfn = makecachingfilectxfn(filectxfn)
2770
2787
2771 if editor:
2788 if editor:
2772 self._text = editor(self._repo, self, [])
2789 self._text = editor(self._repo, self, [])
2773 self._repo.savecommitmessage(self._text)
2790 self._repo.savecommitmessage(self._text)
2774
2791
2775 def filectx(self, path, filelog=None):
2792 def filectx(self, path, filelog=None):
2776 """get a file context from the working directory
2793 """get a file context from the working directory
2777
2794
2778 Returns None if file doesn't exist and should be removed."""
2795 Returns None if file doesn't exist and should be removed."""
2779 return self._filectxfn(self._repo, self, path)
2796 return self._filectxfn(self._repo, self, path)
2780
2797
2781 def commit(self):
2798 def commit(self):
2782 """commit context to the repo"""
2799 """commit context to the repo"""
2783 return self._repo.commitctx(self)
2800 return self._repo.commitctx(self)
2784
2801
2785 @propertycache
2802 @propertycache
2786 def _manifest(self):
2803 def _manifest(self):
2787 """generate a manifest based on the return values of filectxfn"""
2804 """generate a manifest based on the return values of filectxfn"""
2788
2805
2789 # keep this simple for now; just worry about p1
2806 # keep this simple for now; just worry about p1
2790 pctx = self._parents[0]
2807 pctx = self._parents[0]
2791 man = pctx.manifest().copy()
2808 man = pctx.manifest().copy()
2792
2809
2793 for f in self._status.modified:
2810 for f in self._status.modified:
2794 man[f] = modifiednodeid
2811 man[f] = modifiednodeid
2795
2812
2796 for f in self._status.added:
2813 for f in self._status.added:
2797 man[f] = addednodeid
2814 man[f] = addednodeid
2798
2815
2799 for f in self._status.removed:
2816 for f in self._status.removed:
2800 if f in man:
2817 if f in man:
2801 del man[f]
2818 del man[f]
2802
2819
2803 return man
2820 return man
2804
2821
2805 @propertycache
2822 @propertycache
2806 def _status(self):
2823 def _status(self):
2807 """Calculate exact status from ``files`` specified at construction
2824 """Calculate exact status from ``files`` specified at construction
2808 """
2825 """
2809 man1 = self.p1().manifest()
2826 man1 = self.p1().manifest()
2810 p2 = self._parents[1]
2827 p2 = self._parents[1]
2811 # "1 < len(self._parents)" can't be used for checking
2828 # "1 < len(self._parents)" can't be used for checking
2812 # existence of the 2nd parent, because "memctx._parents" is
2829 # existence of the 2nd parent, because "memctx._parents" is
2813 # explicitly initialized by the list, of which length is 2.
2830 # explicitly initialized by the list, of which length is 2.
2814 if p2.node() != nullid:
2831 if p2.node() != nullid:
2815 man2 = p2.manifest()
2832 man2 = p2.manifest()
2816 managing = lambda f: f in man1 or f in man2
2833 managing = lambda f: f in man1 or f in man2
2817 else:
2834 else:
2818 managing = lambda f: f in man1
2835 managing = lambda f: f in man1
2819
2836
2820 modified, added, removed = [], [], []
2837 modified, added, removed = [], [], []
2821 for f in self._files:
2838 for f in self._files:
2822 if not managing(f):
2839 if not managing(f):
2823 added.append(f)
2840 added.append(f)
2824 elif self[f]:
2841 elif self[f]:
2825 modified.append(f)
2842 modified.append(f)
2826 else:
2843 else:
2827 removed.append(f)
2844 removed.append(f)
2828
2845
2829 return scmutil.status(modified, added, removed, [], [], [], [])
2846 return scmutil.status(modified, added, removed, [], [], [], [])
2830
2847
2831
2848
2832 class memfilectx(committablefilectx):
2849 class memfilectx(committablefilectx):
2833 """memfilectx represents an in-memory file to commit.
2850 """memfilectx represents an in-memory file to commit.
2834
2851
2835 See memctx and committablefilectx for more details.
2852 See memctx and committablefilectx for more details.
2836 """
2853 """
2837
2854
2838 def __init__(
2855 def __init__(
2839 self,
2856 self,
2840 repo,
2857 repo,
2841 changectx,
2858 changectx,
2842 path,
2859 path,
2843 data,
2860 data,
2844 islink=False,
2861 islink=False,
2845 isexec=False,
2862 isexec=False,
2846 copysource=None,
2863 copysource=None,
2847 ):
2864 ):
2848 """
2865 """
2849 path is the normalized file path relative to repository root.
2866 path is the normalized file path relative to repository root.
2850 data is the file content as a string.
2867 data is the file content as a string.
2851 islink is True if the file is a symbolic link.
2868 islink is True if the file is a symbolic link.
2852 isexec is True if the file is executable.
2869 isexec is True if the file is executable.
2853 copied is the source file path if current file was copied in the
2870 copied is the source file path if current file was copied in the
2854 revision being committed, or None."""
2871 revision being committed, or None."""
2855 super(memfilectx, self).__init__(repo, path, None, changectx)
2872 super(memfilectx, self).__init__(repo, path, None, changectx)
2856 self._data = data
2873 self._data = data
2857 if islink:
2874 if islink:
2858 self._flags = b'l'
2875 self._flags = b'l'
2859 elif isexec:
2876 elif isexec:
2860 self._flags = b'x'
2877 self._flags = b'x'
2861 else:
2878 else:
2862 self._flags = b''
2879 self._flags = b''
2863 self._copysource = copysource
2880 self._copysource = copysource
2864
2881
2865 def copysource(self):
2882 def copysource(self):
2866 return self._copysource
2883 return self._copysource
2867
2884
2868 def cmp(self, fctx):
2885 def cmp(self, fctx):
2869 return self.data() != fctx.data()
2886 return self.data() != fctx.data()
2870
2887
2871 def data(self):
2888 def data(self):
2872 return self._data
2889 return self._data
2873
2890
2874 def remove(self, ignoremissing=False):
2891 def remove(self, ignoremissing=False):
2875 """wraps unlink for a repo's working directory"""
2892 """wraps unlink for a repo's working directory"""
2876 # need to figure out what to do here
2893 # need to figure out what to do here
2877 del self._changectx[self._path]
2894 del self._changectx[self._path]
2878
2895
2879 def write(self, data, flags, **kwargs):
2896 def write(self, data, flags, **kwargs):
2880 """wraps repo.wwrite"""
2897 """wraps repo.wwrite"""
2881 self._data = data
2898 self._data = data
2882
2899
2883
2900
2884 class metadataonlyctx(committablectx):
2901 class metadataonlyctx(committablectx):
2885 """Like memctx but it's reusing the manifest of different commit.
2902 """Like memctx but it's reusing the manifest of different commit.
2886 Intended to be used by lightweight operations that are creating
2903 Intended to be used by lightweight operations that are creating
2887 metadata-only changes.
2904 metadata-only changes.
2888
2905
2889 Revision information is supplied at initialization time. 'repo' is the
2906 Revision information is supplied at initialization time. 'repo' is the
2890 current localrepo, 'ctx' is original revision which manifest we're reuisng
2907 current localrepo, 'ctx' is original revision which manifest we're reuisng
2891 'parents' is a sequence of two parent revisions identifiers (pass None for
2908 'parents' is a sequence of two parent revisions identifiers (pass None for
2892 every missing parent), 'text' is the commit.
2909 every missing parent), 'text' is the commit.
2893
2910
2894 user receives the committer name and defaults to current repository
2911 user receives the committer name and defaults to current repository
2895 username, date is the commit date in any format supported by
2912 username, date is the commit date in any format supported by
2896 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2913 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2897 metadata or is left empty.
2914 metadata or is left empty.
2898 """
2915 """
2899
2916
2900 def __init__(
2917 def __init__(
2901 self,
2918 self,
2902 repo,
2919 repo,
2903 originalctx,
2920 originalctx,
2904 parents=None,
2921 parents=None,
2905 text=None,
2922 text=None,
2906 user=None,
2923 user=None,
2907 date=None,
2924 date=None,
2908 extra=None,
2925 extra=None,
2909 editor=None,
2926 editor=None,
2910 ):
2927 ):
2911 if text is None:
2928 if text is None:
2912 text = originalctx.description()
2929 text = originalctx.description()
2913 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2930 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2914 self._rev = None
2931 self._rev = None
2915 self._node = None
2932 self._node = None
2916 self._originalctx = originalctx
2933 self._originalctx = originalctx
2917 self._manifestnode = originalctx.manifestnode()
2934 self._manifestnode = originalctx.manifestnode()
2918 if parents is None:
2935 if parents is None:
2919 parents = originalctx.parents()
2936 parents = originalctx.parents()
2920 else:
2937 else:
2921 parents = [repo[p] for p in parents if p is not None]
2938 parents = [repo[p] for p in parents if p is not None]
2922 parents = parents[:]
2939 parents = parents[:]
2923 while len(parents) < 2:
2940 while len(parents) < 2:
2924 parents.append(repo[nullid])
2941 parents.append(repo[nullid])
2925 p1, p2 = self._parents = parents
2942 p1, p2 = self._parents = parents
2926
2943
2927 # sanity check to ensure that the reused manifest parents are
2944 # sanity check to ensure that the reused manifest parents are
2928 # manifests of our commit parents
2945 # manifests of our commit parents
2929 mp1, mp2 = self.manifestctx().parents
2946 mp1, mp2 = self.manifestctx().parents
2930 if p1 != nullid and p1.manifestnode() != mp1:
2947 if p1 != nullid and p1.manifestnode() != mp1:
2931 raise RuntimeError(
2948 raise RuntimeError(
2932 r"can't reuse the manifest: its p1 "
2949 r"can't reuse the manifest: its p1 "
2933 r"doesn't match the new ctx p1"
2950 r"doesn't match the new ctx p1"
2934 )
2951 )
2935 if p2 != nullid and p2.manifestnode() != mp2:
2952 if p2 != nullid and p2.manifestnode() != mp2:
2936 raise RuntimeError(
2953 raise RuntimeError(
2937 r"can't reuse the manifest: "
2954 r"can't reuse the manifest: "
2938 r"its p2 doesn't match the new ctx p2"
2955 r"its p2 doesn't match the new ctx p2"
2939 )
2956 )
2940
2957
2941 self._files = originalctx.files()
2958 self._files = originalctx.files()
2942 self.substate = {}
2959 self.substate = {}
2943
2960
2944 if editor:
2961 if editor:
2945 self._text = editor(self._repo, self, [])
2962 self._text = editor(self._repo, self, [])
2946 self._repo.savecommitmessage(self._text)
2963 self._repo.savecommitmessage(self._text)
2947
2964
2948 def manifestnode(self):
2965 def manifestnode(self):
2949 return self._manifestnode
2966 return self._manifestnode
2950
2967
2951 @property
2968 @property
2952 def _manifestctx(self):
2969 def _manifestctx(self):
2953 return self._repo.manifestlog[self._manifestnode]
2970 return self._repo.manifestlog[self._manifestnode]
2954
2971
2955 def filectx(self, path, filelog=None):
2972 def filectx(self, path, filelog=None):
2956 return self._originalctx.filectx(path, filelog=filelog)
2973 return self._originalctx.filectx(path, filelog=filelog)
2957
2974
2958 def commit(self):
2975 def commit(self):
2959 """commit context to the repo"""
2976 """commit context to the repo"""
2960 return self._repo.commitctx(self)
2977 return self._repo.commitctx(self)
2961
2978
2962 @property
2979 @property
2963 def _manifest(self):
2980 def _manifest(self):
2964 return self._originalctx.manifest()
2981 return self._originalctx.manifest()
2965
2982
2966 @propertycache
2983 @propertycache
2967 def _status(self):
2984 def _status(self):
2968 """Calculate exact status from ``files`` specified in the ``origctx``
2985 """Calculate exact status from ``files`` specified in the ``origctx``
2969 and parents manifests.
2986 and parents manifests.
2970 """
2987 """
2971 man1 = self.p1().manifest()
2988 man1 = self.p1().manifest()
2972 p2 = self._parents[1]
2989 p2 = self._parents[1]
2973 # "1 < len(self._parents)" can't be used for checking
2990 # "1 < len(self._parents)" can't be used for checking
2974 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2991 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2975 # explicitly initialized by the list, of which length is 2.
2992 # explicitly initialized by the list, of which length is 2.
2976 if p2.node() != nullid:
2993 if p2.node() != nullid:
2977 man2 = p2.manifest()
2994 man2 = p2.manifest()
2978 managing = lambda f: f in man1 or f in man2
2995 managing = lambda f: f in man1 or f in man2
2979 else:
2996 else:
2980 managing = lambda f: f in man1
2997 managing = lambda f: f in man1
2981
2998
2982 modified, added, removed = [], [], []
2999 modified, added, removed = [], [], []
2983 for f in self._files:
3000 for f in self._files:
2984 if not managing(f):
3001 if not managing(f):
2985 added.append(f)
3002 added.append(f)
2986 elif f in self:
3003 elif f in self:
2987 modified.append(f)
3004 modified.append(f)
2988 else:
3005 else:
2989 removed.append(f)
3006 removed.append(f)
2990
3007
2991 return scmutil.status(modified, added, removed, [], [], [], [])
3008 return scmutil.status(modified, added, removed, [], [], [], [])
2992
3009
2993
3010
2994 class arbitraryfilectx(object):
3011 class arbitraryfilectx(object):
2995 """Allows you to use filectx-like functions on a file in an arbitrary
3012 """Allows you to use filectx-like functions on a file in an arbitrary
2996 location on disk, possibly not in the working directory.
3013 location on disk, possibly not in the working directory.
2997 """
3014 """
2998
3015
2999 def __init__(self, path, repo=None):
3016 def __init__(self, path, repo=None):
3000 # Repo is optional because contrib/simplemerge uses this class.
3017 # Repo is optional because contrib/simplemerge uses this class.
3001 self._repo = repo
3018 self._repo = repo
3002 self._path = path
3019 self._path = path
3003
3020
3004 def cmp(self, fctx):
3021 def cmp(self, fctx):
3005 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3022 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3006 # path if either side is a symlink.
3023 # path if either side is a symlink.
3007 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3024 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3008 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3025 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3009 # Add a fast-path for merge if both sides are disk-backed.
3026 # Add a fast-path for merge if both sides are disk-backed.
3010 # Note that filecmp uses the opposite return values (True if same)
3027 # Note that filecmp uses the opposite return values (True if same)
3011 # from our cmp functions (True if different).
3028 # from our cmp functions (True if different).
3012 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3029 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3013 return self.data() != fctx.data()
3030 return self.data() != fctx.data()
3014
3031
3015 def path(self):
3032 def path(self):
3016 return self._path
3033 return self._path
3017
3034
3018 def flags(self):
3035 def flags(self):
3019 return b''
3036 return b''
3020
3037
3021 def data(self):
3038 def data(self):
3022 return util.readfile(self._path)
3039 return util.readfile(self._path)
3023
3040
3024 def decodeddata(self):
3041 def decodeddata(self):
3025 with open(self._path, b"rb") as f:
3042 with open(self._path, b"rb") as f:
3026 return f.read()
3043 return f.read()
3027
3044
3028 def remove(self):
3045 def remove(self):
3029 util.unlink(self._path)
3046 util.unlink(self._path)
3030
3047
3031 def write(self, data, flags, **kwargs):
3048 def write(self, data, flags, **kwargs):
3032 assert not flags
3049 assert not flags
3033 with open(self._path, b"wb") as f:
3050 with open(self._path, b"wb") as f:
3034 f.write(data)
3051 f.write(data)
@@ -1,3747 +1,3734 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import os
12 import os
13 import random
13 import random
14 import sys
14 import sys
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 bin,
20 bin,
21 hex,
21 hex,
22 nullid,
22 nullid,
23 nullrev,
23 nullrev,
24 short,
24 short,
25 )
25 )
26 from .pycompat import (
26 from .pycompat import (
27 delattr,
27 delattr,
28 getattr,
28 getattr,
29 )
29 )
30 from . import (
30 from . import (
31 bookmarks,
31 bookmarks,
32 branchmap,
32 branchmap,
33 bundle2,
33 bundle2,
34 changegroup,
34 changegroup,
35 color,
35 color,
36 context,
36 context,
37 dirstate,
37 dirstate,
38 dirstateguard,
38 dirstateguard,
39 discovery,
39 discovery,
40 encoding,
40 encoding,
41 error,
41 error,
42 exchange,
42 exchange,
43 extensions,
43 extensions,
44 filelog,
44 filelog,
45 hook,
45 hook,
46 lock as lockmod,
46 lock as lockmod,
47 match as matchmod,
47 match as matchmod,
48 merge as mergemod,
48 merge as mergemod,
49 mergeutil,
49 mergeutil,
50 namespaces,
50 namespaces,
51 narrowspec,
51 narrowspec,
52 obsolete,
52 obsolete,
53 pathutil,
53 pathutil,
54 phases,
54 phases,
55 pushkey,
55 pushkey,
56 pycompat,
56 pycompat,
57 repoview,
57 repoview,
58 revset,
58 revset,
59 revsetlang,
59 revsetlang,
60 scmutil,
60 scmutil,
61 sparse,
61 sparse,
62 store as storemod,
62 store as storemod,
63 subrepoutil,
63 subrepoutil,
64 tags as tagsmod,
64 tags as tagsmod,
65 transaction,
65 transaction,
66 txnutil,
66 txnutil,
67 util,
67 util,
68 vfs as vfsmod,
68 vfs as vfsmod,
69 )
69 )
70
70
71 from .interfaces import (
71 from .interfaces import (
72 repository,
72 repository,
73 util as interfaceutil,
73 util as interfaceutil,
74 )
74 )
75
75
76 from .utils import (
76 from .utils import (
77 procutil,
77 procutil,
78 stringutil,
78 stringutil,
79 )
79 )
80
80
81 from .revlogutils import constants as revlogconst
81 from .revlogutils import constants as revlogconst
82
82
83 release = lockmod.release
83 release = lockmod.release
84 urlerr = util.urlerr
84 urlerr = util.urlerr
85 urlreq = util.urlreq
85 urlreq = util.urlreq
86
86
87 # set of (path, vfs-location) tuples. vfs-location is:
87 # set of (path, vfs-location) tuples. vfs-location is:
88 # - 'plain for vfs relative paths
88 # - 'plain for vfs relative paths
89 # - '' for svfs relative paths
89 # - '' for svfs relative paths
90 _cachedfiles = set()
90 _cachedfiles = set()
91
91
92
92
93 class _basefilecache(scmutil.filecache):
93 class _basefilecache(scmutil.filecache):
94 """All filecache usage on repo are done for logic that should be unfiltered
94 """All filecache usage on repo are done for logic that should be unfiltered
95 """
95 """
96
96
97 def __get__(self, repo, type=None):
97 def __get__(self, repo, type=None):
98 if repo is None:
98 if repo is None:
99 return self
99 return self
100 # proxy to unfiltered __dict__ since filtered repo has no entry
100 # proxy to unfiltered __dict__ since filtered repo has no entry
101 unfi = repo.unfiltered()
101 unfi = repo.unfiltered()
102 try:
102 try:
103 return unfi.__dict__[self.sname]
103 return unfi.__dict__[self.sname]
104 except KeyError:
104 except KeyError:
105 pass
105 pass
106 return super(_basefilecache, self).__get__(unfi, type)
106 return super(_basefilecache, self).__get__(unfi, type)
107
107
108 def set(self, repo, value):
108 def set(self, repo, value):
109 return super(_basefilecache, self).set(repo.unfiltered(), value)
109 return super(_basefilecache, self).set(repo.unfiltered(), value)
110
110
111
111
112 class repofilecache(_basefilecache):
112 class repofilecache(_basefilecache):
113 """filecache for files in .hg but outside of .hg/store"""
113 """filecache for files in .hg but outside of .hg/store"""
114
114
115 def __init__(self, *paths):
115 def __init__(self, *paths):
116 super(repofilecache, self).__init__(*paths)
116 super(repofilecache, self).__init__(*paths)
117 for path in paths:
117 for path in paths:
118 _cachedfiles.add((path, b'plain'))
118 _cachedfiles.add((path, b'plain'))
119
119
120 def join(self, obj, fname):
120 def join(self, obj, fname):
121 return obj.vfs.join(fname)
121 return obj.vfs.join(fname)
122
122
123
123
124 class storecache(_basefilecache):
124 class storecache(_basefilecache):
125 """filecache for files in the store"""
125 """filecache for files in the store"""
126
126
127 def __init__(self, *paths):
127 def __init__(self, *paths):
128 super(storecache, self).__init__(*paths)
128 super(storecache, self).__init__(*paths)
129 for path in paths:
129 for path in paths:
130 _cachedfiles.add((path, b''))
130 _cachedfiles.add((path, b''))
131
131
132 def join(self, obj, fname):
132 def join(self, obj, fname):
133 return obj.sjoin(fname)
133 return obj.sjoin(fname)
134
134
135
135
136 class mixedrepostorecache(_basefilecache):
136 class mixedrepostorecache(_basefilecache):
137 """filecache for a mix files in .hg/store and outside"""
137 """filecache for a mix files in .hg/store and outside"""
138
138
139 def __init__(self, *pathsandlocations):
139 def __init__(self, *pathsandlocations):
140 # scmutil.filecache only uses the path for passing back into our
140 # scmutil.filecache only uses the path for passing back into our
141 # join(), so we can safely pass a list of paths and locations
141 # join(), so we can safely pass a list of paths and locations
142 super(mixedrepostorecache, self).__init__(*pathsandlocations)
142 super(mixedrepostorecache, self).__init__(*pathsandlocations)
143 _cachedfiles.update(pathsandlocations)
143 _cachedfiles.update(pathsandlocations)
144
144
145 def join(self, obj, fnameandlocation):
145 def join(self, obj, fnameandlocation):
146 fname, location = fnameandlocation
146 fname, location = fnameandlocation
147 if location == b'plain':
147 if location == b'plain':
148 return obj.vfs.join(fname)
148 return obj.vfs.join(fname)
149 else:
149 else:
150 if location != b'':
150 if location != b'':
151 raise error.ProgrammingError(
151 raise error.ProgrammingError(
152 b'unexpected location: %s' % location
152 b'unexpected location: %s' % location
153 )
153 )
154 return obj.sjoin(fname)
154 return obj.sjoin(fname)
155
155
156
156
157 def isfilecached(repo, name):
157 def isfilecached(repo, name):
158 """check if a repo has already cached "name" filecache-ed property
158 """check if a repo has already cached "name" filecache-ed property
159
159
160 This returns (cachedobj-or-None, iscached) tuple.
160 This returns (cachedobj-or-None, iscached) tuple.
161 """
161 """
162 cacheentry = repo.unfiltered()._filecache.get(name, None)
162 cacheentry = repo.unfiltered()._filecache.get(name, None)
163 if not cacheentry:
163 if not cacheentry:
164 return None, False
164 return None, False
165 return cacheentry.obj, True
165 return cacheentry.obj, True
166
166
167
167
168 class unfilteredpropertycache(util.propertycache):
168 class unfilteredpropertycache(util.propertycache):
169 """propertycache that apply to unfiltered repo only"""
169 """propertycache that apply to unfiltered repo only"""
170
170
171 def __get__(self, repo, type=None):
171 def __get__(self, repo, type=None):
172 unfi = repo.unfiltered()
172 unfi = repo.unfiltered()
173 if unfi is repo:
173 if unfi is repo:
174 return super(unfilteredpropertycache, self).__get__(unfi)
174 return super(unfilteredpropertycache, self).__get__(unfi)
175 return getattr(unfi, self.name)
175 return getattr(unfi, self.name)
176
176
177
177
178 class filteredpropertycache(util.propertycache):
178 class filteredpropertycache(util.propertycache):
179 """propertycache that must take filtering in account"""
179 """propertycache that must take filtering in account"""
180
180
181 def cachevalue(self, obj, value):
181 def cachevalue(self, obj, value):
182 object.__setattr__(obj, self.name, value)
182 object.__setattr__(obj, self.name, value)
183
183
184
184
185 def hasunfilteredcache(repo, name):
185 def hasunfilteredcache(repo, name):
186 """check if a repo has an unfilteredpropertycache value for <name>"""
186 """check if a repo has an unfilteredpropertycache value for <name>"""
187 return name in vars(repo.unfiltered())
187 return name in vars(repo.unfiltered())
188
188
189
189
190 def unfilteredmethod(orig):
190 def unfilteredmethod(orig):
191 """decorate method that always need to be run on unfiltered version"""
191 """decorate method that always need to be run on unfiltered version"""
192
192
193 def wrapper(repo, *args, **kwargs):
193 def wrapper(repo, *args, **kwargs):
194 return orig(repo.unfiltered(), *args, **kwargs)
194 return orig(repo.unfiltered(), *args, **kwargs)
195
195
196 return wrapper
196 return wrapper
197
197
198
198
199 moderncaps = {
199 moderncaps = {
200 b'lookup',
200 b'lookup',
201 b'branchmap',
201 b'branchmap',
202 b'pushkey',
202 b'pushkey',
203 b'known',
203 b'known',
204 b'getbundle',
204 b'getbundle',
205 b'unbundle',
205 b'unbundle',
206 }
206 }
207 legacycaps = moderncaps.union({b'changegroupsubset'})
207 legacycaps = moderncaps.union({b'changegroupsubset'})
208
208
209
209
210 @interfaceutil.implementer(repository.ipeercommandexecutor)
210 @interfaceutil.implementer(repository.ipeercommandexecutor)
211 class localcommandexecutor(object):
211 class localcommandexecutor(object):
212 def __init__(self, peer):
212 def __init__(self, peer):
213 self._peer = peer
213 self._peer = peer
214 self._sent = False
214 self._sent = False
215 self._closed = False
215 self._closed = False
216
216
217 def __enter__(self):
217 def __enter__(self):
218 return self
218 return self
219
219
220 def __exit__(self, exctype, excvalue, exctb):
220 def __exit__(self, exctype, excvalue, exctb):
221 self.close()
221 self.close()
222
222
223 def callcommand(self, command, args):
223 def callcommand(self, command, args):
224 if self._sent:
224 if self._sent:
225 raise error.ProgrammingError(
225 raise error.ProgrammingError(
226 b'callcommand() cannot be used after sendcommands()'
226 b'callcommand() cannot be used after sendcommands()'
227 )
227 )
228
228
229 if self._closed:
229 if self._closed:
230 raise error.ProgrammingError(
230 raise error.ProgrammingError(
231 b'callcommand() cannot be used after close()'
231 b'callcommand() cannot be used after close()'
232 )
232 )
233
233
234 # We don't need to support anything fancy. Just call the named
234 # We don't need to support anything fancy. Just call the named
235 # method on the peer and return a resolved future.
235 # method on the peer and return a resolved future.
236 fn = getattr(self._peer, pycompat.sysstr(command))
236 fn = getattr(self._peer, pycompat.sysstr(command))
237
237
238 f = pycompat.futures.Future()
238 f = pycompat.futures.Future()
239
239
240 try:
240 try:
241 result = fn(**pycompat.strkwargs(args))
241 result = fn(**pycompat.strkwargs(args))
242 except Exception:
242 except Exception:
243 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
243 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
244 else:
244 else:
245 f.set_result(result)
245 f.set_result(result)
246
246
247 return f
247 return f
248
248
249 def sendcommands(self):
249 def sendcommands(self):
250 self._sent = True
250 self._sent = True
251
251
252 def close(self):
252 def close(self):
253 self._closed = True
253 self._closed = True
254
254
255
255
256 @interfaceutil.implementer(repository.ipeercommands)
256 @interfaceutil.implementer(repository.ipeercommands)
257 class localpeer(repository.peer):
257 class localpeer(repository.peer):
258 '''peer for a local repo; reflects only the most recent API'''
258 '''peer for a local repo; reflects only the most recent API'''
259
259
260 def __init__(self, repo, caps=None):
260 def __init__(self, repo, caps=None):
261 super(localpeer, self).__init__()
261 super(localpeer, self).__init__()
262
262
263 if caps is None:
263 if caps is None:
264 caps = moderncaps.copy()
264 caps = moderncaps.copy()
265 self._repo = repo.filtered(b'served')
265 self._repo = repo.filtered(b'served')
266 self.ui = repo.ui
266 self.ui = repo.ui
267 self._caps = repo._restrictcapabilities(caps)
267 self._caps = repo._restrictcapabilities(caps)
268
268
269 # Begin of _basepeer interface.
269 # Begin of _basepeer interface.
270
270
271 def url(self):
271 def url(self):
272 return self._repo.url()
272 return self._repo.url()
273
273
274 def local(self):
274 def local(self):
275 return self._repo
275 return self._repo
276
276
277 def peer(self):
277 def peer(self):
278 return self
278 return self
279
279
280 def canpush(self):
280 def canpush(self):
281 return True
281 return True
282
282
283 def close(self):
283 def close(self):
284 self._repo.close()
284 self._repo.close()
285
285
286 # End of _basepeer interface.
286 # End of _basepeer interface.
287
287
288 # Begin of _basewirecommands interface.
288 # Begin of _basewirecommands interface.
289
289
290 def branchmap(self):
290 def branchmap(self):
291 return self._repo.branchmap()
291 return self._repo.branchmap()
292
292
293 def capabilities(self):
293 def capabilities(self):
294 return self._caps
294 return self._caps
295
295
296 def clonebundles(self):
296 def clonebundles(self):
297 return self._repo.tryread(b'clonebundles.manifest')
297 return self._repo.tryread(b'clonebundles.manifest')
298
298
299 def debugwireargs(self, one, two, three=None, four=None, five=None):
299 def debugwireargs(self, one, two, three=None, four=None, five=None):
300 """Used to test argument passing over the wire"""
300 """Used to test argument passing over the wire"""
301 return b"%s %s %s %s %s" % (
301 return b"%s %s %s %s %s" % (
302 one,
302 one,
303 two,
303 two,
304 pycompat.bytestr(three),
304 pycompat.bytestr(three),
305 pycompat.bytestr(four),
305 pycompat.bytestr(four),
306 pycompat.bytestr(five),
306 pycompat.bytestr(five),
307 )
307 )
308
308
309 def getbundle(
309 def getbundle(
310 self, source, heads=None, common=None, bundlecaps=None, **kwargs
310 self, source, heads=None, common=None, bundlecaps=None, **kwargs
311 ):
311 ):
312 chunks = exchange.getbundlechunks(
312 chunks = exchange.getbundlechunks(
313 self._repo,
313 self._repo,
314 source,
314 source,
315 heads=heads,
315 heads=heads,
316 common=common,
316 common=common,
317 bundlecaps=bundlecaps,
317 bundlecaps=bundlecaps,
318 **kwargs
318 **kwargs
319 )[1]
319 )[1]
320 cb = util.chunkbuffer(chunks)
320 cb = util.chunkbuffer(chunks)
321
321
322 if exchange.bundle2requested(bundlecaps):
322 if exchange.bundle2requested(bundlecaps):
323 # When requesting a bundle2, getbundle returns a stream to make the
323 # When requesting a bundle2, getbundle returns a stream to make the
324 # wire level function happier. We need to build a proper object
324 # wire level function happier. We need to build a proper object
325 # from it in local peer.
325 # from it in local peer.
326 return bundle2.getunbundler(self.ui, cb)
326 return bundle2.getunbundler(self.ui, cb)
327 else:
327 else:
328 return changegroup.getunbundler(b'01', cb, None)
328 return changegroup.getunbundler(b'01', cb, None)
329
329
330 def heads(self):
330 def heads(self):
331 return self._repo.heads()
331 return self._repo.heads()
332
332
333 def known(self, nodes):
333 def known(self, nodes):
334 return self._repo.known(nodes)
334 return self._repo.known(nodes)
335
335
336 def listkeys(self, namespace):
336 def listkeys(self, namespace):
337 return self._repo.listkeys(namespace)
337 return self._repo.listkeys(namespace)
338
338
339 def lookup(self, key):
339 def lookup(self, key):
340 return self._repo.lookup(key)
340 return self._repo.lookup(key)
341
341
342 def pushkey(self, namespace, key, old, new):
342 def pushkey(self, namespace, key, old, new):
343 return self._repo.pushkey(namespace, key, old, new)
343 return self._repo.pushkey(namespace, key, old, new)
344
344
345 def stream_out(self):
345 def stream_out(self):
346 raise error.Abort(_(b'cannot perform stream clone against local peer'))
346 raise error.Abort(_(b'cannot perform stream clone against local peer'))
347
347
348 def unbundle(self, bundle, heads, url):
348 def unbundle(self, bundle, heads, url):
349 """apply a bundle on a repo
349 """apply a bundle on a repo
350
350
351 This function handles the repo locking itself."""
351 This function handles the repo locking itself."""
352 try:
352 try:
353 try:
353 try:
354 bundle = exchange.readbundle(self.ui, bundle, None)
354 bundle = exchange.readbundle(self.ui, bundle, None)
355 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
355 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
356 if util.safehasattr(ret, b'getchunks'):
356 if util.safehasattr(ret, b'getchunks'):
357 # This is a bundle20 object, turn it into an unbundler.
357 # This is a bundle20 object, turn it into an unbundler.
358 # This little dance should be dropped eventually when the
358 # This little dance should be dropped eventually when the
359 # API is finally improved.
359 # API is finally improved.
360 stream = util.chunkbuffer(ret.getchunks())
360 stream = util.chunkbuffer(ret.getchunks())
361 ret = bundle2.getunbundler(self.ui, stream)
361 ret = bundle2.getunbundler(self.ui, stream)
362 return ret
362 return ret
363 except Exception as exc:
363 except Exception as exc:
364 # If the exception contains output salvaged from a bundle2
364 # If the exception contains output salvaged from a bundle2
365 # reply, we need to make sure it is printed before continuing
365 # reply, we need to make sure it is printed before continuing
366 # to fail. So we build a bundle2 with such output and consume
366 # to fail. So we build a bundle2 with such output and consume
367 # it directly.
367 # it directly.
368 #
368 #
369 # This is not very elegant but allows a "simple" solution for
369 # This is not very elegant but allows a "simple" solution for
370 # issue4594
370 # issue4594
371 output = getattr(exc, '_bundle2salvagedoutput', ())
371 output = getattr(exc, '_bundle2salvagedoutput', ())
372 if output:
372 if output:
373 bundler = bundle2.bundle20(self._repo.ui)
373 bundler = bundle2.bundle20(self._repo.ui)
374 for out in output:
374 for out in output:
375 bundler.addpart(out)
375 bundler.addpart(out)
376 stream = util.chunkbuffer(bundler.getchunks())
376 stream = util.chunkbuffer(bundler.getchunks())
377 b = bundle2.getunbundler(self.ui, stream)
377 b = bundle2.getunbundler(self.ui, stream)
378 bundle2.processbundle(self._repo, b)
378 bundle2.processbundle(self._repo, b)
379 raise
379 raise
380 except error.PushRaced as exc:
380 except error.PushRaced as exc:
381 raise error.ResponseError(
381 raise error.ResponseError(
382 _(b'push failed:'), stringutil.forcebytestr(exc)
382 _(b'push failed:'), stringutil.forcebytestr(exc)
383 )
383 )
384
384
385 # End of _basewirecommands interface.
385 # End of _basewirecommands interface.
386
386
387 # Begin of peer interface.
387 # Begin of peer interface.
388
388
389 def commandexecutor(self):
389 def commandexecutor(self):
390 return localcommandexecutor(self)
390 return localcommandexecutor(self)
391
391
392 # End of peer interface.
392 # End of peer interface.
393
393
394
394
395 @interfaceutil.implementer(repository.ipeerlegacycommands)
395 @interfaceutil.implementer(repository.ipeerlegacycommands)
396 class locallegacypeer(localpeer):
396 class locallegacypeer(localpeer):
397 '''peer extension which implements legacy methods too; used for tests with
397 '''peer extension which implements legacy methods too; used for tests with
398 restricted capabilities'''
398 restricted capabilities'''
399
399
400 def __init__(self, repo):
400 def __init__(self, repo):
401 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
401 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
402
402
403 # Begin of baselegacywirecommands interface.
403 # Begin of baselegacywirecommands interface.
404
404
405 def between(self, pairs):
405 def between(self, pairs):
406 return self._repo.between(pairs)
406 return self._repo.between(pairs)
407
407
408 def branches(self, nodes):
408 def branches(self, nodes):
409 return self._repo.branches(nodes)
409 return self._repo.branches(nodes)
410
410
411 def changegroup(self, nodes, source):
411 def changegroup(self, nodes, source):
412 outgoing = discovery.outgoing(
412 outgoing = discovery.outgoing(
413 self._repo, missingroots=nodes, missingheads=self._repo.heads()
413 self._repo, missingroots=nodes, missingheads=self._repo.heads()
414 )
414 )
415 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
415 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
416
416
417 def changegroupsubset(self, bases, heads, source):
417 def changegroupsubset(self, bases, heads, source):
418 outgoing = discovery.outgoing(
418 outgoing = discovery.outgoing(
419 self._repo, missingroots=bases, missingheads=heads
419 self._repo, missingroots=bases, missingheads=heads
420 )
420 )
421 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
421 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
422
422
423 # End of baselegacywirecommands interface.
423 # End of baselegacywirecommands interface.
424
424
425
425
426 # Increment the sub-version when the revlog v2 format changes to lock out old
426 # Increment the sub-version when the revlog v2 format changes to lock out old
427 # clients.
427 # clients.
428 REVLOGV2_REQUIREMENT = b'exp-revlogv2.1'
428 REVLOGV2_REQUIREMENT = b'exp-revlogv2.1'
429
429
430 # A repository with the sparserevlog feature will have delta chains that
430 # A repository with the sparserevlog feature will have delta chains that
431 # can spread over a larger span. Sparse reading cuts these large spans into
431 # can spread over a larger span. Sparse reading cuts these large spans into
432 # pieces, so that each piece isn't too big.
432 # pieces, so that each piece isn't too big.
433 # Without the sparserevlog capability, reading from the repository could use
433 # Without the sparserevlog capability, reading from the repository could use
434 # huge amounts of memory, because the whole span would be read at once,
434 # huge amounts of memory, because the whole span would be read at once,
435 # including all the intermediate revisions that aren't pertinent for the chain.
435 # including all the intermediate revisions that aren't pertinent for the chain.
436 # This is why once a repository has enabled sparse-read, it becomes required.
436 # This is why once a repository has enabled sparse-read, it becomes required.
437 SPARSEREVLOG_REQUIREMENT = b'sparserevlog'
437 SPARSEREVLOG_REQUIREMENT = b'sparserevlog'
438
438
439 # A repository with the sidedataflag requirement will allow to store extra
439 # A repository with the sidedataflag requirement will allow to store extra
440 # information for revision without altering their original hashes.
440 # information for revision without altering their original hashes.
441 SIDEDATA_REQUIREMENT = b'exp-sidedata-flag'
441 SIDEDATA_REQUIREMENT = b'exp-sidedata-flag'
442
442
443 # A repository with the the copies-sidedata-changeset requirement will store
443 # A repository with the the copies-sidedata-changeset requirement will store
444 # copies related information in changeset's sidedata.
444 # copies related information in changeset's sidedata.
445 COPIESSDC_REQUIREMENT = b'exp-copies-sidedata-changeset'
445 COPIESSDC_REQUIREMENT = b'exp-copies-sidedata-changeset'
446
446
447 # Functions receiving (ui, features) that extensions can register to impact
447 # Functions receiving (ui, features) that extensions can register to impact
448 # the ability to load repositories with custom requirements. Only
448 # the ability to load repositories with custom requirements. Only
449 # functions defined in loaded extensions are called.
449 # functions defined in loaded extensions are called.
450 #
450 #
451 # The function receives a set of requirement strings that the repository
451 # The function receives a set of requirement strings that the repository
452 # is capable of opening. Functions will typically add elements to the
452 # is capable of opening. Functions will typically add elements to the
453 # set to reflect that the extension knows how to handle that requirements.
453 # set to reflect that the extension knows how to handle that requirements.
454 featuresetupfuncs = set()
454 featuresetupfuncs = set()
455
455
456
456
457 def makelocalrepository(baseui, path, intents=None):
457 def makelocalrepository(baseui, path, intents=None):
458 """Create a local repository object.
458 """Create a local repository object.
459
459
460 Given arguments needed to construct a local repository, this function
460 Given arguments needed to construct a local repository, this function
461 performs various early repository loading functionality (such as
461 performs various early repository loading functionality (such as
462 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
462 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
463 the repository can be opened, derives a type suitable for representing
463 the repository can be opened, derives a type suitable for representing
464 that repository, and returns an instance of it.
464 that repository, and returns an instance of it.
465
465
466 The returned object conforms to the ``repository.completelocalrepository``
466 The returned object conforms to the ``repository.completelocalrepository``
467 interface.
467 interface.
468
468
469 The repository type is derived by calling a series of factory functions
469 The repository type is derived by calling a series of factory functions
470 for each aspect/interface of the final repository. These are defined by
470 for each aspect/interface of the final repository. These are defined by
471 ``REPO_INTERFACES``.
471 ``REPO_INTERFACES``.
472
472
473 Each factory function is called to produce a type implementing a specific
473 Each factory function is called to produce a type implementing a specific
474 interface. The cumulative list of returned types will be combined into a
474 interface. The cumulative list of returned types will be combined into a
475 new type and that type will be instantiated to represent the local
475 new type and that type will be instantiated to represent the local
476 repository.
476 repository.
477
477
478 The factory functions each receive various state that may be consulted
478 The factory functions each receive various state that may be consulted
479 as part of deriving a type.
479 as part of deriving a type.
480
480
481 Extensions should wrap these factory functions to customize repository type
481 Extensions should wrap these factory functions to customize repository type
482 creation. Note that an extension's wrapped function may be called even if
482 creation. Note that an extension's wrapped function may be called even if
483 that extension is not loaded for the repo being constructed. Extensions
483 that extension is not loaded for the repo being constructed. Extensions
484 should check if their ``__name__`` appears in the
484 should check if their ``__name__`` appears in the
485 ``extensionmodulenames`` set passed to the factory function and no-op if
485 ``extensionmodulenames`` set passed to the factory function and no-op if
486 not.
486 not.
487 """
487 """
488 ui = baseui.copy()
488 ui = baseui.copy()
489 # Prevent copying repo configuration.
489 # Prevent copying repo configuration.
490 ui.copy = baseui.copy
490 ui.copy = baseui.copy
491
491
492 # Working directory VFS rooted at repository root.
492 # Working directory VFS rooted at repository root.
493 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
493 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
494
494
495 # Main VFS for .hg/ directory.
495 # Main VFS for .hg/ directory.
496 hgpath = wdirvfs.join(b'.hg')
496 hgpath = wdirvfs.join(b'.hg')
497 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
497 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
498
498
499 # The .hg/ path should exist and should be a directory. All other
499 # The .hg/ path should exist and should be a directory. All other
500 # cases are errors.
500 # cases are errors.
501 if not hgvfs.isdir():
501 if not hgvfs.isdir():
502 try:
502 try:
503 hgvfs.stat()
503 hgvfs.stat()
504 except OSError as e:
504 except OSError as e:
505 if e.errno != errno.ENOENT:
505 if e.errno != errno.ENOENT:
506 raise
506 raise
507
507
508 raise error.RepoError(_(b'repository %s not found') % path)
508 raise error.RepoError(_(b'repository %s not found') % path)
509
509
510 # .hg/requires file contains a newline-delimited list of
510 # .hg/requires file contains a newline-delimited list of
511 # features/capabilities the opener (us) must have in order to use
511 # features/capabilities the opener (us) must have in order to use
512 # the repository. This file was introduced in Mercurial 0.9.2,
512 # the repository. This file was introduced in Mercurial 0.9.2,
513 # which means very old repositories may not have one. We assume
513 # which means very old repositories may not have one. We assume
514 # a missing file translates to no requirements.
514 # a missing file translates to no requirements.
515 try:
515 try:
516 requirements = set(hgvfs.read(b'requires').splitlines())
516 requirements = set(hgvfs.read(b'requires').splitlines())
517 except IOError as e:
517 except IOError as e:
518 if e.errno != errno.ENOENT:
518 if e.errno != errno.ENOENT:
519 raise
519 raise
520 requirements = set()
520 requirements = set()
521
521
522 # The .hg/hgrc file may load extensions or contain config options
522 # The .hg/hgrc file may load extensions or contain config options
523 # that influence repository construction. Attempt to load it and
523 # that influence repository construction. Attempt to load it and
524 # process any new extensions that it may have pulled in.
524 # process any new extensions that it may have pulled in.
525 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
525 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
526 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
526 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
527 extensions.loadall(ui)
527 extensions.loadall(ui)
528 extensions.populateui(ui)
528 extensions.populateui(ui)
529
529
530 # Set of module names of extensions loaded for this repository.
530 # Set of module names of extensions loaded for this repository.
531 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
531 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
532
532
533 supportedrequirements = gathersupportedrequirements(ui)
533 supportedrequirements = gathersupportedrequirements(ui)
534
534
535 # We first validate the requirements are known.
535 # We first validate the requirements are known.
536 ensurerequirementsrecognized(requirements, supportedrequirements)
536 ensurerequirementsrecognized(requirements, supportedrequirements)
537
537
538 # Then we validate that the known set is reasonable to use together.
538 # Then we validate that the known set is reasonable to use together.
539 ensurerequirementscompatible(ui, requirements)
539 ensurerequirementscompatible(ui, requirements)
540
540
541 # TODO there are unhandled edge cases related to opening repositories with
541 # TODO there are unhandled edge cases related to opening repositories with
542 # shared storage. If storage is shared, we should also test for requirements
542 # shared storage. If storage is shared, we should also test for requirements
543 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
543 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
544 # that repo, as that repo may load extensions needed to open it. This is a
544 # that repo, as that repo may load extensions needed to open it. This is a
545 # bit complicated because we don't want the other hgrc to overwrite settings
545 # bit complicated because we don't want the other hgrc to overwrite settings
546 # in this hgrc.
546 # in this hgrc.
547 #
547 #
548 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
548 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
549 # file when sharing repos. But if a requirement is added after the share is
549 # file when sharing repos. But if a requirement is added after the share is
550 # performed, thereby introducing a new requirement for the opener, we may
550 # performed, thereby introducing a new requirement for the opener, we may
551 # will not see that and could encounter a run-time error interacting with
551 # will not see that and could encounter a run-time error interacting with
552 # that shared store since it has an unknown-to-us requirement.
552 # that shared store since it has an unknown-to-us requirement.
553
553
554 # At this point, we know we should be capable of opening the repository.
554 # At this point, we know we should be capable of opening the repository.
555 # Now get on with doing that.
555 # Now get on with doing that.
556
556
557 features = set()
557 features = set()
558
558
559 # The "store" part of the repository holds versioned data. How it is
559 # The "store" part of the repository holds versioned data. How it is
560 # accessed is determined by various requirements. The ``shared`` or
560 # accessed is determined by various requirements. The ``shared`` or
561 # ``relshared`` requirements indicate the store lives in the path contained
561 # ``relshared`` requirements indicate the store lives in the path contained
562 # in the ``.hg/sharedpath`` file. This is an absolute path for
562 # in the ``.hg/sharedpath`` file. This is an absolute path for
563 # ``shared`` and relative to ``.hg/`` for ``relshared``.
563 # ``shared`` and relative to ``.hg/`` for ``relshared``.
564 if b'shared' in requirements or b'relshared' in requirements:
564 if b'shared' in requirements or b'relshared' in requirements:
565 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
565 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
566 if b'relshared' in requirements:
566 if b'relshared' in requirements:
567 sharedpath = hgvfs.join(sharedpath)
567 sharedpath = hgvfs.join(sharedpath)
568
568
569 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
569 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
570
570
571 if not sharedvfs.exists():
571 if not sharedvfs.exists():
572 raise error.RepoError(
572 raise error.RepoError(
573 _(b'.hg/sharedpath points to nonexistent directory %s')
573 _(b'.hg/sharedpath points to nonexistent directory %s')
574 % sharedvfs.base
574 % sharedvfs.base
575 )
575 )
576
576
577 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
577 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
578
578
579 storebasepath = sharedvfs.base
579 storebasepath = sharedvfs.base
580 cachepath = sharedvfs.join(b'cache')
580 cachepath = sharedvfs.join(b'cache')
581 else:
581 else:
582 storebasepath = hgvfs.base
582 storebasepath = hgvfs.base
583 cachepath = hgvfs.join(b'cache')
583 cachepath = hgvfs.join(b'cache')
584 wcachepath = hgvfs.join(b'wcache')
584 wcachepath = hgvfs.join(b'wcache')
585
585
586 # The store has changed over time and the exact layout is dictated by
586 # The store has changed over time and the exact layout is dictated by
587 # requirements. The store interface abstracts differences across all
587 # requirements. The store interface abstracts differences across all
588 # of them.
588 # of them.
589 store = makestore(
589 store = makestore(
590 requirements,
590 requirements,
591 storebasepath,
591 storebasepath,
592 lambda base: vfsmod.vfs(base, cacheaudited=True),
592 lambda base: vfsmod.vfs(base, cacheaudited=True),
593 )
593 )
594 hgvfs.createmode = store.createmode
594 hgvfs.createmode = store.createmode
595
595
596 storevfs = store.vfs
596 storevfs = store.vfs
597 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
597 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
598
598
599 # The cache vfs is used to manage cache files.
599 # The cache vfs is used to manage cache files.
600 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
600 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
601 cachevfs.createmode = store.createmode
601 cachevfs.createmode = store.createmode
602 # The cache vfs is used to manage cache files related to the working copy
602 # The cache vfs is used to manage cache files related to the working copy
603 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
603 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
604 wcachevfs.createmode = store.createmode
604 wcachevfs.createmode = store.createmode
605
605
606 # Now resolve the type for the repository object. We do this by repeatedly
606 # Now resolve the type for the repository object. We do this by repeatedly
607 # calling a factory function to produces types for specific aspects of the
607 # calling a factory function to produces types for specific aspects of the
608 # repo's operation. The aggregate returned types are used as base classes
608 # repo's operation. The aggregate returned types are used as base classes
609 # for a dynamically-derived type, which will represent our new repository.
609 # for a dynamically-derived type, which will represent our new repository.
610
610
611 bases = []
611 bases = []
612 extrastate = {}
612 extrastate = {}
613
613
614 for iface, fn in REPO_INTERFACES:
614 for iface, fn in REPO_INTERFACES:
615 # We pass all potentially useful state to give extensions tons of
615 # We pass all potentially useful state to give extensions tons of
616 # flexibility.
616 # flexibility.
617 typ = fn()(
617 typ = fn()(
618 ui=ui,
618 ui=ui,
619 intents=intents,
619 intents=intents,
620 requirements=requirements,
620 requirements=requirements,
621 features=features,
621 features=features,
622 wdirvfs=wdirvfs,
622 wdirvfs=wdirvfs,
623 hgvfs=hgvfs,
623 hgvfs=hgvfs,
624 store=store,
624 store=store,
625 storevfs=storevfs,
625 storevfs=storevfs,
626 storeoptions=storevfs.options,
626 storeoptions=storevfs.options,
627 cachevfs=cachevfs,
627 cachevfs=cachevfs,
628 wcachevfs=wcachevfs,
628 wcachevfs=wcachevfs,
629 extensionmodulenames=extensionmodulenames,
629 extensionmodulenames=extensionmodulenames,
630 extrastate=extrastate,
630 extrastate=extrastate,
631 baseclasses=bases,
631 baseclasses=bases,
632 )
632 )
633
633
634 if not isinstance(typ, type):
634 if not isinstance(typ, type):
635 raise error.ProgrammingError(
635 raise error.ProgrammingError(
636 b'unable to construct type for %s' % iface
636 b'unable to construct type for %s' % iface
637 )
637 )
638
638
639 bases.append(typ)
639 bases.append(typ)
640
640
641 # type() allows you to use characters in type names that wouldn't be
641 # type() allows you to use characters in type names that wouldn't be
642 # recognized as Python symbols in source code. We abuse that to add
642 # recognized as Python symbols in source code. We abuse that to add
643 # rich information about our constructed repo.
643 # rich information about our constructed repo.
644 name = pycompat.sysstr(
644 name = pycompat.sysstr(
645 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
645 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
646 )
646 )
647
647
648 cls = type(name, tuple(bases), {})
648 cls = type(name, tuple(bases), {})
649
649
650 return cls(
650 return cls(
651 baseui=baseui,
651 baseui=baseui,
652 ui=ui,
652 ui=ui,
653 origroot=path,
653 origroot=path,
654 wdirvfs=wdirvfs,
654 wdirvfs=wdirvfs,
655 hgvfs=hgvfs,
655 hgvfs=hgvfs,
656 requirements=requirements,
656 requirements=requirements,
657 supportedrequirements=supportedrequirements,
657 supportedrequirements=supportedrequirements,
658 sharedpath=storebasepath,
658 sharedpath=storebasepath,
659 store=store,
659 store=store,
660 cachevfs=cachevfs,
660 cachevfs=cachevfs,
661 wcachevfs=wcachevfs,
661 wcachevfs=wcachevfs,
662 features=features,
662 features=features,
663 intents=intents,
663 intents=intents,
664 )
664 )
665
665
666
666
667 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
667 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
668 """Load hgrc files/content into a ui instance.
668 """Load hgrc files/content into a ui instance.
669
669
670 This is called during repository opening to load any additional
670 This is called during repository opening to load any additional
671 config files or settings relevant to the current repository.
671 config files or settings relevant to the current repository.
672
672
673 Returns a bool indicating whether any additional configs were loaded.
673 Returns a bool indicating whether any additional configs were loaded.
674
674
675 Extensions should monkeypatch this function to modify how per-repo
675 Extensions should monkeypatch this function to modify how per-repo
676 configs are loaded. For example, an extension may wish to pull in
676 configs are loaded. For example, an extension may wish to pull in
677 configs from alternate files or sources.
677 configs from alternate files or sources.
678 """
678 """
679 try:
679 try:
680 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
680 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
681 return True
681 return True
682 except IOError:
682 except IOError:
683 return False
683 return False
684
684
685
685
686 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
686 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
687 """Perform additional actions after .hg/hgrc is loaded.
687 """Perform additional actions after .hg/hgrc is loaded.
688
688
689 This function is called during repository loading immediately after
689 This function is called during repository loading immediately after
690 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
690 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
691
691
692 The function can be used to validate configs, automatically add
692 The function can be used to validate configs, automatically add
693 options (including extensions) based on requirements, etc.
693 options (including extensions) based on requirements, etc.
694 """
694 """
695
695
696 # Map of requirements to list of extensions to load automatically when
696 # Map of requirements to list of extensions to load automatically when
697 # requirement is present.
697 # requirement is present.
698 autoextensions = {
698 autoextensions = {
699 b'largefiles': [b'largefiles'],
699 b'largefiles': [b'largefiles'],
700 b'lfs': [b'lfs'],
700 b'lfs': [b'lfs'],
701 }
701 }
702
702
703 for requirement, names in sorted(autoextensions.items()):
703 for requirement, names in sorted(autoextensions.items()):
704 if requirement not in requirements:
704 if requirement not in requirements:
705 continue
705 continue
706
706
707 for name in names:
707 for name in names:
708 if not ui.hasconfig(b'extensions', name):
708 if not ui.hasconfig(b'extensions', name):
709 ui.setconfig(b'extensions', name, b'', source=b'autoload')
709 ui.setconfig(b'extensions', name, b'', source=b'autoload')
710
710
711
711
712 def gathersupportedrequirements(ui):
712 def gathersupportedrequirements(ui):
713 """Determine the complete set of recognized requirements."""
713 """Determine the complete set of recognized requirements."""
714 # Start with all requirements supported by this file.
714 # Start with all requirements supported by this file.
715 supported = set(localrepository._basesupported)
715 supported = set(localrepository._basesupported)
716
716
717 # Execute ``featuresetupfuncs`` entries if they belong to an extension
717 # Execute ``featuresetupfuncs`` entries if they belong to an extension
718 # relevant to this ui instance.
718 # relevant to this ui instance.
719 modules = {m.__name__ for n, m in extensions.extensions(ui)}
719 modules = {m.__name__ for n, m in extensions.extensions(ui)}
720
720
721 for fn in featuresetupfuncs:
721 for fn in featuresetupfuncs:
722 if fn.__module__ in modules:
722 if fn.__module__ in modules:
723 fn(ui, supported)
723 fn(ui, supported)
724
724
725 # Add derived requirements from registered compression engines.
725 # Add derived requirements from registered compression engines.
726 for name in util.compengines:
726 for name in util.compengines:
727 engine = util.compengines[name]
727 engine = util.compengines[name]
728 if engine.available() and engine.revlogheader():
728 if engine.available() and engine.revlogheader():
729 supported.add(b'exp-compression-%s' % name)
729 supported.add(b'exp-compression-%s' % name)
730 if engine.name() == b'zstd':
730 if engine.name() == b'zstd':
731 supported.add(b'revlog-compression-zstd')
731 supported.add(b'revlog-compression-zstd')
732
732
733 return supported
733 return supported
734
734
735
735
736 def ensurerequirementsrecognized(requirements, supported):
736 def ensurerequirementsrecognized(requirements, supported):
737 """Validate that a set of local requirements is recognized.
737 """Validate that a set of local requirements is recognized.
738
738
739 Receives a set of requirements. Raises an ``error.RepoError`` if there
739 Receives a set of requirements. Raises an ``error.RepoError`` if there
740 exists any requirement in that set that currently loaded code doesn't
740 exists any requirement in that set that currently loaded code doesn't
741 recognize.
741 recognize.
742
742
743 Returns a set of supported requirements.
743 Returns a set of supported requirements.
744 """
744 """
745 missing = set()
745 missing = set()
746
746
747 for requirement in requirements:
747 for requirement in requirements:
748 if requirement in supported:
748 if requirement in supported:
749 continue
749 continue
750
750
751 if not requirement or not requirement[0:1].isalnum():
751 if not requirement or not requirement[0:1].isalnum():
752 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
752 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
753
753
754 missing.add(requirement)
754 missing.add(requirement)
755
755
756 if missing:
756 if missing:
757 raise error.RequirementError(
757 raise error.RequirementError(
758 _(b'repository requires features unknown to this Mercurial: %s')
758 _(b'repository requires features unknown to this Mercurial: %s')
759 % b' '.join(sorted(missing)),
759 % b' '.join(sorted(missing)),
760 hint=_(
760 hint=_(
761 b'see https://mercurial-scm.org/wiki/MissingRequirement '
761 b'see https://mercurial-scm.org/wiki/MissingRequirement '
762 b'for more information'
762 b'for more information'
763 ),
763 ),
764 )
764 )
765
765
766
766
767 def ensurerequirementscompatible(ui, requirements):
767 def ensurerequirementscompatible(ui, requirements):
768 """Validates that a set of recognized requirements is mutually compatible.
768 """Validates that a set of recognized requirements is mutually compatible.
769
769
770 Some requirements may not be compatible with others or require
770 Some requirements may not be compatible with others or require
771 config options that aren't enabled. This function is called during
771 config options that aren't enabled. This function is called during
772 repository opening to ensure that the set of requirements needed
772 repository opening to ensure that the set of requirements needed
773 to open a repository is sane and compatible with config options.
773 to open a repository is sane and compatible with config options.
774
774
775 Extensions can monkeypatch this function to perform additional
775 Extensions can monkeypatch this function to perform additional
776 checking.
776 checking.
777
777
778 ``error.RepoError`` should be raised on failure.
778 ``error.RepoError`` should be raised on failure.
779 """
779 """
780 if b'exp-sparse' in requirements and not sparse.enabled:
780 if b'exp-sparse' in requirements and not sparse.enabled:
781 raise error.RepoError(
781 raise error.RepoError(
782 _(
782 _(
783 b'repository is using sparse feature but '
783 b'repository is using sparse feature but '
784 b'sparse is not enabled; enable the '
784 b'sparse is not enabled; enable the '
785 b'"sparse" extensions to access'
785 b'"sparse" extensions to access'
786 )
786 )
787 )
787 )
788
788
789
789
790 def makestore(requirements, path, vfstype):
790 def makestore(requirements, path, vfstype):
791 """Construct a storage object for a repository."""
791 """Construct a storage object for a repository."""
792 if b'store' in requirements:
792 if b'store' in requirements:
793 if b'fncache' in requirements:
793 if b'fncache' in requirements:
794 return storemod.fncachestore(
794 return storemod.fncachestore(
795 path, vfstype, b'dotencode' in requirements
795 path, vfstype, b'dotencode' in requirements
796 )
796 )
797
797
798 return storemod.encodedstore(path, vfstype)
798 return storemod.encodedstore(path, vfstype)
799
799
800 return storemod.basicstore(path, vfstype)
800 return storemod.basicstore(path, vfstype)
801
801
802
802
803 def resolvestorevfsoptions(ui, requirements, features):
803 def resolvestorevfsoptions(ui, requirements, features):
804 """Resolve the options to pass to the store vfs opener.
804 """Resolve the options to pass to the store vfs opener.
805
805
806 The returned dict is used to influence behavior of the storage layer.
806 The returned dict is used to influence behavior of the storage layer.
807 """
807 """
808 options = {}
808 options = {}
809
809
810 if b'treemanifest' in requirements:
810 if b'treemanifest' in requirements:
811 options[b'treemanifest'] = True
811 options[b'treemanifest'] = True
812
812
813 # experimental config: format.manifestcachesize
813 # experimental config: format.manifestcachesize
814 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
814 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
815 if manifestcachesize is not None:
815 if manifestcachesize is not None:
816 options[b'manifestcachesize'] = manifestcachesize
816 options[b'manifestcachesize'] = manifestcachesize
817
817
818 # In the absence of another requirement superseding a revlog-related
818 # In the absence of another requirement superseding a revlog-related
819 # requirement, we have to assume the repo is using revlog version 0.
819 # requirement, we have to assume the repo is using revlog version 0.
820 # This revlog format is super old and we don't bother trying to parse
820 # This revlog format is super old and we don't bother trying to parse
821 # opener options for it because those options wouldn't do anything
821 # opener options for it because those options wouldn't do anything
822 # meaningful on such old repos.
822 # meaningful on such old repos.
823 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
823 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
824 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
824 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
825 else: # explicitly mark repo as using revlogv0
825 else: # explicitly mark repo as using revlogv0
826 options[b'revlogv0'] = True
826 options[b'revlogv0'] = True
827
827
828 if COPIESSDC_REQUIREMENT in requirements:
828 if COPIESSDC_REQUIREMENT in requirements:
829 options[b'copies-storage'] = b'changeset-sidedata'
829 options[b'copies-storage'] = b'changeset-sidedata'
830 else:
830 else:
831 writecopiesto = ui.config(b'experimental', b'copies.write-to')
831 writecopiesto = ui.config(b'experimental', b'copies.write-to')
832 copiesextramode = (b'changeset-only', b'compatibility')
832 copiesextramode = (b'changeset-only', b'compatibility')
833 if writecopiesto in copiesextramode:
833 if writecopiesto in copiesextramode:
834 options[b'copies-storage'] = b'extra'
834 options[b'copies-storage'] = b'extra'
835
835
836 return options
836 return options
837
837
838
838
839 def resolverevlogstorevfsoptions(ui, requirements, features):
839 def resolverevlogstorevfsoptions(ui, requirements, features):
840 """Resolve opener options specific to revlogs."""
840 """Resolve opener options specific to revlogs."""
841
841
842 options = {}
842 options = {}
843 options[b'flagprocessors'] = {}
843 options[b'flagprocessors'] = {}
844
844
845 if b'revlogv1' in requirements:
845 if b'revlogv1' in requirements:
846 options[b'revlogv1'] = True
846 options[b'revlogv1'] = True
847 if REVLOGV2_REQUIREMENT in requirements:
847 if REVLOGV2_REQUIREMENT in requirements:
848 options[b'revlogv2'] = True
848 options[b'revlogv2'] = True
849
849
850 if b'generaldelta' in requirements:
850 if b'generaldelta' in requirements:
851 options[b'generaldelta'] = True
851 options[b'generaldelta'] = True
852
852
853 # experimental config: format.chunkcachesize
853 # experimental config: format.chunkcachesize
854 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
854 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
855 if chunkcachesize is not None:
855 if chunkcachesize is not None:
856 options[b'chunkcachesize'] = chunkcachesize
856 options[b'chunkcachesize'] = chunkcachesize
857
857
858 deltabothparents = ui.configbool(
858 deltabothparents = ui.configbool(
859 b'storage', b'revlog.optimize-delta-parent-choice'
859 b'storage', b'revlog.optimize-delta-parent-choice'
860 )
860 )
861 options[b'deltabothparents'] = deltabothparents
861 options[b'deltabothparents'] = deltabothparents
862
862
863 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
863 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
864 lazydeltabase = False
864 lazydeltabase = False
865 if lazydelta:
865 if lazydelta:
866 lazydeltabase = ui.configbool(
866 lazydeltabase = ui.configbool(
867 b'storage', b'revlog.reuse-external-delta-parent'
867 b'storage', b'revlog.reuse-external-delta-parent'
868 )
868 )
869 if lazydeltabase is None:
869 if lazydeltabase is None:
870 lazydeltabase = not scmutil.gddeltaconfig(ui)
870 lazydeltabase = not scmutil.gddeltaconfig(ui)
871 options[b'lazydelta'] = lazydelta
871 options[b'lazydelta'] = lazydelta
872 options[b'lazydeltabase'] = lazydeltabase
872 options[b'lazydeltabase'] = lazydeltabase
873
873
874 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
874 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
875 if 0 <= chainspan:
875 if 0 <= chainspan:
876 options[b'maxdeltachainspan'] = chainspan
876 options[b'maxdeltachainspan'] = chainspan
877
877
878 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
878 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
879 if mmapindexthreshold is not None:
879 if mmapindexthreshold is not None:
880 options[b'mmapindexthreshold'] = mmapindexthreshold
880 options[b'mmapindexthreshold'] = mmapindexthreshold
881
881
882 withsparseread = ui.configbool(b'experimental', b'sparse-read')
882 withsparseread = ui.configbool(b'experimental', b'sparse-read')
883 srdensitythres = float(
883 srdensitythres = float(
884 ui.config(b'experimental', b'sparse-read.density-threshold')
884 ui.config(b'experimental', b'sparse-read.density-threshold')
885 )
885 )
886 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
886 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
887 options[b'with-sparse-read'] = withsparseread
887 options[b'with-sparse-read'] = withsparseread
888 options[b'sparse-read-density-threshold'] = srdensitythres
888 options[b'sparse-read-density-threshold'] = srdensitythres
889 options[b'sparse-read-min-gap-size'] = srmingapsize
889 options[b'sparse-read-min-gap-size'] = srmingapsize
890
890
891 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
891 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
892 options[b'sparse-revlog'] = sparserevlog
892 options[b'sparse-revlog'] = sparserevlog
893 if sparserevlog:
893 if sparserevlog:
894 options[b'generaldelta'] = True
894 options[b'generaldelta'] = True
895
895
896 sidedata = SIDEDATA_REQUIREMENT in requirements
896 sidedata = SIDEDATA_REQUIREMENT in requirements
897 options[b'side-data'] = sidedata
897 options[b'side-data'] = sidedata
898
898
899 maxchainlen = None
899 maxchainlen = None
900 if sparserevlog:
900 if sparserevlog:
901 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
901 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
902 # experimental config: format.maxchainlen
902 # experimental config: format.maxchainlen
903 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
903 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
904 if maxchainlen is not None:
904 if maxchainlen is not None:
905 options[b'maxchainlen'] = maxchainlen
905 options[b'maxchainlen'] = maxchainlen
906
906
907 for r in requirements:
907 for r in requirements:
908 # we allow multiple compression engine requirement to co-exist because
908 # we allow multiple compression engine requirement to co-exist because
909 # strickly speaking, revlog seems to support mixed compression style.
909 # strickly speaking, revlog seems to support mixed compression style.
910 #
910 #
911 # The compression used for new entries will be "the last one"
911 # The compression used for new entries will be "the last one"
912 prefix = r.startswith
912 prefix = r.startswith
913 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
913 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
914 options[b'compengine'] = r.split(b'-', 2)[2]
914 options[b'compengine'] = r.split(b'-', 2)[2]
915
915
916 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
916 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
917 if options[b'zlib.level'] is not None:
917 if options[b'zlib.level'] is not None:
918 if not (0 <= options[b'zlib.level'] <= 9):
918 if not (0 <= options[b'zlib.level'] <= 9):
919 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
919 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
920 raise error.Abort(msg % options[b'zlib.level'])
920 raise error.Abort(msg % options[b'zlib.level'])
921 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
921 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
922 if options[b'zstd.level'] is not None:
922 if options[b'zstd.level'] is not None:
923 if not (0 <= options[b'zstd.level'] <= 22):
923 if not (0 <= options[b'zstd.level'] <= 22):
924 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
924 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
925 raise error.Abort(msg % options[b'zstd.level'])
925 raise error.Abort(msg % options[b'zstd.level'])
926
926
927 if repository.NARROW_REQUIREMENT in requirements:
927 if repository.NARROW_REQUIREMENT in requirements:
928 options[b'enableellipsis'] = True
928 options[b'enableellipsis'] = True
929
929
930 if ui.configbool(b'experimental', b'rust.index'):
930 if ui.configbool(b'experimental', b'rust.index'):
931 options[b'rust.index'] = True
931 options[b'rust.index'] = True
932
932
933 return options
933 return options
934
934
935
935
936 def makemain(**kwargs):
936 def makemain(**kwargs):
937 """Produce a type conforming to ``ilocalrepositorymain``."""
937 """Produce a type conforming to ``ilocalrepositorymain``."""
938 return localrepository
938 return localrepository
939
939
940
940
941 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
941 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
942 class revlogfilestorage(object):
942 class revlogfilestorage(object):
943 """File storage when using revlogs."""
943 """File storage when using revlogs."""
944
944
945 def file(self, path):
945 def file(self, path):
946 if path[0] == b'/':
946 if path[0] == b'/':
947 path = path[1:]
947 path = path[1:]
948
948
949 return filelog.filelog(self.svfs, path)
949 return filelog.filelog(self.svfs, path)
950
950
951
951
952 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
952 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
953 class revlognarrowfilestorage(object):
953 class revlognarrowfilestorage(object):
954 """File storage when using revlogs and narrow files."""
954 """File storage when using revlogs and narrow files."""
955
955
956 def file(self, path):
956 def file(self, path):
957 if path[0] == b'/':
957 if path[0] == b'/':
958 path = path[1:]
958 path = path[1:]
959
959
960 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
960 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
961
961
962
962
963 def makefilestorage(requirements, features, **kwargs):
963 def makefilestorage(requirements, features, **kwargs):
964 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
964 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
965 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
965 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
966 features.add(repository.REPO_FEATURE_STREAM_CLONE)
966 features.add(repository.REPO_FEATURE_STREAM_CLONE)
967
967
968 if repository.NARROW_REQUIREMENT in requirements:
968 if repository.NARROW_REQUIREMENT in requirements:
969 return revlognarrowfilestorage
969 return revlognarrowfilestorage
970 else:
970 else:
971 return revlogfilestorage
971 return revlogfilestorage
972
972
973
973
974 # List of repository interfaces and factory functions for them. Each
974 # List of repository interfaces and factory functions for them. Each
975 # will be called in order during ``makelocalrepository()`` to iteratively
975 # will be called in order during ``makelocalrepository()`` to iteratively
976 # derive the final type for a local repository instance. We capture the
976 # derive the final type for a local repository instance. We capture the
977 # function as a lambda so we don't hold a reference and the module-level
977 # function as a lambda so we don't hold a reference and the module-level
978 # functions can be wrapped.
978 # functions can be wrapped.
979 REPO_INTERFACES = [
979 REPO_INTERFACES = [
980 (repository.ilocalrepositorymain, lambda: makemain),
980 (repository.ilocalrepositorymain, lambda: makemain),
981 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
981 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
982 ]
982 ]
983
983
984
984
985 @interfaceutil.implementer(repository.ilocalrepositorymain)
985 @interfaceutil.implementer(repository.ilocalrepositorymain)
986 class localrepository(object):
986 class localrepository(object):
987 """Main class for representing local repositories.
987 """Main class for representing local repositories.
988
988
989 All local repositories are instances of this class.
989 All local repositories are instances of this class.
990
990
991 Constructed on its own, instances of this class are not usable as
991 Constructed on its own, instances of this class are not usable as
992 repository objects. To obtain a usable repository object, call
992 repository objects. To obtain a usable repository object, call
993 ``hg.repository()``, ``localrepo.instance()``, or
993 ``hg.repository()``, ``localrepo.instance()``, or
994 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
994 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
995 ``instance()`` adds support for creating new repositories.
995 ``instance()`` adds support for creating new repositories.
996 ``hg.repository()`` adds more extension integration, including calling
996 ``hg.repository()`` adds more extension integration, including calling
997 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
997 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
998 used.
998 used.
999 """
999 """
1000
1000
1001 # obsolete experimental requirements:
1001 # obsolete experimental requirements:
1002 # - manifestv2: An experimental new manifest format that allowed
1002 # - manifestv2: An experimental new manifest format that allowed
1003 # for stem compression of long paths. Experiment ended up not
1003 # for stem compression of long paths. Experiment ended up not
1004 # being successful (repository sizes went up due to worse delta
1004 # being successful (repository sizes went up due to worse delta
1005 # chains), and the code was deleted in 4.6.
1005 # chains), and the code was deleted in 4.6.
1006 supportedformats = {
1006 supportedformats = {
1007 b'revlogv1',
1007 b'revlogv1',
1008 b'generaldelta',
1008 b'generaldelta',
1009 b'treemanifest',
1009 b'treemanifest',
1010 COPIESSDC_REQUIREMENT,
1010 COPIESSDC_REQUIREMENT,
1011 REVLOGV2_REQUIREMENT,
1011 REVLOGV2_REQUIREMENT,
1012 SIDEDATA_REQUIREMENT,
1012 SIDEDATA_REQUIREMENT,
1013 SPARSEREVLOG_REQUIREMENT,
1013 SPARSEREVLOG_REQUIREMENT,
1014 bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT,
1014 bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT,
1015 }
1015 }
1016 _basesupported = supportedformats | {
1016 _basesupported = supportedformats | {
1017 b'store',
1017 b'store',
1018 b'fncache',
1018 b'fncache',
1019 b'shared',
1019 b'shared',
1020 b'relshared',
1020 b'relshared',
1021 b'dotencode',
1021 b'dotencode',
1022 b'exp-sparse',
1022 b'exp-sparse',
1023 b'internal-phase',
1023 b'internal-phase',
1024 }
1024 }
1025
1025
1026 # list of prefix for file which can be written without 'wlock'
1026 # list of prefix for file which can be written without 'wlock'
1027 # Extensions should extend this list when needed
1027 # Extensions should extend this list when needed
1028 _wlockfreeprefix = {
1028 _wlockfreeprefix = {
1029 # We migh consider requiring 'wlock' for the next
1029 # We migh consider requiring 'wlock' for the next
1030 # two, but pretty much all the existing code assume
1030 # two, but pretty much all the existing code assume
1031 # wlock is not needed so we keep them excluded for
1031 # wlock is not needed so we keep them excluded for
1032 # now.
1032 # now.
1033 b'hgrc',
1033 b'hgrc',
1034 b'requires',
1034 b'requires',
1035 # XXX cache is a complicatged business someone
1035 # XXX cache is a complicatged business someone
1036 # should investigate this in depth at some point
1036 # should investigate this in depth at some point
1037 b'cache/',
1037 b'cache/',
1038 # XXX shouldn't be dirstate covered by the wlock?
1038 # XXX shouldn't be dirstate covered by the wlock?
1039 b'dirstate',
1039 b'dirstate',
1040 # XXX bisect was still a bit too messy at the time
1040 # XXX bisect was still a bit too messy at the time
1041 # this changeset was introduced. Someone should fix
1041 # this changeset was introduced. Someone should fix
1042 # the remainig bit and drop this line
1042 # the remainig bit and drop this line
1043 b'bisect.state',
1043 b'bisect.state',
1044 }
1044 }
1045
1045
1046 def __init__(
1046 def __init__(
1047 self,
1047 self,
1048 baseui,
1048 baseui,
1049 ui,
1049 ui,
1050 origroot,
1050 origroot,
1051 wdirvfs,
1051 wdirvfs,
1052 hgvfs,
1052 hgvfs,
1053 requirements,
1053 requirements,
1054 supportedrequirements,
1054 supportedrequirements,
1055 sharedpath,
1055 sharedpath,
1056 store,
1056 store,
1057 cachevfs,
1057 cachevfs,
1058 wcachevfs,
1058 wcachevfs,
1059 features,
1059 features,
1060 intents=None,
1060 intents=None,
1061 ):
1061 ):
1062 """Create a new local repository instance.
1062 """Create a new local repository instance.
1063
1063
1064 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1064 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1065 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1065 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1066 object.
1066 object.
1067
1067
1068 Arguments:
1068 Arguments:
1069
1069
1070 baseui
1070 baseui
1071 ``ui.ui`` instance that ``ui`` argument was based off of.
1071 ``ui.ui`` instance that ``ui`` argument was based off of.
1072
1072
1073 ui
1073 ui
1074 ``ui.ui`` instance for use by the repository.
1074 ``ui.ui`` instance for use by the repository.
1075
1075
1076 origroot
1076 origroot
1077 ``bytes`` path to working directory root of this repository.
1077 ``bytes`` path to working directory root of this repository.
1078
1078
1079 wdirvfs
1079 wdirvfs
1080 ``vfs.vfs`` rooted at the working directory.
1080 ``vfs.vfs`` rooted at the working directory.
1081
1081
1082 hgvfs
1082 hgvfs
1083 ``vfs.vfs`` rooted at .hg/
1083 ``vfs.vfs`` rooted at .hg/
1084
1084
1085 requirements
1085 requirements
1086 ``set`` of bytestrings representing repository opening requirements.
1086 ``set`` of bytestrings representing repository opening requirements.
1087
1087
1088 supportedrequirements
1088 supportedrequirements
1089 ``set`` of bytestrings representing repository requirements that we
1089 ``set`` of bytestrings representing repository requirements that we
1090 know how to open. May be a supetset of ``requirements``.
1090 know how to open. May be a supetset of ``requirements``.
1091
1091
1092 sharedpath
1092 sharedpath
1093 ``bytes`` Defining path to storage base directory. Points to a
1093 ``bytes`` Defining path to storage base directory. Points to a
1094 ``.hg/`` directory somewhere.
1094 ``.hg/`` directory somewhere.
1095
1095
1096 store
1096 store
1097 ``store.basicstore`` (or derived) instance providing access to
1097 ``store.basicstore`` (or derived) instance providing access to
1098 versioned storage.
1098 versioned storage.
1099
1099
1100 cachevfs
1100 cachevfs
1101 ``vfs.vfs`` used for cache files.
1101 ``vfs.vfs`` used for cache files.
1102
1102
1103 wcachevfs
1103 wcachevfs
1104 ``vfs.vfs`` used for cache files related to the working copy.
1104 ``vfs.vfs`` used for cache files related to the working copy.
1105
1105
1106 features
1106 features
1107 ``set`` of bytestrings defining features/capabilities of this
1107 ``set`` of bytestrings defining features/capabilities of this
1108 instance.
1108 instance.
1109
1109
1110 intents
1110 intents
1111 ``set`` of system strings indicating what this repo will be used
1111 ``set`` of system strings indicating what this repo will be used
1112 for.
1112 for.
1113 """
1113 """
1114 self.baseui = baseui
1114 self.baseui = baseui
1115 self.ui = ui
1115 self.ui = ui
1116 self.origroot = origroot
1116 self.origroot = origroot
1117 # vfs rooted at working directory.
1117 # vfs rooted at working directory.
1118 self.wvfs = wdirvfs
1118 self.wvfs = wdirvfs
1119 self.root = wdirvfs.base
1119 self.root = wdirvfs.base
1120 # vfs rooted at .hg/. Used to access most non-store paths.
1120 # vfs rooted at .hg/. Used to access most non-store paths.
1121 self.vfs = hgvfs
1121 self.vfs = hgvfs
1122 self.path = hgvfs.base
1122 self.path = hgvfs.base
1123 self.requirements = requirements
1123 self.requirements = requirements
1124 self.supported = supportedrequirements
1124 self.supported = supportedrequirements
1125 self.sharedpath = sharedpath
1125 self.sharedpath = sharedpath
1126 self.store = store
1126 self.store = store
1127 self.cachevfs = cachevfs
1127 self.cachevfs = cachevfs
1128 self.wcachevfs = wcachevfs
1128 self.wcachevfs = wcachevfs
1129 self.features = features
1129 self.features = features
1130
1130
1131 self.filtername = None
1131 self.filtername = None
1132
1132
1133 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1133 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1134 b'devel', b'check-locks'
1134 b'devel', b'check-locks'
1135 ):
1135 ):
1136 self.vfs.audit = self._getvfsward(self.vfs.audit)
1136 self.vfs.audit = self._getvfsward(self.vfs.audit)
1137 # A list of callback to shape the phase if no data were found.
1137 # A list of callback to shape the phase if no data were found.
1138 # Callback are in the form: func(repo, roots) --> processed root.
1138 # Callback are in the form: func(repo, roots) --> processed root.
1139 # This list it to be filled by extension during repo setup
1139 # This list it to be filled by extension during repo setup
1140 self._phasedefaults = []
1140 self._phasedefaults = []
1141
1141
1142 color.setup(self.ui)
1142 color.setup(self.ui)
1143
1143
1144 self.spath = self.store.path
1144 self.spath = self.store.path
1145 self.svfs = self.store.vfs
1145 self.svfs = self.store.vfs
1146 self.sjoin = self.store.join
1146 self.sjoin = self.store.join
1147 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1147 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1148 b'devel', b'check-locks'
1148 b'devel', b'check-locks'
1149 ):
1149 ):
1150 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1150 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1151 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1151 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1152 else: # standard vfs
1152 else: # standard vfs
1153 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1153 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1154
1154
1155 self._dirstatevalidatewarned = False
1155 self._dirstatevalidatewarned = False
1156
1156
1157 self._branchcaches = branchmap.BranchMapCache()
1157 self._branchcaches = branchmap.BranchMapCache()
1158 self._revbranchcache = None
1158 self._revbranchcache = None
1159 self._filterpats = {}
1159 self._filterpats = {}
1160 self._datafilters = {}
1160 self._datafilters = {}
1161 self._transref = self._lockref = self._wlockref = None
1161 self._transref = self._lockref = self._wlockref = None
1162
1162
1163 # A cache for various files under .hg/ that tracks file changes,
1163 # A cache for various files under .hg/ that tracks file changes,
1164 # (used by the filecache decorator)
1164 # (used by the filecache decorator)
1165 #
1165 #
1166 # Maps a property name to its util.filecacheentry
1166 # Maps a property name to its util.filecacheentry
1167 self._filecache = {}
1167 self._filecache = {}
1168
1168
1169 # hold sets of revision to be filtered
1169 # hold sets of revision to be filtered
1170 # should be cleared when something might have changed the filter value:
1170 # should be cleared when something might have changed the filter value:
1171 # - new changesets,
1171 # - new changesets,
1172 # - phase change,
1172 # - phase change,
1173 # - new obsolescence marker,
1173 # - new obsolescence marker,
1174 # - working directory parent change,
1174 # - working directory parent change,
1175 # - bookmark changes
1175 # - bookmark changes
1176 self.filteredrevcache = {}
1176 self.filteredrevcache = {}
1177
1177
1178 # post-dirstate-status hooks
1178 # post-dirstate-status hooks
1179 self._postdsstatus = []
1179 self._postdsstatus = []
1180
1180
1181 # generic mapping between names and nodes
1181 # generic mapping between names and nodes
1182 self.names = namespaces.namespaces()
1182 self.names = namespaces.namespaces()
1183
1183
1184 # Key to signature value.
1184 # Key to signature value.
1185 self._sparsesignaturecache = {}
1185 self._sparsesignaturecache = {}
1186 # Signature to cached matcher instance.
1186 # Signature to cached matcher instance.
1187 self._sparsematchercache = {}
1187 self._sparsematchercache = {}
1188
1188
1189 self._extrafilterid = repoview.extrafilter(ui)
1189 self._extrafilterid = repoview.extrafilter(ui)
1190
1190
1191 self.filecopiesmode = None
1191 self.filecopiesmode = None
1192 if COPIESSDC_REQUIREMENT in self.requirements:
1192 if COPIESSDC_REQUIREMENT in self.requirements:
1193 self.filecopiesmode = b'changeset-sidedata'
1193 self.filecopiesmode = b'changeset-sidedata'
1194
1194
1195 def _getvfsward(self, origfunc):
1195 def _getvfsward(self, origfunc):
1196 """build a ward for self.vfs"""
1196 """build a ward for self.vfs"""
1197 rref = weakref.ref(self)
1197 rref = weakref.ref(self)
1198
1198
1199 def checkvfs(path, mode=None):
1199 def checkvfs(path, mode=None):
1200 ret = origfunc(path, mode=mode)
1200 ret = origfunc(path, mode=mode)
1201 repo = rref()
1201 repo = rref()
1202 if (
1202 if (
1203 repo is None
1203 repo is None
1204 or not util.safehasattr(repo, b'_wlockref')
1204 or not util.safehasattr(repo, b'_wlockref')
1205 or not util.safehasattr(repo, b'_lockref')
1205 or not util.safehasattr(repo, b'_lockref')
1206 ):
1206 ):
1207 return
1207 return
1208 if mode in (None, b'r', b'rb'):
1208 if mode in (None, b'r', b'rb'):
1209 return
1209 return
1210 if path.startswith(repo.path):
1210 if path.startswith(repo.path):
1211 # truncate name relative to the repository (.hg)
1211 # truncate name relative to the repository (.hg)
1212 path = path[len(repo.path) + 1 :]
1212 path = path[len(repo.path) + 1 :]
1213 if path.startswith(b'cache/'):
1213 if path.startswith(b'cache/'):
1214 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1214 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1215 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1215 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1216 if path.startswith(b'journal.') or path.startswith(b'undo.'):
1216 if path.startswith(b'journal.') or path.startswith(b'undo.'):
1217 # journal is covered by 'lock'
1217 # journal is covered by 'lock'
1218 if repo._currentlock(repo._lockref) is None:
1218 if repo._currentlock(repo._lockref) is None:
1219 repo.ui.develwarn(
1219 repo.ui.develwarn(
1220 b'write with no lock: "%s"' % path,
1220 b'write with no lock: "%s"' % path,
1221 stacklevel=3,
1221 stacklevel=3,
1222 config=b'check-locks',
1222 config=b'check-locks',
1223 )
1223 )
1224 elif repo._currentlock(repo._wlockref) is None:
1224 elif repo._currentlock(repo._wlockref) is None:
1225 # rest of vfs files are covered by 'wlock'
1225 # rest of vfs files are covered by 'wlock'
1226 #
1226 #
1227 # exclude special files
1227 # exclude special files
1228 for prefix in self._wlockfreeprefix:
1228 for prefix in self._wlockfreeprefix:
1229 if path.startswith(prefix):
1229 if path.startswith(prefix):
1230 return
1230 return
1231 repo.ui.develwarn(
1231 repo.ui.develwarn(
1232 b'write with no wlock: "%s"' % path,
1232 b'write with no wlock: "%s"' % path,
1233 stacklevel=3,
1233 stacklevel=3,
1234 config=b'check-locks',
1234 config=b'check-locks',
1235 )
1235 )
1236 return ret
1236 return ret
1237
1237
1238 return checkvfs
1238 return checkvfs
1239
1239
1240 def _getsvfsward(self, origfunc):
1240 def _getsvfsward(self, origfunc):
1241 """build a ward for self.svfs"""
1241 """build a ward for self.svfs"""
1242 rref = weakref.ref(self)
1242 rref = weakref.ref(self)
1243
1243
1244 def checksvfs(path, mode=None):
1244 def checksvfs(path, mode=None):
1245 ret = origfunc(path, mode=mode)
1245 ret = origfunc(path, mode=mode)
1246 repo = rref()
1246 repo = rref()
1247 if repo is None or not util.safehasattr(repo, b'_lockref'):
1247 if repo is None or not util.safehasattr(repo, b'_lockref'):
1248 return
1248 return
1249 if mode in (None, b'r', b'rb'):
1249 if mode in (None, b'r', b'rb'):
1250 return
1250 return
1251 if path.startswith(repo.sharedpath):
1251 if path.startswith(repo.sharedpath):
1252 # truncate name relative to the repository (.hg)
1252 # truncate name relative to the repository (.hg)
1253 path = path[len(repo.sharedpath) + 1 :]
1253 path = path[len(repo.sharedpath) + 1 :]
1254 if repo._currentlock(repo._lockref) is None:
1254 if repo._currentlock(repo._lockref) is None:
1255 repo.ui.develwarn(
1255 repo.ui.develwarn(
1256 b'write with no lock: "%s"' % path, stacklevel=4
1256 b'write with no lock: "%s"' % path, stacklevel=4
1257 )
1257 )
1258 return ret
1258 return ret
1259
1259
1260 return checksvfs
1260 return checksvfs
1261
1261
1262 def close(self):
1262 def close(self):
1263 self._writecaches()
1263 self._writecaches()
1264
1264
1265 def _writecaches(self):
1265 def _writecaches(self):
1266 if self._revbranchcache:
1266 if self._revbranchcache:
1267 self._revbranchcache.write()
1267 self._revbranchcache.write()
1268
1268
1269 def _restrictcapabilities(self, caps):
1269 def _restrictcapabilities(self, caps):
1270 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1270 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1271 caps = set(caps)
1271 caps = set(caps)
1272 capsblob = bundle2.encodecaps(
1272 capsblob = bundle2.encodecaps(
1273 bundle2.getrepocaps(self, role=b'client')
1273 bundle2.getrepocaps(self, role=b'client')
1274 )
1274 )
1275 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1275 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1276 return caps
1276 return caps
1277
1277
1278 def _writerequirements(self):
1278 def _writerequirements(self):
1279 scmutil.writerequires(self.vfs, self.requirements)
1279 scmutil.writerequires(self.vfs, self.requirements)
1280
1280
1281 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1281 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1282 # self -> auditor -> self._checknested -> self
1282 # self -> auditor -> self._checknested -> self
1283
1283
1284 @property
1284 @property
1285 def auditor(self):
1285 def auditor(self):
1286 # This is only used by context.workingctx.match in order to
1286 # This is only used by context.workingctx.match in order to
1287 # detect files in subrepos.
1287 # detect files in subrepos.
1288 return pathutil.pathauditor(self.root, callback=self._checknested)
1288 return pathutil.pathauditor(self.root, callback=self._checknested)
1289
1289
1290 @property
1290 @property
1291 def nofsauditor(self):
1291 def nofsauditor(self):
1292 # This is only used by context.basectx.match in order to detect
1292 # This is only used by context.basectx.match in order to detect
1293 # files in subrepos.
1293 # files in subrepos.
1294 return pathutil.pathauditor(
1294 return pathutil.pathauditor(
1295 self.root, callback=self._checknested, realfs=False, cached=True
1295 self.root, callback=self._checknested, realfs=False, cached=True
1296 )
1296 )
1297
1297
1298 def _checknested(self, path):
1298 def _checknested(self, path):
1299 """Determine if path is a legal nested repository."""
1299 """Determine if path is a legal nested repository."""
1300 if not path.startswith(self.root):
1300 if not path.startswith(self.root):
1301 return False
1301 return False
1302 subpath = path[len(self.root) + 1 :]
1302 subpath = path[len(self.root) + 1 :]
1303 normsubpath = util.pconvert(subpath)
1303 normsubpath = util.pconvert(subpath)
1304
1304
1305 # XXX: Checking against the current working copy is wrong in
1305 # XXX: Checking against the current working copy is wrong in
1306 # the sense that it can reject things like
1306 # the sense that it can reject things like
1307 #
1307 #
1308 # $ hg cat -r 10 sub/x.txt
1308 # $ hg cat -r 10 sub/x.txt
1309 #
1309 #
1310 # if sub/ is no longer a subrepository in the working copy
1310 # if sub/ is no longer a subrepository in the working copy
1311 # parent revision.
1311 # parent revision.
1312 #
1312 #
1313 # However, it can of course also allow things that would have
1313 # However, it can of course also allow things that would have
1314 # been rejected before, such as the above cat command if sub/
1314 # been rejected before, such as the above cat command if sub/
1315 # is a subrepository now, but was a normal directory before.
1315 # is a subrepository now, but was a normal directory before.
1316 # The old path auditor would have rejected by mistake since it
1316 # The old path auditor would have rejected by mistake since it
1317 # panics when it sees sub/.hg/.
1317 # panics when it sees sub/.hg/.
1318 #
1318 #
1319 # All in all, checking against the working copy seems sensible
1319 # All in all, checking against the working copy seems sensible
1320 # since we want to prevent access to nested repositories on
1320 # since we want to prevent access to nested repositories on
1321 # the filesystem *now*.
1321 # the filesystem *now*.
1322 ctx = self[None]
1322 ctx = self[None]
1323 parts = util.splitpath(subpath)
1323 parts = util.splitpath(subpath)
1324 while parts:
1324 while parts:
1325 prefix = b'/'.join(parts)
1325 prefix = b'/'.join(parts)
1326 if prefix in ctx.substate:
1326 if prefix in ctx.substate:
1327 if prefix == normsubpath:
1327 if prefix == normsubpath:
1328 return True
1328 return True
1329 else:
1329 else:
1330 sub = ctx.sub(prefix)
1330 sub = ctx.sub(prefix)
1331 return sub.checknested(subpath[len(prefix) + 1 :])
1331 return sub.checknested(subpath[len(prefix) + 1 :])
1332 else:
1332 else:
1333 parts.pop()
1333 parts.pop()
1334 return False
1334 return False
1335
1335
1336 def peer(self):
1336 def peer(self):
1337 return localpeer(self) # not cached to avoid reference cycle
1337 return localpeer(self) # not cached to avoid reference cycle
1338
1338
1339 def unfiltered(self):
1339 def unfiltered(self):
1340 """Return unfiltered version of the repository
1340 """Return unfiltered version of the repository
1341
1341
1342 Intended to be overwritten by filtered repo."""
1342 Intended to be overwritten by filtered repo."""
1343 return self
1343 return self
1344
1344
1345 def filtered(self, name, visibilityexceptions=None):
1345 def filtered(self, name, visibilityexceptions=None):
1346 """Return a filtered version of a repository
1346 """Return a filtered version of a repository
1347
1347
1348 The `name` parameter is the identifier of the requested view. This
1348 The `name` parameter is the identifier of the requested view. This
1349 will return a repoview object set "exactly" to the specified view.
1349 will return a repoview object set "exactly" to the specified view.
1350
1350
1351 This function does not apply recursive filtering to a repository. For
1351 This function does not apply recursive filtering to a repository. For
1352 example calling `repo.filtered("served")` will return a repoview using
1352 example calling `repo.filtered("served")` will return a repoview using
1353 the "served" view, regardless of the initial view used by `repo`.
1353 the "served" view, regardless of the initial view used by `repo`.
1354
1354
1355 In other word, there is always only one level of `repoview` "filtering".
1355 In other word, there is always only one level of `repoview` "filtering".
1356 """
1356 """
1357 if self._extrafilterid is not None and b'%' not in name:
1357 if self._extrafilterid is not None and b'%' not in name:
1358 name = name + b'%' + self._extrafilterid
1358 name = name + b'%' + self._extrafilterid
1359
1359
1360 cls = repoview.newtype(self.unfiltered().__class__)
1360 cls = repoview.newtype(self.unfiltered().__class__)
1361 return cls(self, name, visibilityexceptions)
1361 return cls(self, name, visibilityexceptions)
1362
1362
1363 @mixedrepostorecache(
1363 @mixedrepostorecache(
1364 (b'bookmarks', b'plain'),
1364 (b'bookmarks', b'plain'),
1365 (b'bookmarks.current', b'plain'),
1365 (b'bookmarks.current', b'plain'),
1366 (b'bookmarks', b''),
1366 (b'bookmarks', b''),
1367 (b'00changelog.i', b''),
1367 (b'00changelog.i', b''),
1368 )
1368 )
1369 def _bookmarks(self):
1369 def _bookmarks(self):
1370 # Since the multiple files involved in the transaction cannot be
1370 # Since the multiple files involved in the transaction cannot be
1371 # written atomically (with current repository format), there is a race
1371 # written atomically (with current repository format), there is a race
1372 # condition here.
1372 # condition here.
1373 #
1373 #
1374 # 1) changelog content A is read
1374 # 1) changelog content A is read
1375 # 2) outside transaction update changelog to content B
1375 # 2) outside transaction update changelog to content B
1376 # 3) outside transaction update bookmark file referring to content B
1376 # 3) outside transaction update bookmark file referring to content B
1377 # 4) bookmarks file content is read and filtered against changelog-A
1377 # 4) bookmarks file content is read and filtered against changelog-A
1378 #
1378 #
1379 # When this happens, bookmarks against nodes missing from A are dropped.
1379 # When this happens, bookmarks against nodes missing from A are dropped.
1380 #
1380 #
1381 # Having this happening during read is not great, but it become worse
1381 # Having this happening during read is not great, but it become worse
1382 # when this happen during write because the bookmarks to the "unknown"
1382 # when this happen during write because the bookmarks to the "unknown"
1383 # nodes will be dropped for good. However, writes happen within locks.
1383 # nodes will be dropped for good. However, writes happen within locks.
1384 # This locking makes it possible to have a race free consistent read.
1384 # This locking makes it possible to have a race free consistent read.
1385 # For this purpose data read from disc before locking are
1385 # For this purpose data read from disc before locking are
1386 # "invalidated" right after the locks are taken. This invalidations are
1386 # "invalidated" right after the locks are taken. This invalidations are
1387 # "light", the `filecache` mechanism keep the data in memory and will
1387 # "light", the `filecache` mechanism keep the data in memory and will
1388 # reuse them if the underlying files did not changed. Not parsing the
1388 # reuse them if the underlying files did not changed. Not parsing the
1389 # same data multiple times helps performances.
1389 # same data multiple times helps performances.
1390 #
1390 #
1391 # Unfortunately in the case describe above, the files tracked by the
1391 # Unfortunately in the case describe above, the files tracked by the
1392 # bookmarks file cache might not have changed, but the in-memory
1392 # bookmarks file cache might not have changed, but the in-memory
1393 # content is still "wrong" because we used an older changelog content
1393 # content is still "wrong" because we used an older changelog content
1394 # to process the on-disk data. So after locking, the changelog would be
1394 # to process the on-disk data. So after locking, the changelog would be
1395 # refreshed but `_bookmarks` would be preserved.
1395 # refreshed but `_bookmarks` would be preserved.
1396 # Adding `00changelog.i` to the list of tracked file is not
1396 # Adding `00changelog.i` to the list of tracked file is not
1397 # enough, because at the time we build the content for `_bookmarks` in
1397 # enough, because at the time we build the content for `_bookmarks` in
1398 # (4), the changelog file has already diverged from the content used
1398 # (4), the changelog file has already diverged from the content used
1399 # for loading `changelog` in (1)
1399 # for loading `changelog` in (1)
1400 #
1400 #
1401 # To prevent the issue, we force the changelog to be explicitly
1401 # To prevent the issue, we force the changelog to be explicitly
1402 # reloaded while computing `_bookmarks`. The data race can still happen
1402 # reloaded while computing `_bookmarks`. The data race can still happen
1403 # without the lock (with a narrower window), but it would no longer go
1403 # without the lock (with a narrower window), but it would no longer go
1404 # undetected during the lock time refresh.
1404 # undetected during the lock time refresh.
1405 #
1405 #
1406 # The new schedule is as follow
1406 # The new schedule is as follow
1407 #
1407 #
1408 # 1) filecache logic detect that `_bookmarks` needs to be computed
1408 # 1) filecache logic detect that `_bookmarks` needs to be computed
1409 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1409 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1410 # 3) We force `changelog` filecache to be tested
1410 # 3) We force `changelog` filecache to be tested
1411 # 4) cachestat for `changelog` are captured (for changelog)
1411 # 4) cachestat for `changelog` are captured (for changelog)
1412 # 5) `_bookmarks` is computed and cached
1412 # 5) `_bookmarks` is computed and cached
1413 #
1413 #
1414 # The step in (3) ensure we have a changelog at least as recent as the
1414 # The step in (3) ensure we have a changelog at least as recent as the
1415 # cache stat computed in (1). As a result at locking time:
1415 # cache stat computed in (1). As a result at locking time:
1416 # * if the changelog did not changed since (1) -> we can reuse the data
1416 # * if the changelog did not changed since (1) -> we can reuse the data
1417 # * otherwise -> the bookmarks get refreshed.
1417 # * otherwise -> the bookmarks get refreshed.
1418 self._refreshchangelog()
1418 self._refreshchangelog()
1419 return bookmarks.bmstore(self)
1419 return bookmarks.bmstore(self)
1420
1420
1421 def _refreshchangelog(self):
1421 def _refreshchangelog(self):
1422 """make sure the in memory changelog match the on-disk one"""
1422 """make sure the in memory changelog match the on-disk one"""
1423 if 'changelog' in vars(self) and self.currenttransaction() is None:
1423 if 'changelog' in vars(self) and self.currenttransaction() is None:
1424 del self.changelog
1424 del self.changelog
1425
1425
1426 @property
1426 @property
1427 def _activebookmark(self):
1427 def _activebookmark(self):
1428 return self._bookmarks.active
1428 return self._bookmarks.active
1429
1429
1430 # _phasesets depend on changelog. what we need is to call
1430 # _phasesets depend on changelog. what we need is to call
1431 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1431 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1432 # can't be easily expressed in filecache mechanism.
1432 # can't be easily expressed in filecache mechanism.
1433 @storecache(b'phaseroots', b'00changelog.i')
1433 @storecache(b'phaseroots', b'00changelog.i')
1434 def _phasecache(self):
1434 def _phasecache(self):
1435 return phases.phasecache(self, self._phasedefaults)
1435 return phases.phasecache(self, self._phasedefaults)
1436
1436
1437 @storecache(b'obsstore')
1437 @storecache(b'obsstore')
1438 def obsstore(self):
1438 def obsstore(self):
1439 return obsolete.makestore(self.ui, self)
1439 return obsolete.makestore(self.ui, self)
1440
1440
1441 @storecache(b'00changelog.i')
1441 @storecache(b'00changelog.i')
1442 def changelog(self):
1442 def changelog(self):
1443 return self.store.changelog(txnutil.mayhavepending(self.root))
1443 return self.store.changelog(txnutil.mayhavepending(self.root))
1444
1444
1445 @storecache(b'00manifest.i')
1445 @storecache(b'00manifest.i')
1446 def manifestlog(self):
1446 def manifestlog(self):
1447 return self.store.manifestlog(self, self._storenarrowmatch)
1447 return self.store.manifestlog(self, self._storenarrowmatch)
1448
1448
1449 @repofilecache(b'dirstate')
1449 @repofilecache(b'dirstate')
1450 def dirstate(self):
1450 def dirstate(self):
1451 return self._makedirstate()
1451 return self._makedirstate()
1452
1452
1453 def _makedirstate(self):
1453 def _makedirstate(self):
1454 """Extension point for wrapping the dirstate per-repo."""
1454 """Extension point for wrapping the dirstate per-repo."""
1455 sparsematchfn = lambda: sparse.matcher(self)
1455 sparsematchfn = lambda: sparse.matcher(self)
1456
1456
1457 return dirstate.dirstate(
1457 return dirstate.dirstate(
1458 self.vfs, self.ui, self.root, self._dirstatevalidate, sparsematchfn
1458 self.vfs, self.ui, self.root, self._dirstatevalidate, sparsematchfn
1459 )
1459 )
1460
1460
1461 def _dirstatevalidate(self, node):
1461 def _dirstatevalidate(self, node):
1462 try:
1462 try:
1463 self.changelog.rev(node)
1463 self.changelog.rev(node)
1464 return node
1464 return node
1465 except error.LookupError:
1465 except error.LookupError:
1466 if not self._dirstatevalidatewarned:
1466 if not self._dirstatevalidatewarned:
1467 self._dirstatevalidatewarned = True
1467 self._dirstatevalidatewarned = True
1468 self.ui.warn(
1468 self.ui.warn(
1469 _(b"warning: ignoring unknown working parent %s!\n")
1469 _(b"warning: ignoring unknown working parent %s!\n")
1470 % short(node)
1470 % short(node)
1471 )
1471 )
1472 return nullid
1472 return nullid
1473
1473
1474 @storecache(narrowspec.FILENAME)
1474 @storecache(narrowspec.FILENAME)
1475 def narrowpats(self):
1475 def narrowpats(self):
1476 """matcher patterns for this repository's narrowspec
1476 """matcher patterns for this repository's narrowspec
1477
1477
1478 A tuple of (includes, excludes).
1478 A tuple of (includes, excludes).
1479 """
1479 """
1480 return narrowspec.load(self)
1480 return narrowspec.load(self)
1481
1481
1482 @storecache(narrowspec.FILENAME)
1482 @storecache(narrowspec.FILENAME)
1483 def _storenarrowmatch(self):
1483 def _storenarrowmatch(self):
1484 if repository.NARROW_REQUIREMENT not in self.requirements:
1484 if repository.NARROW_REQUIREMENT not in self.requirements:
1485 return matchmod.always()
1485 return matchmod.always()
1486 include, exclude = self.narrowpats
1486 include, exclude = self.narrowpats
1487 return narrowspec.match(self.root, include=include, exclude=exclude)
1487 return narrowspec.match(self.root, include=include, exclude=exclude)
1488
1488
1489 @storecache(narrowspec.FILENAME)
1489 @storecache(narrowspec.FILENAME)
1490 def _narrowmatch(self):
1490 def _narrowmatch(self):
1491 if repository.NARROW_REQUIREMENT not in self.requirements:
1491 if repository.NARROW_REQUIREMENT not in self.requirements:
1492 return matchmod.always()
1492 return matchmod.always()
1493 narrowspec.checkworkingcopynarrowspec(self)
1493 narrowspec.checkworkingcopynarrowspec(self)
1494 include, exclude = self.narrowpats
1494 include, exclude = self.narrowpats
1495 return narrowspec.match(self.root, include=include, exclude=exclude)
1495 return narrowspec.match(self.root, include=include, exclude=exclude)
1496
1496
1497 def narrowmatch(self, match=None, includeexact=False):
1497 def narrowmatch(self, match=None, includeexact=False):
1498 """matcher corresponding the the repo's narrowspec
1498 """matcher corresponding the the repo's narrowspec
1499
1499
1500 If `match` is given, then that will be intersected with the narrow
1500 If `match` is given, then that will be intersected with the narrow
1501 matcher.
1501 matcher.
1502
1502
1503 If `includeexact` is True, then any exact matches from `match` will
1503 If `includeexact` is True, then any exact matches from `match` will
1504 be included even if they're outside the narrowspec.
1504 be included even if they're outside the narrowspec.
1505 """
1505 """
1506 if match:
1506 if match:
1507 if includeexact and not self._narrowmatch.always():
1507 if includeexact and not self._narrowmatch.always():
1508 # do not exclude explicitly-specified paths so that they can
1508 # do not exclude explicitly-specified paths so that they can
1509 # be warned later on
1509 # be warned later on
1510 em = matchmod.exact(match.files())
1510 em = matchmod.exact(match.files())
1511 nm = matchmod.unionmatcher([self._narrowmatch, em])
1511 nm = matchmod.unionmatcher([self._narrowmatch, em])
1512 return matchmod.intersectmatchers(match, nm)
1512 return matchmod.intersectmatchers(match, nm)
1513 return matchmod.intersectmatchers(match, self._narrowmatch)
1513 return matchmod.intersectmatchers(match, self._narrowmatch)
1514 return self._narrowmatch
1514 return self._narrowmatch
1515
1515
1516 def setnarrowpats(self, newincludes, newexcludes):
1516 def setnarrowpats(self, newincludes, newexcludes):
1517 narrowspec.save(self, newincludes, newexcludes)
1517 narrowspec.save(self, newincludes, newexcludes)
1518 self.invalidate(clearfilecache=True)
1518 self.invalidate(clearfilecache=True)
1519
1519
1520 @util.propertycache
1520 @util.propertycache
1521 def _quick_access_changeid(self):
1521 def _quick_access_changeid(self):
1522 """an helper dictionnary for __getitem__ calls
1522 """an helper dictionnary for __getitem__ calls
1523
1523
1524 This contains a list of symbol we can recognise right away without
1524 This contains a list of symbol we can recognise right away without
1525 further processing.
1525 further processing.
1526 """
1526 """
1527 return {
1527 return {
1528 b'null': (nullrev, nullid),
1528 b'null': (nullrev, nullid),
1529 nullrev: (nullrev, nullid),
1529 nullrev: (nullrev, nullid),
1530 nullid: (nullrev, nullid),
1530 nullid: (nullrev, nullid),
1531 }
1531 }
1532
1532
1533 def __getitem__(self, changeid):
1533 def __getitem__(self, changeid):
1534 # dealing with special cases
1534 # dealing with special cases
1535 if changeid is None:
1535 if changeid is None:
1536 return context.workingctx(self)
1536 return context.workingctx(self)
1537 if isinstance(changeid, context.basectx):
1537 if isinstance(changeid, context.basectx):
1538 return changeid
1538 return changeid
1539
1539
1540 # dealing with multiple revisions
1540 # dealing with multiple revisions
1541 if isinstance(changeid, slice):
1541 if isinstance(changeid, slice):
1542 # wdirrev isn't contiguous so the slice shouldn't include it
1542 # wdirrev isn't contiguous so the slice shouldn't include it
1543 return [
1543 return [
1544 self[i]
1544 self[i]
1545 for i in pycompat.xrange(*changeid.indices(len(self)))
1545 for i in pycompat.xrange(*changeid.indices(len(self)))
1546 if i not in self.changelog.filteredrevs
1546 if i not in self.changelog.filteredrevs
1547 ]
1547 ]
1548
1548
1549 # dealing with some special values
1549 # dealing with some special values
1550 quick_access = self._quick_access_changeid.get(changeid)
1550 quick_access = self._quick_access_changeid.get(changeid)
1551 if quick_access is not None:
1551 if quick_access is not None:
1552 rev, node = quick_access
1552 rev, node = quick_access
1553 return context.changectx(self, rev, node, maybe_filtered=False)
1553 return context.changectx(self, rev, node, maybe_filtered=False)
1554 if changeid == b'tip':
1554 if changeid == b'tip':
1555 node = self.changelog.tip()
1555 node = self.changelog.tip()
1556 rev = self.changelog.rev(node)
1556 rev = self.changelog.rev(node)
1557 return context.changectx(self, rev, node)
1557 return context.changectx(self, rev, node)
1558
1558
1559 # dealing with arbitrary values
1559 # dealing with arbitrary values
1560 try:
1560 try:
1561 if isinstance(changeid, int):
1561 if isinstance(changeid, int):
1562 node = self.changelog.node(changeid)
1562 node = self.changelog.node(changeid)
1563 rev = changeid
1563 rev = changeid
1564 elif changeid == b'.':
1564 elif changeid == b'.':
1565 # this is a hack to delay/avoid loading obsmarkers
1565 # this is a hack to delay/avoid loading obsmarkers
1566 # when we know that '.' won't be hidden
1566 # when we know that '.' won't be hidden
1567 node = self.dirstate.p1()
1567 node = self.dirstate.p1()
1568 rev = self.unfiltered().changelog.rev(node)
1568 rev = self.unfiltered().changelog.rev(node)
1569 elif len(changeid) == 20:
1569 elif len(changeid) == 20:
1570 try:
1570 try:
1571 node = changeid
1571 node = changeid
1572 rev = self.changelog.rev(changeid)
1572 rev = self.changelog.rev(changeid)
1573 except error.FilteredLookupError:
1573 except error.FilteredLookupError:
1574 changeid = hex(changeid) # for the error message
1574 changeid = hex(changeid) # for the error message
1575 raise
1575 raise
1576 except LookupError:
1576 except LookupError:
1577 # check if it might have come from damaged dirstate
1577 # check if it might have come from damaged dirstate
1578 #
1578 #
1579 # XXX we could avoid the unfiltered if we had a recognizable
1579 # XXX we could avoid the unfiltered if we had a recognizable
1580 # exception for filtered changeset access
1580 # exception for filtered changeset access
1581 if (
1581 if (
1582 self.local()
1582 self.local()
1583 and changeid in self.unfiltered().dirstate.parents()
1583 and changeid in self.unfiltered().dirstate.parents()
1584 ):
1584 ):
1585 msg = _(b"working directory has unknown parent '%s'!")
1585 msg = _(b"working directory has unknown parent '%s'!")
1586 raise error.Abort(msg % short(changeid))
1586 raise error.Abort(msg % short(changeid))
1587 changeid = hex(changeid) # for the error message
1587 changeid = hex(changeid) # for the error message
1588 raise
1588 raise
1589
1589
1590 elif len(changeid) == 40:
1590 elif len(changeid) == 40:
1591 node = bin(changeid)
1591 node = bin(changeid)
1592 rev = self.changelog.rev(node)
1592 rev = self.changelog.rev(node)
1593 else:
1593 else:
1594 raise error.ProgrammingError(
1594 raise error.ProgrammingError(
1595 b"unsupported changeid '%s' of type %s"
1595 b"unsupported changeid '%s' of type %s"
1596 % (changeid, pycompat.bytestr(type(changeid)))
1596 % (changeid, pycompat.bytestr(type(changeid)))
1597 )
1597 )
1598
1598
1599 return context.changectx(self, rev, node)
1599 return context.changectx(self, rev, node)
1600
1600
1601 except (error.FilteredIndexError, error.FilteredLookupError):
1601 except (error.FilteredIndexError, error.FilteredLookupError):
1602 raise error.FilteredRepoLookupError(
1602 raise error.FilteredRepoLookupError(
1603 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1603 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1604 )
1604 )
1605 except (IndexError, LookupError):
1605 except (IndexError, LookupError):
1606 raise error.RepoLookupError(
1606 raise error.RepoLookupError(
1607 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1607 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1608 )
1608 )
1609 except error.WdirUnsupported:
1609 except error.WdirUnsupported:
1610 return context.workingctx(self)
1610 return context.workingctx(self)
1611
1611
1612 def __contains__(self, changeid):
1612 def __contains__(self, changeid):
1613 """True if the given changeid exists
1613 """True if the given changeid exists
1614
1614
1615 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1615 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1616 specified.
1616 specified.
1617 """
1617 """
1618 try:
1618 try:
1619 self[changeid]
1619 self[changeid]
1620 return True
1620 return True
1621 except error.RepoLookupError:
1621 except error.RepoLookupError:
1622 return False
1622 return False
1623
1623
1624 def __nonzero__(self):
1624 def __nonzero__(self):
1625 return True
1625 return True
1626
1626
1627 __bool__ = __nonzero__
1627 __bool__ = __nonzero__
1628
1628
1629 def __len__(self):
1629 def __len__(self):
1630 # no need to pay the cost of repoview.changelog
1630 # no need to pay the cost of repoview.changelog
1631 unfi = self.unfiltered()
1631 unfi = self.unfiltered()
1632 return len(unfi.changelog)
1632 return len(unfi.changelog)
1633
1633
1634 def __iter__(self):
1634 def __iter__(self):
1635 return iter(self.changelog)
1635 return iter(self.changelog)
1636
1636
1637 def revs(self, expr, *args):
1637 def revs(self, expr, *args):
1638 '''Find revisions matching a revset.
1638 '''Find revisions matching a revset.
1639
1639
1640 The revset is specified as a string ``expr`` that may contain
1640 The revset is specified as a string ``expr`` that may contain
1641 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1641 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1642
1642
1643 Revset aliases from the configuration are not expanded. To expand
1643 Revset aliases from the configuration are not expanded. To expand
1644 user aliases, consider calling ``scmutil.revrange()`` or
1644 user aliases, consider calling ``scmutil.revrange()`` or
1645 ``repo.anyrevs([expr], user=True)``.
1645 ``repo.anyrevs([expr], user=True)``.
1646
1646
1647 Returns a revset.abstractsmartset, which is a list-like interface
1647 Returns a revset.abstractsmartset, which is a list-like interface
1648 that contains integer revisions.
1648 that contains integer revisions.
1649 '''
1649 '''
1650 tree = revsetlang.spectree(expr, *args)
1650 tree = revsetlang.spectree(expr, *args)
1651 return revset.makematcher(tree)(self)
1651 return revset.makematcher(tree)(self)
1652
1652
1653 def set(self, expr, *args):
1653 def set(self, expr, *args):
1654 '''Find revisions matching a revset and emit changectx instances.
1654 '''Find revisions matching a revset and emit changectx instances.
1655
1655
1656 This is a convenience wrapper around ``revs()`` that iterates the
1656 This is a convenience wrapper around ``revs()`` that iterates the
1657 result and is a generator of changectx instances.
1657 result and is a generator of changectx instances.
1658
1658
1659 Revset aliases from the configuration are not expanded. To expand
1659 Revset aliases from the configuration are not expanded. To expand
1660 user aliases, consider calling ``scmutil.revrange()``.
1660 user aliases, consider calling ``scmutil.revrange()``.
1661 '''
1661 '''
1662 for r in self.revs(expr, *args):
1662 for r in self.revs(expr, *args):
1663 yield self[r]
1663 yield self[r]
1664
1664
1665 def anyrevs(self, specs, user=False, localalias=None):
1665 def anyrevs(self, specs, user=False, localalias=None):
1666 '''Find revisions matching one of the given revsets.
1666 '''Find revisions matching one of the given revsets.
1667
1667
1668 Revset aliases from the configuration are not expanded by default. To
1668 Revset aliases from the configuration are not expanded by default. To
1669 expand user aliases, specify ``user=True``. To provide some local
1669 expand user aliases, specify ``user=True``. To provide some local
1670 definitions overriding user aliases, set ``localalias`` to
1670 definitions overriding user aliases, set ``localalias`` to
1671 ``{name: definitionstring}``.
1671 ``{name: definitionstring}``.
1672 '''
1672 '''
1673 if specs == [b'null']:
1673 if specs == [b'null']:
1674 return revset.baseset([nullrev])
1674 return revset.baseset([nullrev])
1675 if user:
1675 if user:
1676 m = revset.matchany(
1676 m = revset.matchany(
1677 self.ui,
1677 self.ui,
1678 specs,
1678 specs,
1679 lookup=revset.lookupfn(self),
1679 lookup=revset.lookupfn(self),
1680 localalias=localalias,
1680 localalias=localalias,
1681 )
1681 )
1682 else:
1682 else:
1683 m = revset.matchany(None, specs, localalias=localalias)
1683 m = revset.matchany(None, specs, localalias=localalias)
1684 return m(self)
1684 return m(self)
1685
1685
1686 def url(self):
1686 def url(self):
1687 return b'file:' + self.root
1687 return b'file:' + self.root
1688
1688
1689 def hook(self, name, throw=False, **args):
1689 def hook(self, name, throw=False, **args):
1690 """Call a hook, passing this repo instance.
1690 """Call a hook, passing this repo instance.
1691
1691
1692 This a convenience method to aid invoking hooks. Extensions likely
1692 This a convenience method to aid invoking hooks. Extensions likely
1693 won't call this unless they have registered a custom hook or are
1693 won't call this unless they have registered a custom hook or are
1694 replacing code that is expected to call a hook.
1694 replacing code that is expected to call a hook.
1695 """
1695 """
1696 return hook.hook(self.ui, self, name, throw, **args)
1696 return hook.hook(self.ui, self, name, throw, **args)
1697
1697
1698 @filteredpropertycache
1698 @filteredpropertycache
1699 def _tagscache(self):
1699 def _tagscache(self):
1700 '''Returns a tagscache object that contains various tags related
1700 '''Returns a tagscache object that contains various tags related
1701 caches.'''
1701 caches.'''
1702
1702
1703 # This simplifies its cache management by having one decorated
1703 # This simplifies its cache management by having one decorated
1704 # function (this one) and the rest simply fetch things from it.
1704 # function (this one) and the rest simply fetch things from it.
1705 class tagscache(object):
1705 class tagscache(object):
1706 def __init__(self):
1706 def __init__(self):
1707 # These two define the set of tags for this repository. tags
1707 # These two define the set of tags for this repository. tags
1708 # maps tag name to node; tagtypes maps tag name to 'global' or
1708 # maps tag name to node; tagtypes maps tag name to 'global' or
1709 # 'local'. (Global tags are defined by .hgtags across all
1709 # 'local'. (Global tags are defined by .hgtags across all
1710 # heads, and local tags are defined in .hg/localtags.)
1710 # heads, and local tags are defined in .hg/localtags.)
1711 # They constitute the in-memory cache of tags.
1711 # They constitute the in-memory cache of tags.
1712 self.tags = self.tagtypes = None
1712 self.tags = self.tagtypes = None
1713
1713
1714 self.nodetagscache = self.tagslist = None
1714 self.nodetagscache = self.tagslist = None
1715
1715
1716 cache = tagscache()
1716 cache = tagscache()
1717 cache.tags, cache.tagtypes = self._findtags()
1717 cache.tags, cache.tagtypes = self._findtags()
1718
1718
1719 return cache
1719 return cache
1720
1720
1721 def tags(self):
1721 def tags(self):
1722 '''return a mapping of tag to node'''
1722 '''return a mapping of tag to node'''
1723 t = {}
1723 t = {}
1724 if self.changelog.filteredrevs:
1724 if self.changelog.filteredrevs:
1725 tags, tt = self._findtags()
1725 tags, tt = self._findtags()
1726 else:
1726 else:
1727 tags = self._tagscache.tags
1727 tags = self._tagscache.tags
1728 rev = self.changelog.rev
1728 rev = self.changelog.rev
1729 for k, v in pycompat.iteritems(tags):
1729 for k, v in pycompat.iteritems(tags):
1730 try:
1730 try:
1731 # ignore tags to unknown nodes
1731 # ignore tags to unknown nodes
1732 rev(v)
1732 rev(v)
1733 t[k] = v
1733 t[k] = v
1734 except (error.LookupError, ValueError):
1734 except (error.LookupError, ValueError):
1735 pass
1735 pass
1736 return t
1736 return t
1737
1737
1738 def _findtags(self):
1738 def _findtags(self):
1739 '''Do the hard work of finding tags. Return a pair of dicts
1739 '''Do the hard work of finding tags. Return a pair of dicts
1740 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1740 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1741 maps tag name to a string like \'global\' or \'local\'.
1741 maps tag name to a string like \'global\' or \'local\'.
1742 Subclasses or extensions are free to add their own tags, but
1742 Subclasses or extensions are free to add their own tags, but
1743 should be aware that the returned dicts will be retained for the
1743 should be aware that the returned dicts will be retained for the
1744 duration of the localrepo object.'''
1744 duration of the localrepo object.'''
1745
1745
1746 # XXX what tagtype should subclasses/extensions use? Currently
1746 # XXX what tagtype should subclasses/extensions use? Currently
1747 # mq and bookmarks add tags, but do not set the tagtype at all.
1747 # mq and bookmarks add tags, but do not set the tagtype at all.
1748 # Should each extension invent its own tag type? Should there
1748 # Should each extension invent its own tag type? Should there
1749 # be one tagtype for all such "virtual" tags? Or is the status
1749 # be one tagtype for all such "virtual" tags? Or is the status
1750 # quo fine?
1750 # quo fine?
1751
1751
1752 # map tag name to (node, hist)
1752 # map tag name to (node, hist)
1753 alltags = tagsmod.findglobaltags(self.ui, self)
1753 alltags = tagsmod.findglobaltags(self.ui, self)
1754 # map tag name to tag type
1754 # map tag name to tag type
1755 tagtypes = dict((tag, b'global') for tag in alltags)
1755 tagtypes = dict((tag, b'global') for tag in alltags)
1756
1756
1757 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1757 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1758
1758
1759 # Build the return dicts. Have to re-encode tag names because
1759 # Build the return dicts. Have to re-encode tag names because
1760 # the tags module always uses UTF-8 (in order not to lose info
1760 # the tags module always uses UTF-8 (in order not to lose info
1761 # writing to the cache), but the rest of Mercurial wants them in
1761 # writing to the cache), but the rest of Mercurial wants them in
1762 # local encoding.
1762 # local encoding.
1763 tags = {}
1763 tags = {}
1764 for (name, (node, hist)) in pycompat.iteritems(alltags):
1764 for (name, (node, hist)) in pycompat.iteritems(alltags):
1765 if node != nullid:
1765 if node != nullid:
1766 tags[encoding.tolocal(name)] = node
1766 tags[encoding.tolocal(name)] = node
1767 tags[b'tip'] = self.changelog.tip()
1767 tags[b'tip'] = self.changelog.tip()
1768 tagtypes = dict(
1768 tagtypes = dict(
1769 [
1769 [
1770 (encoding.tolocal(name), value)
1770 (encoding.tolocal(name), value)
1771 for (name, value) in pycompat.iteritems(tagtypes)
1771 for (name, value) in pycompat.iteritems(tagtypes)
1772 ]
1772 ]
1773 )
1773 )
1774 return (tags, tagtypes)
1774 return (tags, tagtypes)
1775
1775
1776 def tagtype(self, tagname):
1776 def tagtype(self, tagname):
1777 '''
1777 '''
1778 return the type of the given tag. result can be:
1778 return the type of the given tag. result can be:
1779
1779
1780 'local' : a local tag
1780 'local' : a local tag
1781 'global' : a global tag
1781 'global' : a global tag
1782 None : tag does not exist
1782 None : tag does not exist
1783 '''
1783 '''
1784
1784
1785 return self._tagscache.tagtypes.get(tagname)
1785 return self._tagscache.tagtypes.get(tagname)
1786
1786
1787 def tagslist(self):
1787 def tagslist(self):
1788 '''return a list of tags ordered by revision'''
1788 '''return a list of tags ordered by revision'''
1789 if not self._tagscache.tagslist:
1789 if not self._tagscache.tagslist:
1790 l = []
1790 l = []
1791 for t, n in pycompat.iteritems(self.tags()):
1791 for t, n in pycompat.iteritems(self.tags()):
1792 l.append((self.changelog.rev(n), t, n))
1792 l.append((self.changelog.rev(n), t, n))
1793 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1793 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1794
1794
1795 return self._tagscache.tagslist
1795 return self._tagscache.tagslist
1796
1796
1797 def nodetags(self, node):
1797 def nodetags(self, node):
1798 '''return the tags associated with a node'''
1798 '''return the tags associated with a node'''
1799 if not self._tagscache.nodetagscache:
1799 if not self._tagscache.nodetagscache:
1800 nodetagscache = {}
1800 nodetagscache = {}
1801 for t, n in pycompat.iteritems(self._tagscache.tags):
1801 for t, n in pycompat.iteritems(self._tagscache.tags):
1802 nodetagscache.setdefault(n, []).append(t)
1802 nodetagscache.setdefault(n, []).append(t)
1803 for tags in pycompat.itervalues(nodetagscache):
1803 for tags in pycompat.itervalues(nodetagscache):
1804 tags.sort()
1804 tags.sort()
1805 self._tagscache.nodetagscache = nodetagscache
1805 self._tagscache.nodetagscache = nodetagscache
1806 return self._tagscache.nodetagscache.get(node, [])
1806 return self._tagscache.nodetagscache.get(node, [])
1807
1807
1808 def nodebookmarks(self, node):
1808 def nodebookmarks(self, node):
1809 """return the list of bookmarks pointing to the specified node"""
1809 """return the list of bookmarks pointing to the specified node"""
1810 return self._bookmarks.names(node)
1810 return self._bookmarks.names(node)
1811
1811
1812 def branchmap(self):
1812 def branchmap(self):
1813 '''returns a dictionary {branch: [branchheads]} with branchheads
1813 '''returns a dictionary {branch: [branchheads]} with branchheads
1814 ordered by increasing revision number'''
1814 ordered by increasing revision number'''
1815 return self._branchcaches[self]
1815 return self._branchcaches[self]
1816
1816
1817 @unfilteredmethod
1817 @unfilteredmethod
1818 def revbranchcache(self):
1818 def revbranchcache(self):
1819 if not self._revbranchcache:
1819 if not self._revbranchcache:
1820 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1820 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1821 return self._revbranchcache
1821 return self._revbranchcache
1822
1822
1823 def branchtip(self, branch, ignoremissing=False):
1823 def branchtip(self, branch, ignoremissing=False):
1824 '''return the tip node for a given branch
1824 '''return the tip node for a given branch
1825
1825
1826 If ignoremissing is True, then this method will not raise an error.
1826 If ignoremissing is True, then this method will not raise an error.
1827 This is helpful for callers that only expect None for a missing branch
1827 This is helpful for callers that only expect None for a missing branch
1828 (e.g. namespace).
1828 (e.g. namespace).
1829
1829
1830 '''
1830 '''
1831 try:
1831 try:
1832 return self.branchmap().branchtip(branch)
1832 return self.branchmap().branchtip(branch)
1833 except KeyError:
1833 except KeyError:
1834 if not ignoremissing:
1834 if not ignoremissing:
1835 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
1835 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
1836 else:
1836 else:
1837 pass
1837 pass
1838
1838
1839 def lookup(self, key):
1839 def lookup(self, key):
1840 node = scmutil.revsymbol(self, key).node()
1840 node = scmutil.revsymbol(self, key).node()
1841 if node is None:
1841 if node is None:
1842 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
1842 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
1843 return node
1843 return node
1844
1844
1845 def lookupbranch(self, key):
1845 def lookupbranch(self, key):
1846 if self.branchmap().hasbranch(key):
1846 if self.branchmap().hasbranch(key):
1847 return key
1847 return key
1848
1848
1849 return scmutil.revsymbol(self, key).branch()
1849 return scmutil.revsymbol(self, key).branch()
1850
1850
1851 def known(self, nodes):
1851 def known(self, nodes):
1852 cl = self.changelog
1852 cl = self.changelog
1853 get_rev = cl.index.get_rev
1853 get_rev = cl.index.get_rev
1854 filtered = cl.filteredrevs
1854 filtered = cl.filteredrevs
1855 result = []
1855 result = []
1856 for n in nodes:
1856 for n in nodes:
1857 r = get_rev(n)
1857 r = get_rev(n)
1858 resp = not (r is None or r in filtered)
1858 resp = not (r is None or r in filtered)
1859 result.append(resp)
1859 result.append(resp)
1860 return result
1860 return result
1861
1861
1862 def local(self):
1862 def local(self):
1863 return self
1863 return self
1864
1864
1865 def publishing(self):
1865 def publishing(self):
1866 # it's safe (and desirable) to trust the publish flag unconditionally
1866 # it's safe (and desirable) to trust the publish flag unconditionally
1867 # so that we don't finalize changes shared between users via ssh or nfs
1867 # so that we don't finalize changes shared between users via ssh or nfs
1868 return self.ui.configbool(b'phases', b'publish', untrusted=True)
1868 return self.ui.configbool(b'phases', b'publish', untrusted=True)
1869
1869
1870 def cancopy(self):
1870 def cancopy(self):
1871 # so statichttprepo's override of local() works
1871 # so statichttprepo's override of local() works
1872 if not self.local():
1872 if not self.local():
1873 return False
1873 return False
1874 if not self.publishing():
1874 if not self.publishing():
1875 return True
1875 return True
1876 # if publishing we can't copy if there is filtered content
1876 # if publishing we can't copy if there is filtered content
1877 return not self.filtered(b'visible').changelog.filteredrevs
1877 return not self.filtered(b'visible').changelog.filteredrevs
1878
1878
1879 def shared(self):
1879 def shared(self):
1880 '''the type of shared repository (None if not shared)'''
1880 '''the type of shared repository (None if not shared)'''
1881 if self.sharedpath != self.path:
1881 if self.sharedpath != self.path:
1882 return b'store'
1882 return b'store'
1883 return None
1883 return None
1884
1884
1885 def wjoin(self, f, *insidef):
1885 def wjoin(self, f, *insidef):
1886 return self.vfs.reljoin(self.root, f, *insidef)
1886 return self.vfs.reljoin(self.root, f, *insidef)
1887
1887
1888 def setparents(self, p1, p2=nullid):
1888 def setparents(self, p1, p2=nullid):
1889 with self.dirstate.parentchange():
1889 self[None].setparents(p1, p2)
1890 copies = self.dirstate.setparents(p1, p2)
1891 pctx = self[p1]
1892 if copies:
1893 # Adjust copy records, the dirstate cannot do it, it
1894 # requires access to parents manifests. Preserve them
1895 # only for entries added to first parent.
1896 for f in copies:
1897 if f not in pctx and copies[f] in pctx:
1898 self.dirstate.copy(copies[f], f)
1899 if p2 == nullid:
1900 for f, s in sorted(self.dirstate.copies().items()):
1901 if f not in pctx and s not in pctx:
1902 self.dirstate.copy(None, f)
1903
1890
1904 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1891 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1905 """changeid must be a changeset revision, if specified.
1892 """changeid must be a changeset revision, if specified.
1906 fileid can be a file revision or node."""
1893 fileid can be a file revision or node."""
1907 return context.filectx(
1894 return context.filectx(
1908 self, path, changeid, fileid, changectx=changectx
1895 self, path, changeid, fileid, changectx=changectx
1909 )
1896 )
1910
1897
1911 def getcwd(self):
1898 def getcwd(self):
1912 return self.dirstate.getcwd()
1899 return self.dirstate.getcwd()
1913
1900
1914 def pathto(self, f, cwd=None):
1901 def pathto(self, f, cwd=None):
1915 return self.dirstate.pathto(f, cwd)
1902 return self.dirstate.pathto(f, cwd)
1916
1903
1917 def _loadfilter(self, filter):
1904 def _loadfilter(self, filter):
1918 if filter not in self._filterpats:
1905 if filter not in self._filterpats:
1919 l = []
1906 l = []
1920 for pat, cmd in self.ui.configitems(filter):
1907 for pat, cmd in self.ui.configitems(filter):
1921 if cmd == b'!':
1908 if cmd == b'!':
1922 continue
1909 continue
1923 mf = matchmod.match(self.root, b'', [pat])
1910 mf = matchmod.match(self.root, b'', [pat])
1924 fn = None
1911 fn = None
1925 params = cmd
1912 params = cmd
1926 for name, filterfn in pycompat.iteritems(self._datafilters):
1913 for name, filterfn in pycompat.iteritems(self._datafilters):
1927 if cmd.startswith(name):
1914 if cmd.startswith(name):
1928 fn = filterfn
1915 fn = filterfn
1929 params = cmd[len(name) :].lstrip()
1916 params = cmd[len(name) :].lstrip()
1930 break
1917 break
1931 if not fn:
1918 if not fn:
1932 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1919 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1933 fn.__name__ = 'commandfilter'
1920 fn.__name__ = 'commandfilter'
1934 # Wrap old filters not supporting keyword arguments
1921 # Wrap old filters not supporting keyword arguments
1935 if not pycompat.getargspec(fn)[2]:
1922 if not pycompat.getargspec(fn)[2]:
1936 oldfn = fn
1923 oldfn = fn
1937 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
1924 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
1938 fn.__name__ = 'compat-' + oldfn.__name__
1925 fn.__name__ = 'compat-' + oldfn.__name__
1939 l.append((mf, fn, params))
1926 l.append((mf, fn, params))
1940 self._filterpats[filter] = l
1927 self._filterpats[filter] = l
1941 return self._filterpats[filter]
1928 return self._filterpats[filter]
1942
1929
1943 def _filter(self, filterpats, filename, data):
1930 def _filter(self, filterpats, filename, data):
1944 for mf, fn, cmd in filterpats:
1931 for mf, fn, cmd in filterpats:
1945 if mf(filename):
1932 if mf(filename):
1946 self.ui.debug(
1933 self.ui.debug(
1947 b"filtering %s through %s\n"
1934 b"filtering %s through %s\n"
1948 % (filename, cmd or pycompat.sysbytes(fn.__name__))
1935 % (filename, cmd or pycompat.sysbytes(fn.__name__))
1949 )
1936 )
1950 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1937 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1951 break
1938 break
1952
1939
1953 return data
1940 return data
1954
1941
1955 @unfilteredpropertycache
1942 @unfilteredpropertycache
1956 def _encodefilterpats(self):
1943 def _encodefilterpats(self):
1957 return self._loadfilter(b'encode')
1944 return self._loadfilter(b'encode')
1958
1945
1959 @unfilteredpropertycache
1946 @unfilteredpropertycache
1960 def _decodefilterpats(self):
1947 def _decodefilterpats(self):
1961 return self._loadfilter(b'decode')
1948 return self._loadfilter(b'decode')
1962
1949
1963 def adddatafilter(self, name, filter):
1950 def adddatafilter(self, name, filter):
1964 self._datafilters[name] = filter
1951 self._datafilters[name] = filter
1965
1952
1966 def wread(self, filename):
1953 def wread(self, filename):
1967 if self.wvfs.islink(filename):
1954 if self.wvfs.islink(filename):
1968 data = self.wvfs.readlink(filename)
1955 data = self.wvfs.readlink(filename)
1969 else:
1956 else:
1970 data = self.wvfs.read(filename)
1957 data = self.wvfs.read(filename)
1971 return self._filter(self._encodefilterpats, filename, data)
1958 return self._filter(self._encodefilterpats, filename, data)
1972
1959
1973 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1960 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1974 """write ``data`` into ``filename`` in the working directory
1961 """write ``data`` into ``filename`` in the working directory
1975
1962
1976 This returns length of written (maybe decoded) data.
1963 This returns length of written (maybe decoded) data.
1977 """
1964 """
1978 data = self._filter(self._decodefilterpats, filename, data)
1965 data = self._filter(self._decodefilterpats, filename, data)
1979 if b'l' in flags:
1966 if b'l' in flags:
1980 self.wvfs.symlink(data, filename)
1967 self.wvfs.symlink(data, filename)
1981 else:
1968 else:
1982 self.wvfs.write(
1969 self.wvfs.write(
1983 filename, data, backgroundclose=backgroundclose, **kwargs
1970 filename, data, backgroundclose=backgroundclose, **kwargs
1984 )
1971 )
1985 if b'x' in flags:
1972 if b'x' in flags:
1986 self.wvfs.setflags(filename, False, True)
1973 self.wvfs.setflags(filename, False, True)
1987 else:
1974 else:
1988 self.wvfs.setflags(filename, False, False)
1975 self.wvfs.setflags(filename, False, False)
1989 return len(data)
1976 return len(data)
1990
1977
1991 def wwritedata(self, filename, data):
1978 def wwritedata(self, filename, data):
1992 return self._filter(self._decodefilterpats, filename, data)
1979 return self._filter(self._decodefilterpats, filename, data)
1993
1980
1994 def currenttransaction(self):
1981 def currenttransaction(self):
1995 """return the current transaction or None if non exists"""
1982 """return the current transaction or None if non exists"""
1996 if self._transref:
1983 if self._transref:
1997 tr = self._transref()
1984 tr = self._transref()
1998 else:
1985 else:
1999 tr = None
1986 tr = None
2000
1987
2001 if tr and tr.running():
1988 if tr and tr.running():
2002 return tr
1989 return tr
2003 return None
1990 return None
2004
1991
2005 def transaction(self, desc, report=None):
1992 def transaction(self, desc, report=None):
2006 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1993 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
2007 b'devel', b'check-locks'
1994 b'devel', b'check-locks'
2008 ):
1995 ):
2009 if self._currentlock(self._lockref) is None:
1996 if self._currentlock(self._lockref) is None:
2010 raise error.ProgrammingError(b'transaction requires locking')
1997 raise error.ProgrammingError(b'transaction requires locking')
2011 tr = self.currenttransaction()
1998 tr = self.currenttransaction()
2012 if tr is not None:
1999 if tr is not None:
2013 return tr.nest(name=desc)
2000 return tr.nest(name=desc)
2014
2001
2015 # abort here if the journal already exists
2002 # abort here if the journal already exists
2016 if self.svfs.exists(b"journal"):
2003 if self.svfs.exists(b"journal"):
2017 raise error.RepoError(
2004 raise error.RepoError(
2018 _(b"abandoned transaction found"),
2005 _(b"abandoned transaction found"),
2019 hint=_(b"run 'hg recover' to clean up transaction"),
2006 hint=_(b"run 'hg recover' to clean up transaction"),
2020 )
2007 )
2021
2008
2022 idbase = b"%.40f#%f" % (random.random(), time.time())
2009 idbase = b"%.40f#%f" % (random.random(), time.time())
2023 ha = hex(hashlib.sha1(idbase).digest())
2010 ha = hex(hashlib.sha1(idbase).digest())
2024 txnid = b'TXN:' + ha
2011 txnid = b'TXN:' + ha
2025 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2012 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2026
2013
2027 self._writejournal(desc)
2014 self._writejournal(desc)
2028 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2015 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2029 if report:
2016 if report:
2030 rp = report
2017 rp = report
2031 else:
2018 else:
2032 rp = self.ui.warn
2019 rp = self.ui.warn
2033 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2020 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2034 # we must avoid cyclic reference between repo and transaction.
2021 # we must avoid cyclic reference between repo and transaction.
2035 reporef = weakref.ref(self)
2022 reporef = weakref.ref(self)
2036 # Code to track tag movement
2023 # Code to track tag movement
2037 #
2024 #
2038 # Since tags are all handled as file content, it is actually quite hard
2025 # Since tags are all handled as file content, it is actually quite hard
2039 # to track these movement from a code perspective. So we fallback to a
2026 # to track these movement from a code perspective. So we fallback to a
2040 # tracking at the repository level. One could envision to track changes
2027 # tracking at the repository level. One could envision to track changes
2041 # to the '.hgtags' file through changegroup apply but that fails to
2028 # to the '.hgtags' file through changegroup apply but that fails to
2042 # cope with case where transaction expose new heads without changegroup
2029 # cope with case where transaction expose new heads without changegroup
2043 # being involved (eg: phase movement).
2030 # being involved (eg: phase movement).
2044 #
2031 #
2045 # For now, We gate the feature behind a flag since this likely comes
2032 # For now, We gate the feature behind a flag since this likely comes
2046 # with performance impacts. The current code run more often than needed
2033 # with performance impacts. The current code run more often than needed
2047 # and do not use caches as much as it could. The current focus is on
2034 # and do not use caches as much as it could. The current focus is on
2048 # the behavior of the feature so we disable it by default. The flag
2035 # the behavior of the feature so we disable it by default. The flag
2049 # will be removed when we are happy with the performance impact.
2036 # will be removed when we are happy with the performance impact.
2050 #
2037 #
2051 # Once this feature is no longer experimental move the following
2038 # Once this feature is no longer experimental move the following
2052 # documentation to the appropriate help section:
2039 # documentation to the appropriate help section:
2053 #
2040 #
2054 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2041 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2055 # tags (new or changed or deleted tags). In addition the details of
2042 # tags (new or changed or deleted tags). In addition the details of
2056 # these changes are made available in a file at:
2043 # these changes are made available in a file at:
2057 # ``REPOROOT/.hg/changes/tags.changes``.
2044 # ``REPOROOT/.hg/changes/tags.changes``.
2058 # Make sure you check for HG_TAG_MOVED before reading that file as it
2045 # Make sure you check for HG_TAG_MOVED before reading that file as it
2059 # might exist from a previous transaction even if no tag were touched
2046 # might exist from a previous transaction even if no tag were touched
2060 # in this one. Changes are recorded in a line base format::
2047 # in this one. Changes are recorded in a line base format::
2061 #
2048 #
2062 # <action> <hex-node> <tag-name>\n
2049 # <action> <hex-node> <tag-name>\n
2063 #
2050 #
2064 # Actions are defined as follow:
2051 # Actions are defined as follow:
2065 # "-R": tag is removed,
2052 # "-R": tag is removed,
2066 # "+A": tag is added,
2053 # "+A": tag is added,
2067 # "-M": tag is moved (old value),
2054 # "-M": tag is moved (old value),
2068 # "+M": tag is moved (new value),
2055 # "+M": tag is moved (new value),
2069 tracktags = lambda x: None
2056 tracktags = lambda x: None
2070 # experimental config: experimental.hook-track-tags
2057 # experimental config: experimental.hook-track-tags
2071 shouldtracktags = self.ui.configbool(
2058 shouldtracktags = self.ui.configbool(
2072 b'experimental', b'hook-track-tags'
2059 b'experimental', b'hook-track-tags'
2073 )
2060 )
2074 if desc != b'strip' and shouldtracktags:
2061 if desc != b'strip' and shouldtracktags:
2075 oldheads = self.changelog.headrevs()
2062 oldheads = self.changelog.headrevs()
2076
2063
2077 def tracktags(tr2):
2064 def tracktags(tr2):
2078 repo = reporef()
2065 repo = reporef()
2079 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2066 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2080 newheads = repo.changelog.headrevs()
2067 newheads = repo.changelog.headrevs()
2081 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2068 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2082 # notes: we compare lists here.
2069 # notes: we compare lists here.
2083 # As we do it only once buiding set would not be cheaper
2070 # As we do it only once buiding set would not be cheaper
2084 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2071 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2085 if changes:
2072 if changes:
2086 tr2.hookargs[b'tag_moved'] = b'1'
2073 tr2.hookargs[b'tag_moved'] = b'1'
2087 with repo.vfs(
2074 with repo.vfs(
2088 b'changes/tags.changes', b'w', atomictemp=True
2075 b'changes/tags.changes', b'w', atomictemp=True
2089 ) as changesfile:
2076 ) as changesfile:
2090 # note: we do not register the file to the transaction
2077 # note: we do not register the file to the transaction
2091 # because we needs it to still exist on the transaction
2078 # because we needs it to still exist on the transaction
2092 # is close (for txnclose hooks)
2079 # is close (for txnclose hooks)
2093 tagsmod.writediff(changesfile, changes)
2080 tagsmod.writediff(changesfile, changes)
2094
2081
2095 def validate(tr2):
2082 def validate(tr2):
2096 """will run pre-closing hooks"""
2083 """will run pre-closing hooks"""
2097 # XXX the transaction API is a bit lacking here so we take a hacky
2084 # XXX the transaction API is a bit lacking here so we take a hacky
2098 # path for now
2085 # path for now
2099 #
2086 #
2100 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2087 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2101 # dict is copied before these run. In addition we needs the data
2088 # dict is copied before these run. In addition we needs the data
2102 # available to in memory hooks too.
2089 # available to in memory hooks too.
2103 #
2090 #
2104 # Moreover, we also need to make sure this runs before txnclose
2091 # Moreover, we also need to make sure this runs before txnclose
2105 # hooks and there is no "pending" mechanism that would execute
2092 # hooks and there is no "pending" mechanism that would execute
2106 # logic only if hooks are about to run.
2093 # logic only if hooks are about to run.
2107 #
2094 #
2108 # Fixing this limitation of the transaction is also needed to track
2095 # Fixing this limitation of the transaction is also needed to track
2109 # other families of changes (bookmarks, phases, obsolescence).
2096 # other families of changes (bookmarks, phases, obsolescence).
2110 #
2097 #
2111 # This will have to be fixed before we remove the experimental
2098 # This will have to be fixed before we remove the experimental
2112 # gating.
2099 # gating.
2113 tracktags(tr2)
2100 tracktags(tr2)
2114 repo = reporef()
2101 repo = reporef()
2115
2102
2116 singleheadopt = (b'experimental', b'single-head-per-branch')
2103 singleheadopt = (b'experimental', b'single-head-per-branch')
2117 singlehead = repo.ui.configbool(*singleheadopt)
2104 singlehead = repo.ui.configbool(*singleheadopt)
2118 if singlehead:
2105 if singlehead:
2119 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2106 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2120 accountclosed = singleheadsub.get(
2107 accountclosed = singleheadsub.get(
2121 b"account-closed-heads", False
2108 b"account-closed-heads", False
2122 )
2109 )
2123 scmutil.enforcesinglehead(repo, tr2, desc, accountclosed)
2110 scmutil.enforcesinglehead(repo, tr2, desc, accountclosed)
2124 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2111 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2125 for name, (old, new) in sorted(
2112 for name, (old, new) in sorted(
2126 tr.changes[b'bookmarks'].items()
2113 tr.changes[b'bookmarks'].items()
2127 ):
2114 ):
2128 args = tr.hookargs.copy()
2115 args = tr.hookargs.copy()
2129 args.update(bookmarks.preparehookargs(name, old, new))
2116 args.update(bookmarks.preparehookargs(name, old, new))
2130 repo.hook(
2117 repo.hook(
2131 b'pretxnclose-bookmark',
2118 b'pretxnclose-bookmark',
2132 throw=True,
2119 throw=True,
2133 **pycompat.strkwargs(args)
2120 **pycompat.strkwargs(args)
2134 )
2121 )
2135 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2122 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2136 cl = repo.unfiltered().changelog
2123 cl = repo.unfiltered().changelog
2137 for rev, (old, new) in tr.changes[b'phases'].items():
2124 for rev, (old, new) in tr.changes[b'phases'].items():
2138 args = tr.hookargs.copy()
2125 args = tr.hookargs.copy()
2139 node = hex(cl.node(rev))
2126 node = hex(cl.node(rev))
2140 args.update(phases.preparehookargs(node, old, new))
2127 args.update(phases.preparehookargs(node, old, new))
2141 repo.hook(
2128 repo.hook(
2142 b'pretxnclose-phase',
2129 b'pretxnclose-phase',
2143 throw=True,
2130 throw=True,
2144 **pycompat.strkwargs(args)
2131 **pycompat.strkwargs(args)
2145 )
2132 )
2146
2133
2147 repo.hook(
2134 repo.hook(
2148 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2135 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2149 )
2136 )
2150
2137
2151 def releasefn(tr, success):
2138 def releasefn(tr, success):
2152 repo = reporef()
2139 repo = reporef()
2153 if repo is None:
2140 if repo is None:
2154 # If the repo has been GC'd (and this release function is being
2141 # If the repo has been GC'd (and this release function is being
2155 # called from transaction.__del__), there's not much we can do,
2142 # called from transaction.__del__), there's not much we can do,
2156 # so just leave the unfinished transaction there and let the
2143 # so just leave the unfinished transaction there and let the
2157 # user run `hg recover`.
2144 # user run `hg recover`.
2158 return
2145 return
2159 if success:
2146 if success:
2160 # this should be explicitly invoked here, because
2147 # this should be explicitly invoked here, because
2161 # in-memory changes aren't written out at closing
2148 # in-memory changes aren't written out at closing
2162 # transaction, if tr.addfilegenerator (via
2149 # transaction, if tr.addfilegenerator (via
2163 # dirstate.write or so) isn't invoked while
2150 # dirstate.write or so) isn't invoked while
2164 # transaction running
2151 # transaction running
2165 repo.dirstate.write(None)
2152 repo.dirstate.write(None)
2166 else:
2153 else:
2167 # discard all changes (including ones already written
2154 # discard all changes (including ones already written
2168 # out) in this transaction
2155 # out) in this transaction
2169 narrowspec.restorebackup(self, b'journal.narrowspec')
2156 narrowspec.restorebackup(self, b'journal.narrowspec')
2170 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2157 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2171 repo.dirstate.restorebackup(None, b'journal.dirstate')
2158 repo.dirstate.restorebackup(None, b'journal.dirstate')
2172
2159
2173 repo.invalidate(clearfilecache=True)
2160 repo.invalidate(clearfilecache=True)
2174
2161
2175 tr = transaction.transaction(
2162 tr = transaction.transaction(
2176 rp,
2163 rp,
2177 self.svfs,
2164 self.svfs,
2178 vfsmap,
2165 vfsmap,
2179 b"journal",
2166 b"journal",
2180 b"undo",
2167 b"undo",
2181 aftertrans(renames),
2168 aftertrans(renames),
2182 self.store.createmode,
2169 self.store.createmode,
2183 validator=validate,
2170 validator=validate,
2184 releasefn=releasefn,
2171 releasefn=releasefn,
2185 checkambigfiles=_cachedfiles,
2172 checkambigfiles=_cachedfiles,
2186 name=desc,
2173 name=desc,
2187 )
2174 )
2188 tr.changes[b'origrepolen'] = len(self)
2175 tr.changes[b'origrepolen'] = len(self)
2189 tr.changes[b'obsmarkers'] = set()
2176 tr.changes[b'obsmarkers'] = set()
2190 tr.changes[b'phases'] = {}
2177 tr.changes[b'phases'] = {}
2191 tr.changes[b'bookmarks'] = {}
2178 tr.changes[b'bookmarks'] = {}
2192
2179
2193 tr.hookargs[b'txnid'] = txnid
2180 tr.hookargs[b'txnid'] = txnid
2194 tr.hookargs[b'txnname'] = desc
2181 tr.hookargs[b'txnname'] = desc
2195 # note: writing the fncache only during finalize mean that the file is
2182 # note: writing the fncache only during finalize mean that the file is
2196 # outdated when running hooks. As fncache is used for streaming clone,
2183 # outdated when running hooks. As fncache is used for streaming clone,
2197 # this is not expected to break anything that happen during the hooks.
2184 # this is not expected to break anything that happen during the hooks.
2198 tr.addfinalize(b'flush-fncache', self.store.write)
2185 tr.addfinalize(b'flush-fncache', self.store.write)
2199
2186
2200 def txnclosehook(tr2):
2187 def txnclosehook(tr2):
2201 """To be run if transaction is successful, will schedule a hook run
2188 """To be run if transaction is successful, will schedule a hook run
2202 """
2189 """
2203 # Don't reference tr2 in hook() so we don't hold a reference.
2190 # Don't reference tr2 in hook() so we don't hold a reference.
2204 # This reduces memory consumption when there are multiple
2191 # This reduces memory consumption when there are multiple
2205 # transactions per lock. This can likely go away if issue5045
2192 # transactions per lock. This can likely go away if issue5045
2206 # fixes the function accumulation.
2193 # fixes the function accumulation.
2207 hookargs = tr2.hookargs
2194 hookargs = tr2.hookargs
2208
2195
2209 def hookfunc(unused_success):
2196 def hookfunc(unused_success):
2210 repo = reporef()
2197 repo = reporef()
2211 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2198 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2212 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2199 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2213 for name, (old, new) in bmchanges:
2200 for name, (old, new) in bmchanges:
2214 args = tr.hookargs.copy()
2201 args = tr.hookargs.copy()
2215 args.update(bookmarks.preparehookargs(name, old, new))
2202 args.update(bookmarks.preparehookargs(name, old, new))
2216 repo.hook(
2203 repo.hook(
2217 b'txnclose-bookmark',
2204 b'txnclose-bookmark',
2218 throw=False,
2205 throw=False,
2219 **pycompat.strkwargs(args)
2206 **pycompat.strkwargs(args)
2220 )
2207 )
2221
2208
2222 if hook.hashook(repo.ui, b'txnclose-phase'):
2209 if hook.hashook(repo.ui, b'txnclose-phase'):
2223 cl = repo.unfiltered().changelog
2210 cl = repo.unfiltered().changelog
2224 phasemv = sorted(tr.changes[b'phases'].items())
2211 phasemv = sorted(tr.changes[b'phases'].items())
2225 for rev, (old, new) in phasemv:
2212 for rev, (old, new) in phasemv:
2226 args = tr.hookargs.copy()
2213 args = tr.hookargs.copy()
2227 node = hex(cl.node(rev))
2214 node = hex(cl.node(rev))
2228 args.update(phases.preparehookargs(node, old, new))
2215 args.update(phases.preparehookargs(node, old, new))
2229 repo.hook(
2216 repo.hook(
2230 b'txnclose-phase',
2217 b'txnclose-phase',
2231 throw=False,
2218 throw=False,
2232 **pycompat.strkwargs(args)
2219 **pycompat.strkwargs(args)
2233 )
2220 )
2234
2221
2235 repo.hook(
2222 repo.hook(
2236 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2223 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2237 )
2224 )
2238
2225
2239 reporef()._afterlock(hookfunc)
2226 reporef()._afterlock(hookfunc)
2240
2227
2241 tr.addfinalize(b'txnclose-hook', txnclosehook)
2228 tr.addfinalize(b'txnclose-hook', txnclosehook)
2242 # Include a leading "-" to make it happen before the transaction summary
2229 # Include a leading "-" to make it happen before the transaction summary
2243 # reports registered via scmutil.registersummarycallback() whose names
2230 # reports registered via scmutil.registersummarycallback() whose names
2244 # are 00-txnreport etc. That way, the caches will be warm when the
2231 # are 00-txnreport etc. That way, the caches will be warm when the
2245 # callbacks run.
2232 # callbacks run.
2246 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2233 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2247
2234
2248 def txnaborthook(tr2):
2235 def txnaborthook(tr2):
2249 """To be run if transaction is aborted
2236 """To be run if transaction is aborted
2250 """
2237 """
2251 reporef().hook(
2238 reporef().hook(
2252 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2239 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2253 )
2240 )
2254
2241
2255 tr.addabort(b'txnabort-hook', txnaborthook)
2242 tr.addabort(b'txnabort-hook', txnaborthook)
2256 # avoid eager cache invalidation. in-memory data should be identical
2243 # avoid eager cache invalidation. in-memory data should be identical
2257 # to stored data if transaction has no error.
2244 # to stored data if transaction has no error.
2258 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2245 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2259 self._transref = weakref.ref(tr)
2246 self._transref = weakref.ref(tr)
2260 scmutil.registersummarycallback(self, tr, desc)
2247 scmutil.registersummarycallback(self, tr, desc)
2261 return tr
2248 return tr
2262
2249
2263 def _journalfiles(self):
2250 def _journalfiles(self):
2264 return (
2251 return (
2265 (self.svfs, b'journal'),
2252 (self.svfs, b'journal'),
2266 (self.svfs, b'journal.narrowspec'),
2253 (self.svfs, b'journal.narrowspec'),
2267 (self.vfs, b'journal.narrowspec.dirstate'),
2254 (self.vfs, b'journal.narrowspec.dirstate'),
2268 (self.vfs, b'journal.dirstate'),
2255 (self.vfs, b'journal.dirstate'),
2269 (self.vfs, b'journal.branch'),
2256 (self.vfs, b'journal.branch'),
2270 (self.vfs, b'journal.desc'),
2257 (self.vfs, b'journal.desc'),
2271 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2258 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2272 (self.svfs, b'journal.phaseroots'),
2259 (self.svfs, b'journal.phaseroots'),
2273 )
2260 )
2274
2261
2275 def undofiles(self):
2262 def undofiles(self):
2276 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2263 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2277
2264
2278 @unfilteredmethod
2265 @unfilteredmethod
2279 def _writejournal(self, desc):
2266 def _writejournal(self, desc):
2280 self.dirstate.savebackup(None, b'journal.dirstate')
2267 self.dirstate.savebackup(None, b'journal.dirstate')
2281 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2268 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2282 narrowspec.savebackup(self, b'journal.narrowspec')
2269 narrowspec.savebackup(self, b'journal.narrowspec')
2283 self.vfs.write(
2270 self.vfs.write(
2284 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2271 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2285 )
2272 )
2286 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2273 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2287 bookmarksvfs = bookmarks.bookmarksvfs(self)
2274 bookmarksvfs = bookmarks.bookmarksvfs(self)
2288 bookmarksvfs.write(
2275 bookmarksvfs.write(
2289 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2276 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2290 )
2277 )
2291 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2278 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2292
2279
2293 def recover(self):
2280 def recover(self):
2294 with self.lock():
2281 with self.lock():
2295 if self.svfs.exists(b"journal"):
2282 if self.svfs.exists(b"journal"):
2296 self.ui.status(_(b"rolling back interrupted transaction\n"))
2283 self.ui.status(_(b"rolling back interrupted transaction\n"))
2297 vfsmap = {
2284 vfsmap = {
2298 b'': self.svfs,
2285 b'': self.svfs,
2299 b'plain': self.vfs,
2286 b'plain': self.vfs,
2300 }
2287 }
2301 transaction.rollback(
2288 transaction.rollback(
2302 self.svfs,
2289 self.svfs,
2303 vfsmap,
2290 vfsmap,
2304 b"journal",
2291 b"journal",
2305 self.ui.warn,
2292 self.ui.warn,
2306 checkambigfiles=_cachedfiles,
2293 checkambigfiles=_cachedfiles,
2307 )
2294 )
2308 self.invalidate()
2295 self.invalidate()
2309 return True
2296 return True
2310 else:
2297 else:
2311 self.ui.warn(_(b"no interrupted transaction available\n"))
2298 self.ui.warn(_(b"no interrupted transaction available\n"))
2312 return False
2299 return False
2313
2300
2314 def rollback(self, dryrun=False, force=False):
2301 def rollback(self, dryrun=False, force=False):
2315 wlock = lock = dsguard = None
2302 wlock = lock = dsguard = None
2316 try:
2303 try:
2317 wlock = self.wlock()
2304 wlock = self.wlock()
2318 lock = self.lock()
2305 lock = self.lock()
2319 if self.svfs.exists(b"undo"):
2306 if self.svfs.exists(b"undo"):
2320 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2307 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2321
2308
2322 return self._rollback(dryrun, force, dsguard)
2309 return self._rollback(dryrun, force, dsguard)
2323 else:
2310 else:
2324 self.ui.warn(_(b"no rollback information available\n"))
2311 self.ui.warn(_(b"no rollback information available\n"))
2325 return 1
2312 return 1
2326 finally:
2313 finally:
2327 release(dsguard, lock, wlock)
2314 release(dsguard, lock, wlock)
2328
2315
2329 @unfilteredmethod # Until we get smarter cache management
2316 @unfilteredmethod # Until we get smarter cache management
2330 def _rollback(self, dryrun, force, dsguard):
2317 def _rollback(self, dryrun, force, dsguard):
2331 ui = self.ui
2318 ui = self.ui
2332 try:
2319 try:
2333 args = self.vfs.read(b'undo.desc').splitlines()
2320 args = self.vfs.read(b'undo.desc').splitlines()
2334 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2321 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2335 if len(args) >= 3:
2322 if len(args) >= 3:
2336 detail = args[2]
2323 detail = args[2]
2337 oldtip = oldlen - 1
2324 oldtip = oldlen - 1
2338
2325
2339 if detail and ui.verbose:
2326 if detail and ui.verbose:
2340 msg = _(
2327 msg = _(
2341 b'repository tip rolled back to revision %d'
2328 b'repository tip rolled back to revision %d'
2342 b' (undo %s: %s)\n'
2329 b' (undo %s: %s)\n'
2343 ) % (oldtip, desc, detail)
2330 ) % (oldtip, desc, detail)
2344 else:
2331 else:
2345 msg = _(
2332 msg = _(
2346 b'repository tip rolled back to revision %d (undo %s)\n'
2333 b'repository tip rolled back to revision %d (undo %s)\n'
2347 ) % (oldtip, desc)
2334 ) % (oldtip, desc)
2348 except IOError:
2335 except IOError:
2349 msg = _(b'rolling back unknown transaction\n')
2336 msg = _(b'rolling back unknown transaction\n')
2350 desc = None
2337 desc = None
2351
2338
2352 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2339 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2353 raise error.Abort(
2340 raise error.Abort(
2354 _(
2341 _(
2355 b'rollback of last commit while not checked out '
2342 b'rollback of last commit while not checked out '
2356 b'may lose data'
2343 b'may lose data'
2357 ),
2344 ),
2358 hint=_(b'use -f to force'),
2345 hint=_(b'use -f to force'),
2359 )
2346 )
2360
2347
2361 ui.status(msg)
2348 ui.status(msg)
2362 if dryrun:
2349 if dryrun:
2363 return 0
2350 return 0
2364
2351
2365 parents = self.dirstate.parents()
2352 parents = self.dirstate.parents()
2366 self.destroying()
2353 self.destroying()
2367 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2354 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2368 transaction.rollback(
2355 transaction.rollback(
2369 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2356 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2370 )
2357 )
2371 bookmarksvfs = bookmarks.bookmarksvfs(self)
2358 bookmarksvfs = bookmarks.bookmarksvfs(self)
2372 if bookmarksvfs.exists(b'undo.bookmarks'):
2359 if bookmarksvfs.exists(b'undo.bookmarks'):
2373 bookmarksvfs.rename(
2360 bookmarksvfs.rename(
2374 b'undo.bookmarks', b'bookmarks', checkambig=True
2361 b'undo.bookmarks', b'bookmarks', checkambig=True
2375 )
2362 )
2376 if self.svfs.exists(b'undo.phaseroots'):
2363 if self.svfs.exists(b'undo.phaseroots'):
2377 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2364 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2378 self.invalidate()
2365 self.invalidate()
2379
2366
2380 has_node = self.changelog.index.has_node
2367 has_node = self.changelog.index.has_node
2381 parentgone = any(not has_node(p) for p in parents)
2368 parentgone = any(not has_node(p) for p in parents)
2382 if parentgone:
2369 if parentgone:
2383 # prevent dirstateguard from overwriting already restored one
2370 # prevent dirstateguard from overwriting already restored one
2384 dsguard.close()
2371 dsguard.close()
2385
2372
2386 narrowspec.restorebackup(self, b'undo.narrowspec')
2373 narrowspec.restorebackup(self, b'undo.narrowspec')
2387 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2374 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2388 self.dirstate.restorebackup(None, b'undo.dirstate')
2375 self.dirstate.restorebackup(None, b'undo.dirstate')
2389 try:
2376 try:
2390 branch = self.vfs.read(b'undo.branch')
2377 branch = self.vfs.read(b'undo.branch')
2391 self.dirstate.setbranch(encoding.tolocal(branch))
2378 self.dirstate.setbranch(encoding.tolocal(branch))
2392 except IOError:
2379 except IOError:
2393 ui.warn(
2380 ui.warn(
2394 _(
2381 _(
2395 b'named branch could not be reset: '
2382 b'named branch could not be reset: '
2396 b'current branch is still \'%s\'\n'
2383 b'current branch is still \'%s\'\n'
2397 )
2384 )
2398 % self.dirstate.branch()
2385 % self.dirstate.branch()
2399 )
2386 )
2400
2387
2401 parents = tuple([p.rev() for p in self[None].parents()])
2388 parents = tuple([p.rev() for p in self[None].parents()])
2402 if len(parents) > 1:
2389 if len(parents) > 1:
2403 ui.status(
2390 ui.status(
2404 _(
2391 _(
2405 b'working directory now based on '
2392 b'working directory now based on '
2406 b'revisions %d and %d\n'
2393 b'revisions %d and %d\n'
2407 )
2394 )
2408 % parents
2395 % parents
2409 )
2396 )
2410 else:
2397 else:
2411 ui.status(
2398 ui.status(
2412 _(b'working directory now based on revision %d\n') % parents
2399 _(b'working directory now based on revision %d\n') % parents
2413 )
2400 )
2414 mergemod.mergestate.clean(self, self[b'.'].node())
2401 mergemod.mergestate.clean(self, self[b'.'].node())
2415
2402
2416 # TODO: if we know which new heads may result from this rollback, pass
2403 # TODO: if we know which new heads may result from this rollback, pass
2417 # them to destroy(), which will prevent the branchhead cache from being
2404 # them to destroy(), which will prevent the branchhead cache from being
2418 # invalidated.
2405 # invalidated.
2419 self.destroyed()
2406 self.destroyed()
2420 return 0
2407 return 0
2421
2408
2422 def _buildcacheupdater(self, newtransaction):
2409 def _buildcacheupdater(self, newtransaction):
2423 """called during transaction to build the callback updating cache
2410 """called during transaction to build the callback updating cache
2424
2411
2425 Lives on the repository to help extension who might want to augment
2412 Lives on the repository to help extension who might want to augment
2426 this logic. For this purpose, the created transaction is passed to the
2413 this logic. For this purpose, the created transaction is passed to the
2427 method.
2414 method.
2428 """
2415 """
2429 # we must avoid cyclic reference between repo and transaction.
2416 # we must avoid cyclic reference between repo and transaction.
2430 reporef = weakref.ref(self)
2417 reporef = weakref.ref(self)
2431
2418
2432 def updater(tr):
2419 def updater(tr):
2433 repo = reporef()
2420 repo = reporef()
2434 repo.updatecaches(tr)
2421 repo.updatecaches(tr)
2435
2422
2436 return updater
2423 return updater
2437
2424
2438 @unfilteredmethod
2425 @unfilteredmethod
2439 def updatecaches(self, tr=None, full=False):
2426 def updatecaches(self, tr=None, full=False):
2440 """warm appropriate caches
2427 """warm appropriate caches
2441
2428
2442 If this function is called after a transaction closed. The transaction
2429 If this function is called after a transaction closed. The transaction
2443 will be available in the 'tr' argument. This can be used to selectively
2430 will be available in the 'tr' argument. This can be used to selectively
2444 update caches relevant to the changes in that transaction.
2431 update caches relevant to the changes in that transaction.
2445
2432
2446 If 'full' is set, make sure all caches the function knows about have
2433 If 'full' is set, make sure all caches the function knows about have
2447 up-to-date data. Even the ones usually loaded more lazily.
2434 up-to-date data. Even the ones usually loaded more lazily.
2448 """
2435 """
2449 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2436 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2450 # During strip, many caches are invalid but
2437 # During strip, many caches are invalid but
2451 # later call to `destroyed` will refresh them.
2438 # later call to `destroyed` will refresh them.
2452 return
2439 return
2453
2440
2454 if tr is None or tr.changes[b'origrepolen'] < len(self):
2441 if tr is None or tr.changes[b'origrepolen'] < len(self):
2455 # accessing the 'ser ved' branchmap should refresh all the others,
2442 # accessing the 'ser ved' branchmap should refresh all the others,
2456 self.ui.debug(b'updating the branch cache\n')
2443 self.ui.debug(b'updating the branch cache\n')
2457 self.filtered(b'served').branchmap()
2444 self.filtered(b'served').branchmap()
2458 self.filtered(b'served.hidden').branchmap()
2445 self.filtered(b'served.hidden').branchmap()
2459
2446
2460 if full:
2447 if full:
2461 unfi = self.unfiltered()
2448 unfi = self.unfiltered()
2462 rbc = unfi.revbranchcache()
2449 rbc = unfi.revbranchcache()
2463 for r in unfi.changelog:
2450 for r in unfi.changelog:
2464 rbc.branchinfo(r)
2451 rbc.branchinfo(r)
2465 rbc.write()
2452 rbc.write()
2466
2453
2467 # ensure the working copy parents are in the manifestfulltextcache
2454 # ensure the working copy parents are in the manifestfulltextcache
2468 for ctx in self[b'.'].parents():
2455 for ctx in self[b'.'].parents():
2469 ctx.manifest() # accessing the manifest is enough
2456 ctx.manifest() # accessing the manifest is enough
2470
2457
2471 # accessing fnode cache warms the cache
2458 # accessing fnode cache warms the cache
2472 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2459 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2473 # accessing tags warm the cache
2460 # accessing tags warm the cache
2474 self.tags()
2461 self.tags()
2475 self.filtered(b'served').tags()
2462 self.filtered(b'served').tags()
2476
2463
2477 # The `full` arg is documented as updating even the lazily-loaded
2464 # The `full` arg is documented as updating even the lazily-loaded
2478 # caches immediately, so we're forcing a write to cause these caches
2465 # caches immediately, so we're forcing a write to cause these caches
2479 # to be warmed up even if they haven't explicitly been requested
2466 # to be warmed up even if they haven't explicitly been requested
2480 # yet (if they've never been used by hg, they won't ever have been
2467 # yet (if they've never been used by hg, they won't ever have been
2481 # written, even if they're a subset of another kind of cache that
2468 # written, even if they're a subset of another kind of cache that
2482 # *has* been used).
2469 # *has* been used).
2483 for filt in repoview.filtertable.keys():
2470 for filt in repoview.filtertable.keys():
2484 filtered = self.filtered(filt)
2471 filtered = self.filtered(filt)
2485 filtered.branchmap().write(filtered)
2472 filtered.branchmap().write(filtered)
2486
2473
2487 def invalidatecaches(self):
2474 def invalidatecaches(self):
2488
2475
2489 if '_tagscache' in vars(self):
2476 if '_tagscache' in vars(self):
2490 # can't use delattr on proxy
2477 # can't use delattr on proxy
2491 del self.__dict__['_tagscache']
2478 del self.__dict__['_tagscache']
2492
2479
2493 self._branchcaches.clear()
2480 self._branchcaches.clear()
2494 self.invalidatevolatilesets()
2481 self.invalidatevolatilesets()
2495 self._sparsesignaturecache.clear()
2482 self._sparsesignaturecache.clear()
2496
2483
2497 def invalidatevolatilesets(self):
2484 def invalidatevolatilesets(self):
2498 self.filteredrevcache.clear()
2485 self.filteredrevcache.clear()
2499 obsolete.clearobscaches(self)
2486 obsolete.clearobscaches(self)
2500
2487
2501 def invalidatedirstate(self):
2488 def invalidatedirstate(self):
2502 '''Invalidates the dirstate, causing the next call to dirstate
2489 '''Invalidates the dirstate, causing the next call to dirstate
2503 to check if it was modified since the last time it was read,
2490 to check if it was modified since the last time it was read,
2504 rereading it if it has.
2491 rereading it if it has.
2505
2492
2506 This is different to dirstate.invalidate() that it doesn't always
2493 This is different to dirstate.invalidate() that it doesn't always
2507 rereads the dirstate. Use dirstate.invalidate() if you want to
2494 rereads the dirstate. Use dirstate.invalidate() if you want to
2508 explicitly read the dirstate again (i.e. restoring it to a previous
2495 explicitly read the dirstate again (i.e. restoring it to a previous
2509 known good state).'''
2496 known good state).'''
2510 if hasunfilteredcache(self, 'dirstate'):
2497 if hasunfilteredcache(self, 'dirstate'):
2511 for k in self.dirstate._filecache:
2498 for k in self.dirstate._filecache:
2512 try:
2499 try:
2513 delattr(self.dirstate, k)
2500 delattr(self.dirstate, k)
2514 except AttributeError:
2501 except AttributeError:
2515 pass
2502 pass
2516 delattr(self.unfiltered(), 'dirstate')
2503 delattr(self.unfiltered(), 'dirstate')
2517
2504
2518 def invalidate(self, clearfilecache=False):
2505 def invalidate(self, clearfilecache=False):
2519 '''Invalidates both store and non-store parts other than dirstate
2506 '''Invalidates both store and non-store parts other than dirstate
2520
2507
2521 If a transaction is running, invalidation of store is omitted,
2508 If a transaction is running, invalidation of store is omitted,
2522 because discarding in-memory changes might cause inconsistency
2509 because discarding in-memory changes might cause inconsistency
2523 (e.g. incomplete fncache causes unintentional failure, but
2510 (e.g. incomplete fncache causes unintentional failure, but
2524 redundant one doesn't).
2511 redundant one doesn't).
2525 '''
2512 '''
2526 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2513 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2527 for k in list(self._filecache.keys()):
2514 for k in list(self._filecache.keys()):
2528 # dirstate is invalidated separately in invalidatedirstate()
2515 # dirstate is invalidated separately in invalidatedirstate()
2529 if k == b'dirstate':
2516 if k == b'dirstate':
2530 continue
2517 continue
2531 if (
2518 if (
2532 k == b'changelog'
2519 k == b'changelog'
2533 and self.currenttransaction()
2520 and self.currenttransaction()
2534 and self.changelog._delayed
2521 and self.changelog._delayed
2535 ):
2522 ):
2536 # The changelog object may store unwritten revisions. We don't
2523 # The changelog object may store unwritten revisions. We don't
2537 # want to lose them.
2524 # want to lose them.
2538 # TODO: Solve the problem instead of working around it.
2525 # TODO: Solve the problem instead of working around it.
2539 continue
2526 continue
2540
2527
2541 if clearfilecache:
2528 if clearfilecache:
2542 del self._filecache[k]
2529 del self._filecache[k]
2543 try:
2530 try:
2544 delattr(unfiltered, k)
2531 delattr(unfiltered, k)
2545 except AttributeError:
2532 except AttributeError:
2546 pass
2533 pass
2547 self.invalidatecaches()
2534 self.invalidatecaches()
2548 if not self.currenttransaction():
2535 if not self.currenttransaction():
2549 # TODO: Changing contents of store outside transaction
2536 # TODO: Changing contents of store outside transaction
2550 # causes inconsistency. We should make in-memory store
2537 # causes inconsistency. We should make in-memory store
2551 # changes detectable, and abort if changed.
2538 # changes detectable, and abort if changed.
2552 self.store.invalidatecaches()
2539 self.store.invalidatecaches()
2553
2540
2554 def invalidateall(self):
2541 def invalidateall(self):
2555 '''Fully invalidates both store and non-store parts, causing the
2542 '''Fully invalidates both store and non-store parts, causing the
2556 subsequent operation to reread any outside changes.'''
2543 subsequent operation to reread any outside changes.'''
2557 # extension should hook this to invalidate its caches
2544 # extension should hook this to invalidate its caches
2558 self.invalidate()
2545 self.invalidate()
2559 self.invalidatedirstate()
2546 self.invalidatedirstate()
2560
2547
2561 @unfilteredmethod
2548 @unfilteredmethod
2562 def _refreshfilecachestats(self, tr):
2549 def _refreshfilecachestats(self, tr):
2563 """Reload stats of cached files so that they are flagged as valid"""
2550 """Reload stats of cached files so that they are flagged as valid"""
2564 for k, ce in self._filecache.items():
2551 for k, ce in self._filecache.items():
2565 k = pycompat.sysstr(k)
2552 k = pycompat.sysstr(k)
2566 if k == 'dirstate' or k not in self.__dict__:
2553 if k == 'dirstate' or k not in self.__dict__:
2567 continue
2554 continue
2568 ce.refresh()
2555 ce.refresh()
2569
2556
2570 def _lock(
2557 def _lock(
2571 self,
2558 self,
2572 vfs,
2559 vfs,
2573 lockname,
2560 lockname,
2574 wait,
2561 wait,
2575 releasefn,
2562 releasefn,
2576 acquirefn,
2563 acquirefn,
2577 desc,
2564 desc,
2578 inheritchecker=None,
2565 inheritchecker=None,
2579 parentenvvar=None,
2566 parentenvvar=None,
2580 ):
2567 ):
2581 parentlock = None
2568 parentlock = None
2582 # the contents of parentenvvar are used by the underlying lock to
2569 # the contents of parentenvvar are used by the underlying lock to
2583 # determine whether it can be inherited
2570 # determine whether it can be inherited
2584 if parentenvvar is not None:
2571 if parentenvvar is not None:
2585 parentlock = encoding.environ.get(parentenvvar)
2572 parentlock = encoding.environ.get(parentenvvar)
2586
2573
2587 timeout = 0
2574 timeout = 0
2588 warntimeout = 0
2575 warntimeout = 0
2589 if wait:
2576 if wait:
2590 timeout = self.ui.configint(b"ui", b"timeout")
2577 timeout = self.ui.configint(b"ui", b"timeout")
2591 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2578 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2592 # internal config: ui.signal-safe-lock
2579 # internal config: ui.signal-safe-lock
2593 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2580 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2594
2581
2595 l = lockmod.trylock(
2582 l = lockmod.trylock(
2596 self.ui,
2583 self.ui,
2597 vfs,
2584 vfs,
2598 lockname,
2585 lockname,
2599 timeout,
2586 timeout,
2600 warntimeout,
2587 warntimeout,
2601 releasefn=releasefn,
2588 releasefn=releasefn,
2602 acquirefn=acquirefn,
2589 acquirefn=acquirefn,
2603 desc=desc,
2590 desc=desc,
2604 inheritchecker=inheritchecker,
2591 inheritchecker=inheritchecker,
2605 parentlock=parentlock,
2592 parentlock=parentlock,
2606 signalsafe=signalsafe,
2593 signalsafe=signalsafe,
2607 )
2594 )
2608 return l
2595 return l
2609
2596
2610 def _afterlock(self, callback):
2597 def _afterlock(self, callback):
2611 """add a callback to be run when the repository is fully unlocked
2598 """add a callback to be run when the repository is fully unlocked
2612
2599
2613 The callback will be executed when the outermost lock is released
2600 The callback will be executed when the outermost lock is released
2614 (with wlock being higher level than 'lock')."""
2601 (with wlock being higher level than 'lock')."""
2615 for ref in (self._wlockref, self._lockref):
2602 for ref in (self._wlockref, self._lockref):
2616 l = ref and ref()
2603 l = ref and ref()
2617 if l and l.held:
2604 if l and l.held:
2618 l.postrelease.append(callback)
2605 l.postrelease.append(callback)
2619 break
2606 break
2620 else: # no lock have been found.
2607 else: # no lock have been found.
2621 callback(True)
2608 callback(True)
2622
2609
2623 def lock(self, wait=True):
2610 def lock(self, wait=True):
2624 '''Lock the repository store (.hg/store) and return a weak reference
2611 '''Lock the repository store (.hg/store) and return a weak reference
2625 to the lock. Use this before modifying the store (e.g. committing or
2612 to the lock. Use this before modifying the store (e.g. committing or
2626 stripping). If you are opening a transaction, get a lock as well.)
2613 stripping). If you are opening a transaction, get a lock as well.)
2627
2614
2628 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2615 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2629 'wlock' first to avoid a dead-lock hazard.'''
2616 'wlock' first to avoid a dead-lock hazard.'''
2630 l = self._currentlock(self._lockref)
2617 l = self._currentlock(self._lockref)
2631 if l is not None:
2618 if l is not None:
2632 l.lock()
2619 l.lock()
2633 return l
2620 return l
2634
2621
2635 l = self._lock(
2622 l = self._lock(
2636 vfs=self.svfs,
2623 vfs=self.svfs,
2637 lockname=b"lock",
2624 lockname=b"lock",
2638 wait=wait,
2625 wait=wait,
2639 releasefn=None,
2626 releasefn=None,
2640 acquirefn=self.invalidate,
2627 acquirefn=self.invalidate,
2641 desc=_(b'repository %s') % self.origroot,
2628 desc=_(b'repository %s') % self.origroot,
2642 )
2629 )
2643 self._lockref = weakref.ref(l)
2630 self._lockref = weakref.ref(l)
2644 return l
2631 return l
2645
2632
2646 def _wlockchecktransaction(self):
2633 def _wlockchecktransaction(self):
2647 if self.currenttransaction() is not None:
2634 if self.currenttransaction() is not None:
2648 raise error.LockInheritanceContractViolation(
2635 raise error.LockInheritanceContractViolation(
2649 b'wlock cannot be inherited in the middle of a transaction'
2636 b'wlock cannot be inherited in the middle of a transaction'
2650 )
2637 )
2651
2638
2652 def wlock(self, wait=True):
2639 def wlock(self, wait=True):
2653 '''Lock the non-store parts of the repository (everything under
2640 '''Lock the non-store parts of the repository (everything under
2654 .hg except .hg/store) and return a weak reference to the lock.
2641 .hg except .hg/store) and return a weak reference to the lock.
2655
2642
2656 Use this before modifying files in .hg.
2643 Use this before modifying files in .hg.
2657
2644
2658 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2645 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2659 'wlock' first to avoid a dead-lock hazard.'''
2646 'wlock' first to avoid a dead-lock hazard.'''
2660 l = self._wlockref and self._wlockref()
2647 l = self._wlockref and self._wlockref()
2661 if l is not None and l.held:
2648 if l is not None and l.held:
2662 l.lock()
2649 l.lock()
2663 return l
2650 return l
2664
2651
2665 # We do not need to check for non-waiting lock acquisition. Such
2652 # We do not need to check for non-waiting lock acquisition. Such
2666 # acquisition would not cause dead-lock as they would just fail.
2653 # acquisition would not cause dead-lock as they would just fail.
2667 if wait and (
2654 if wait and (
2668 self.ui.configbool(b'devel', b'all-warnings')
2655 self.ui.configbool(b'devel', b'all-warnings')
2669 or self.ui.configbool(b'devel', b'check-locks')
2656 or self.ui.configbool(b'devel', b'check-locks')
2670 ):
2657 ):
2671 if self._currentlock(self._lockref) is not None:
2658 if self._currentlock(self._lockref) is not None:
2672 self.ui.develwarn(b'"wlock" acquired after "lock"')
2659 self.ui.develwarn(b'"wlock" acquired after "lock"')
2673
2660
2674 def unlock():
2661 def unlock():
2675 if self.dirstate.pendingparentchange():
2662 if self.dirstate.pendingparentchange():
2676 self.dirstate.invalidate()
2663 self.dirstate.invalidate()
2677 else:
2664 else:
2678 self.dirstate.write(None)
2665 self.dirstate.write(None)
2679
2666
2680 self._filecache[b'dirstate'].refresh()
2667 self._filecache[b'dirstate'].refresh()
2681
2668
2682 l = self._lock(
2669 l = self._lock(
2683 self.vfs,
2670 self.vfs,
2684 b"wlock",
2671 b"wlock",
2685 wait,
2672 wait,
2686 unlock,
2673 unlock,
2687 self.invalidatedirstate,
2674 self.invalidatedirstate,
2688 _(b'working directory of %s') % self.origroot,
2675 _(b'working directory of %s') % self.origroot,
2689 inheritchecker=self._wlockchecktransaction,
2676 inheritchecker=self._wlockchecktransaction,
2690 parentenvvar=b'HG_WLOCK_LOCKER',
2677 parentenvvar=b'HG_WLOCK_LOCKER',
2691 )
2678 )
2692 self._wlockref = weakref.ref(l)
2679 self._wlockref = weakref.ref(l)
2693 return l
2680 return l
2694
2681
2695 def _currentlock(self, lockref):
2682 def _currentlock(self, lockref):
2696 """Returns the lock if it's held, or None if it's not."""
2683 """Returns the lock if it's held, or None if it's not."""
2697 if lockref is None:
2684 if lockref is None:
2698 return None
2685 return None
2699 l = lockref()
2686 l = lockref()
2700 if l is None or not l.held:
2687 if l is None or not l.held:
2701 return None
2688 return None
2702 return l
2689 return l
2703
2690
2704 def currentwlock(self):
2691 def currentwlock(self):
2705 """Returns the wlock if it's held, or None if it's not."""
2692 """Returns the wlock if it's held, or None if it's not."""
2706 return self._currentlock(self._wlockref)
2693 return self._currentlock(self._wlockref)
2707
2694
2708 def _filecommit(
2695 def _filecommit(
2709 self,
2696 self,
2710 fctx,
2697 fctx,
2711 manifest1,
2698 manifest1,
2712 manifest2,
2699 manifest2,
2713 linkrev,
2700 linkrev,
2714 tr,
2701 tr,
2715 changelist,
2702 changelist,
2716 includecopymeta,
2703 includecopymeta,
2717 ):
2704 ):
2718 """
2705 """
2719 commit an individual file as part of a larger transaction
2706 commit an individual file as part of a larger transaction
2720 """
2707 """
2721
2708
2722 fname = fctx.path()
2709 fname = fctx.path()
2723 fparent1 = manifest1.get(fname, nullid)
2710 fparent1 = manifest1.get(fname, nullid)
2724 fparent2 = manifest2.get(fname, nullid)
2711 fparent2 = manifest2.get(fname, nullid)
2725 if isinstance(fctx, context.filectx):
2712 if isinstance(fctx, context.filectx):
2726 node = fctx.filenode()
2713 node = fctx.filenode()
2727 if node in [fparent1, fparent2]:
2714 if node in [fparent1, fparent2]:
2728 self.ui.debug(b'reusing %s filelog entry\n' % fname)
2715 self.ui.debug(b'reusing %s filelog entry\n' % fname)
2729 if (
2716 if (
2730 fparent1 != nullid
2717 fparent1 != nullid
2731 and manifest1.flags(fname) != fctx.flags()
2718 and manifest1.flags(fname) != fctx.flags()
2732 ) or (
2719 ) or (
2733 fparent2 != nullid
2720 fparent2 != nullid
2734 and manifest2.flags(fname) != fctx.flags()
2721 and manifest2.flags(fname) != fctx.flags()
2735 ):
2722 ):
2736 changelist.append(fname)
2723 changelist.append(fname)
2737 return node
2724 return node
2738
2725
2739 flog = self.file(fname)
2726 flog = self.file(fname)
2740 meta = {}
2727 meta = {}
2741 cfname = fctx.copysource()
2728 cfname = fctx.copysource()
2742 if cfname and cfname != fname:
2729 if cfname and cfname != fname:
2743 # Mark the new revision of this file as a copy of another
2730 # Mark the new revision of this file as a copy of another
2744 # file. This copy data will effectively act as a parent
2731 # file. This copy data will effectively act as a parent
2745 # of this new revision. If this is a merge, the first
2732 # of this new revision. If this is a merge, the first
2746 # parent will be the nullid (meaning "look up the copy data")
2733 # parent will be the nullid (meaning "look up the copy data")
2747 # and the second one will be the other parent. For example:
2734 # and the second one will be the other parent. For example:
2748 #
2735 #
2749 # 0 --- 1 --- 3 rev1 changes file foo
2736 # 0 --- 1 --- 3 rev1 changes file foo
2750 # \ / rev2 renames foo to bar and changes it
2737 # \ / rev2 renames foo to bar and changes it
2751 # \- 2 -/ rev3 should have bar with all changes and
2738 # \- 2 -/ rev3 should have bar with all changes and
2752 # should record that bar descends from
2739 # should record that bar descends from
2753 # bar in rev2 and foo in rev1
2740 # bar in rev2 and foo in rev1
2754 #
2741 #
2755 # this allows this merge to succeed:
2742 # this allows this merge to succeed:
2756 #
2743 #
2757 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2744 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2758 # \ / merging rev3 and rev4 should use bar@rev2
2745 # \ / merging rev3 and rev4 should use bar@rev2
2759 # \- 2 --- 4 as the merge base
2746 # \- 2 --- 4 as the merge base
2760 #
2747 #
2761
2748
2762 cnode = manifest1.get(cfname)
2749 cnode = manifest1.get(cfname)
2763 newfparent = fparent2
2750 newfparent = fparent2
2764
2751
2765 if manifest2: # branch merge
2752 if manifest2: # branch merge
2766 if fparent2 == nullid or cnode is None: # copied on remote side
2753 if fparent2 == nullid or cnode is None: # copied on remote side
2767 if cfname in manifest2:
2754 if cfname in manifest2:
2768 cnode = manifest2[cfname]
2755 cnode = manifest2[cfname]
2769 newfparent = fparent1
2756 newfparent = fparent1
2770
2757
2771 # Here, we used to search backwards through history to try to find
2758 # Here, we used to search backwards through history to try to find
2772 # where the file copy came from if the source of a copy was not in
2759 # where the file copy came from if the source of a copy was not in
2773 # the parent directory. However, this doesn't actually make sense to
2760 # the parent directory. However, this doesn't actually make sense to
2774 # do (what does a copy from something not in your working copy even
2761 # do (what does a copy from something not in your working copy even
2775 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2762 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2776 # the user that copy information was dropped, so if they didn't
2763 # the user that copy information was dropped, so if they didn't
2777 # expect this outcome it can be fixed, but this is the correct
2764 # expect this outcome it can be fixed, but this is the correct
2778 # behavior in this circumstance.
2765 # behavior in this circumstance.
2779
2766
2780 if cnode:
2767 if cnode:
2781 self.ui.debug(
2768 self.ui.debug(
2782 b" %s: copy %s:%s\n" % (fname, cfname, hex(cnode))
2769 b" %s: copy %s:%s\n" % (fname, cfname, hex(cnode))
2783 )
2770 )
2784 if includecopymeta:
2771 if includecopymeta:
2785 meta[b"copy"] = cfname
2772 meta[b"copy"] = cfname
2786 meta[b"copyrev"] = hex(cnode)
2773 meta[b"copyrev"] = hex(cnode)
2787 fparent1, fparent2 = nullid, newfparent
2774 fparent1, fparent2 = nullid, newfparent
2788 else:
2775 else:
2789 self.ui.warn(
2776 self.ui.warn(
2790 _(
2777 _(
2791 b"warning: can't find ancestor for '%s' "
2778 b"warning: can't find ancestor for '%s' "
2792 b"copied from '%s'!\n"
2779 b"copied from '%s'!\n"
2793 )
2780 )
2794 % (fname, cfname)
2781 % (fname, cfname)
2795 )
2782 )
2796
2783
2797 elif fparent1 == nullid:
2784 elif fparent1 == nullid:
2798 fparent1, fparent2 = fparent2, nullid
2785 fparent1, fparent2 = fparent2, nullid
2799 elif fparent2 != nullid:
2786 elif fparent2 != nullid:
2800 # is one parent an ancestor of the other?
2787 # is one parent an ancestor of the other?
2801 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2788 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2802 if fparent1 in fparentancestors:
2789 if fparent1 in fparentancestors:
2803 fparent1, fparent2 = fparent2, nullid
2790 fparent1, fparent2 = fparent2, nullid
2804 elif fparent2 in fparentancestors:
2791 elif fparent2 in fparentancestors:
2805 fparent2 = nullid
2792 fparent2 = nullid
2806
2793
2807 # is the file changed?
2794 # is the file changed?
2808 text = fctx.data()
2795 text = fctx.data()
2809 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2796 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2810 changelist.append(fname)
2797 changelist.append(fname)
2811 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2798 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2812 # are just the flags changed during merge?
2799 # are just the flags changed during merge?
2813 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2800 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2814 changelist.append(fname)
2801 changelist.append(fname)
2815
2802
2816 return fparent1
2803 return fparent1
2817
2804
2818 def checkcommitpatterns(self, wctx, match, status, fail):
2805 def checkcommitpatterns(self, wctx, match, status, fail):
2819 """check for commit arguments that aren't committable"""
2806 """check for commit arguments that aren't committable"""
2820 if match.isexact() or match.prefix():
2807 if match.isexact() or match.prefix():
2821 matched = set(status.modified + status.added + status.removed)
2808 matched = set(status.modified + status.added + status.removed)
2822
2809
2823 for f in match.files():
2810 for f in match.files():
2824 f = self.dirstate.normalize(f)
2811 f = self.dirstate.normalize(f)
2825 if f == b'.' or f in matched or f in wctx.substate:
2812 if f == b'.' or f in matched or f in wctx.substate:
2826 continue
2813 continue
2827 if f in status.deleted:
2814 if f in status.deleted:
2828 fail(f, _(b'file not found!'))
2815 fail(f, _(b'file not found!'))
2829 # Is it a directory that exists or used to exist?
2816 # Is it a directory that exists or used to exist?
2830 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
2817 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
2831 d = f + b'/'
2818 d = f + b'/'
2832 for mf in matched:
2819 for mf in matched:
2833 if mf.startswith(d):
2820 if mf.startswith(d):
2834 break
2821 break
2835 else:
2822 else:
2836 fail(f, _(b"no match under directory!"))
2823 fail(f, _(b"no match under directory!"))
2837 elif f not in self.dirstate:
2824 elif f not in self.dirstate:
2838 fail(f, _(b"file not tracked!"))
2825 fail(f, _(b"file not tracked!"))
2839
2826
2840 @unfilteredmethod
2827 @unfilteredmethod
2841 def commit(
2828 def commit(
2842 self,
2829 self,
2843 text=b"",
2830 text=b"",
2844 user=None,
2831 user=None,
2845 date=None,
2832 date=None,
2846 match=None,
2833 match=None,
2847 force=False,
2834 force=False,
2848 editor=None,
2835 editor=None,
2849 extra=None,
2836 extra=None,
2850 ):
2837 ):
2851 """Add a new revision to current repository.
2838 """Add a new revision to current repository.
2852
2839
2853 Revision information is gathered from the working directory,
2840 Revision information is gathered from the working directory,
2854 match can be used to filter the committed files. If editor is
2841 match can be used to filter the committed files. If editor is
2855 supplied, it is called to get a commit message.
2842 supplied, it is called to get a commit message.
2856 """
2843 """
2857 if extra is None:
2844 if extra is None:
2858 extra = {}
2845 extra = {}
2859
2846
2860 def fail(f, msg):
2847 def fail(f, msg):
2861 raise error.Abort(b'%s: %s' % (f, msg))
2848 raise error.Abort(b'%s: %s' % (f, msg))
2862
2849
2863 if not match:
2850 if not match:
2864 match = matchmod.always()
2851 match = matchmod.always()
2865
2852
2866 if not force:
2853 if not force:
2867 match.bad = fail
2854 match.bad = fail
2868
2855
2869 # lock() for recent changelog (see issue4368)
2856 # lock() for recent changelog (see issue4368)
2870 with self.wlock(), self.lock():
2857 with self.wlock(), self.lock():
2871 wctx = self[None]
2858 wctx = self[None]
2872 merge = len(wctx.parents()) > 1
2859 merge = len(wctx.parents()) > 1
2873
2860
2874 if not force and merge and not match.always():
2861 if not force and merge and not match.always():
2875 raise error.Abort(
2862 raise error.Abort(
2876 _(
2863 _(
2877 b'cannot partially commit a merge '
2864 b'cannot partially commit a merge '
2878 b'(do not specify files or patterns)'
2865 b'(do not specify files or patterns)'
2879 )
2866 )
2880 )
2867 )
2881
2868
2882 status = self.status(match=match, clean=force)
2869 status = self.status(match=match, clean=force)
2883 if force:
2870 if force:
2884 status.modified.extend(
2871 status.modified.extend(
2885 status.clean
2872 status.clean
2886 ) # mq may commit clean files
2873 ) # mq may commit clean files
2887
2874
2888 # check subrepos
2875 # check subrepos
2889 subs, commitsubs, newstate = subrepoutil.precommit(
2876 subs, commitsubs, newstate = subrepoutil.precommit(
2890 self.ui, wctx, status, match, force=force
2877 self.ui, wctx, status, match, force=force
2891 )
2878 )
2892
2879
2893 # make sure all explicit patterns are matched
2880 # make sure all explicit patterns are matched
2894 if not force:
2881 if not force:
2895 self.checkcommitpatterns(wctx, match, status, fail)
2882 self.checkcommitpatterns(wctx, match, status, fail)
2896
2883
2897 cctx = context.workingcommitctx(
2884 cctx = context.workingcommitctx(
2898 self, status, text, user, date, extra
2885 self, status, text, user, date, extra
2899 )
2886 )
2900
2887
2901 # internal config: ui.allowemptycommit
2888 # internal config: ui.allowemptycommit
2902 allowemptycommit = (
2889 allowemptycommit = (
2903 wctx.branch() != wctx.p1().branch()
2890 wctx.branch() != wctx.p1().branch()
2904 or extra.get(b'close')
2891 or extra.get(b'close')
2905 or merge
2892 or merge
2906 or cctx.files()
2893 or cctx.files()
2907 or self.ui.configbool(b'ui', b'allowemptycommit')
2894 or self.ui.configbool(b'ui', b'allowemptycommit')
2908 )
2895 )
2909 if not allowemptycommit:
2896 if not allowemptycommit:
2910 return None
2897 return None
2911
2898
2912 if merge and cctx.deleted():
2899 if merge and cctx.deleted():
2913 raise error.Abort(_(b"cannot commit merge with missing files"))
2900 raise error.Abort(_(b"cannot commit merge with missing files"))
2914
2901
2915 ms = mergemod.mergestate.read(self)
2902 ms = mergemod.mergestate.read(self)
2916 mergeutil.checkunresolved(ms)
2903 mergeutil.checkunresolved(ms)
2917
2904
2918 if editor:
2905 if editor:
2919 cctx._text = editor(self, cctx, subs)
2906 cctx._text = editor(self, cctx, subs)
2920 edited = text != cctx._text
2907 edited = text != cctx._text
2921
2908
2922 # Save commit message in case this transaction gets rolled back
2909 # Save commit message in case this transaction gets rolled back
2923 # (e.g. by a pretxncommit hook). Leave the content alone on
2910 # (e.g. by a pretxncommit hook). Leave the content alone on
2924 # the assumption that the user will use the same editor again.
2911 # the assumption that the user will use the same editor again.
2925 msgfn = self.savecommitmessage(cctx._text)
2912 msgfn = self.savecommitmessage(cctx._text)
2926
2913
2927 # commit subs and write new state
2914 # commit subs and write new state
2928 if subs:
2915 if subs:
2929 uipathfn = scmutil.getuipathfn(self)
2916 uipathfn = scmutil.getuipathfn(self)
2930 for s in sorted(commitsubs):
2917 for s in sorted(commitsubs):
2931 sub = wctx.sub(s)
2918 sub = wctx.sub(s)
2932 self.ui.status(
2919 self.ui.status(
2933 _(b'committing subrepository %s\n')
2920 _(b'committing subrepository %s\n')
2934 % uipathfn(subrepoutil.subrelpath(sub))
2921 % uipathfn(subrepoutil.subrelpath(sub))
2935 )
2922 )
2936 sr = sub.commit(cctx._text, user, date)
2923 sr = sub.commit(cctx._text, user, date)
2937 newstate[s] = (newstate[s][0], sr)
2924 newstate[s] = (newstate[s][0], sr)
2938 subrepoutil.writestate(self, newstate)
2925 subrepoutil.writestate(self, newstate)
2939
2926
2940 p1, p2 = self.dirstate.parents()
2927 p1, p2 = self.dirstate.parents()
2941 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or b'')
2928 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or b'')
2942 try:
2929 try:
2943 self.hook(
2930 self.hook(
2944 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
2931 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
2945 )
2932 )
2946 with self.transaction(b'commit'):
2933 with self.transaction(b'commit'):
2947 ret = self.commitctx(cctx, True)
2934 ret = self.commitctx(cctx, True)
2948 # update bookmarks, dirstate and mergestate
2935 # update bookmarks, dirstate and mergestate
2949 bookmarks.update(self, [p1, p2], ret)
2936 bookmarks.update(self, [p1, p2], ret)
2950 cctx.markcommitted(ret)
2937 cctx.markcommitted(ret)
2951 ms.reset()
2938 ms.reset()
2952 except: # re-raises
2939 except: # re-raises
2953 if edited:
2940 if edited:
2954 self.ui.write(
2941 self.ui.write(
2955 _(b'note: commit message saved in %s\n') % msgfn
2942 _(b'note: commit message saved in %s\n') % msgfn
2956 )
2943 )
2957 raise
2944 raise
2958
2945
2959 def commithook(unused_success):
2946 def commithook(unused_success):
2960 # hack for command that use a temporary commit (eg: histedit)
2947 # hack for command that use a temporary commit (eg: histedit)
2961 # temporary commit got stripped before hook release
2948 # temporary commit got stripped before hook release
2962 if self.changelog.hasnode(ret):
2949 if self.changelog.hasnode(ret):
2963 self.hook(
2950 self.hook(
2964 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
2951 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
2965 )
2952 )
2966
2953
2967 self._afterlock(commithook)
2954 self._afterlock(commithook)
2968 return ret
2955 return ret
2969
2956
2970 @unfilteredmethod
2957 @unfilteredmethod
2971 def commitctx(self, ctx, error=False, origctx=None):
2958 def commitctx(self, ctx, error=False, origctx=None):
2972 """Add a new revision to current repository.
2959 """Add a new revision to current repository.
2973 Revision information is passed via the context argument.
2960 Revision information is passed via the context argument.
2974
2961
2975 ctx.files() should list all files involved in this commit, i.e.
2962 ctx.files() should list all files involved in this commit, i.e.
2976 modified/added/removed files. On merge, it may be wider than the
2963 modified/added/removed files. On merge, it may be wider than the
2977 ctx.files() to be committed, since any file nodes derived directly
2964 ctx.files() to be committed, since any file nodes derived directly
2978 from p1 or p2 are excluded from the committed ctx.files().
2965 from p1 or p2 are excluded from the committed ctx.files().
2979
2966
2980 origctx is for convert to work around the problem that bug
2967 origctx is for convert to work around the problem that bug
2981 fixes to the files list in changesets change hashes. For
2968 fixes to the files list in changesets change hashes. For
2982 convert to be the identity, it can pass an origctx and this
2969 convert to be the identity, it can pass an origctx and this
2983 function will use the same files list when it makes sense to
2970 function will use the same files list when it makes sense to
2984 do so.
2971 do so.
2985 """
2972 """
2986
2973
2987 p1, p2 = ctx.p1(), ctx.p2()
2974 p1, p2 = ctx.p1(), ctx.p2()
2988 user = ctx.user()
2975 user = ctx.user()
2989
2976
2990 if self.filecopiesmode == b'changeset-sidedata':
2977 if self.filecopiesmode == b'changeset-sidedata':
2991 writechangesetcopy = True
2978 writechangesetcopy = True
2992 writefilecopymeta = True
2979 writefilecopymeta = True
2993 writecopiesto = None
2980 writecopiesto = None
2994 else:
2981 else:
2995 writecopiesto = self.ui.config(b'experimental', b'copies.write-to')
2982 writecopiesto = self.ui.config(b'experimental', b'copies.write-to')
2996 writefilecopymeta = writecopiesto != b'changeset-only'
2983 writefilecopymeta = writecopiesto != b'changeset-only'
2997 writechangesetcopy = writecopiesto in (
2984 writechangesetcopy = writecopiesto in (
2998 b'changeset-only',
2985 b'changeset-only',
2999 b'compatibility',
2986 b'compatibility',
3000 )
2987 )
3001 p1copies, p2copies = None, None
2988 p1copies, p2copies = None, None
3002 if writechangesetcopy:
2989 if writechangesetcopy:
3003 p1copies = ctx.p1copies()
2990 p1copies = ctx.p1copies()
3004 p2copies = ctx.p2copies()
2991 p2copies = ctx.p2copies()
3005 filesadded, filesremoved = None, None
2992 filesadded, filesremoved = None, None
3006 with self.lock(), self.transaction(b"commit") as tr:
2993 with self.lock(), self.transaction(b"commit") as tr:
3007 trp = weakref.proxy(tr)
2994 trp = weakref.proxy(tr)
3008
2995
3009 if ctx.manifestnode():
2996 if ctx.manifestnode():
3010 # reuse an existing manifest revision
2997 # reuse an existing manifest revision
3011 self.ui.debug(b'reusing known manifest\n')
2998 self.ui.debug(b'reusing known manifest\n')
3012 mn = ctx.manifestnode()
2999 mn = ctx.manifestnode()
3013 files = ctx.files()
3000 files = ctx.files()
3014 if writechangesetcopy:
3001 if writechangesetcopy:
3015 filesadded = ctx.filesadded()
3002 filesadded = ctx.filesadded()
3016 filesremoved = ctx.filesremoved()
3003 filesremoved = ctx.filesremoved()
3017 elif ctx.files():
3004 elif ctx.files():
3018 m1ctx = p1.manifestctx()
3005 m1ctx = p1.manifestctx()
3019 m2ctx = p2.manifestctx()
3006 m2ctx = p2.manifestctx()
3020 mctx = m1ctx.copy()
3007 mctx = m1ctx.copy()
3021
3008
3022 m = mctx.read()
3009 m = mctx.read()
3023 m1 = m1ctx.read()
3010 m1 = m1ctx.read()
3024 m2 = m2ctx.read()
3011 m2 = m2ctx.read()
3025
3012
3026 # check in files
3013 # check in files
3027 added = []
3014 added = []
3028 changed = []
3015 changed = []
3029 removed = list(ctx.removed())
3016 removed = list(ctx.removed())
3030 linkrev = len(self)
3017 linkrev = len(self)
3031 self.ui.note(_(b"committing files:\n"))
3018 self.ui.note(_(b"committing files:\n"))
3032 uipathfn = scmutil.getuipathfn(self)
3019 uipathfn = scmutil.getuipathfn(self)
3033 for f in sorted(ctx.modified() + ctx.added()):
3020 for f in sorted(ctx.modified() + ctx.added()):
3034 self.ui.note(uipathfn(f) + b"\n")
3021 self.ui.note(uipathfn(f) + b"\n")
3035 try:
3022 try:
3036 fctx = ctx[f]
3023 fctx = ctx[f]
3037 if fctx is None:
3024 if fctx is None:
3038 removed.append(f)
3025 removed.append(f)
3039 else:
3026 else:
3040 added.append(f)
3027 added.append(f)
3041 m[f] = self._filecommit(
3028 m[f] = self._filecommit(
3042 fctx,
3029 fctx,
3043 m1,
3030 m1,
3044 m2,
3031 m2,
3045 linkrev,
3032 linkrev,
3046 trp,
3033 trp,
3047 changed,
3034 changed,
3048 writefilecopymeta,
3035 writefilecopymeta,
3049 )
3036 )
3050 m.setflag(f, fctx.flags())
3037 m.setflag(f, fctx.flags())
3051 except OSError:
3038 except OSError:
3052 self.ui.warn(
3039 self.ui.warn(
3053 _(b"trouble committing %s!\n") % uipathfn(f)
3040 _(b"trouble committing %s!\n") % uipathfn(f)
3054 )
3041 )
3055 raise
3042 raise
3056 except IOError as inst:
3043 except IOError as inst:
3057 errcode = getattr(inst, 'errno', errno.ENOENT)
3044 errcode = getattr(inst, 'errno', errno.ENOENT)
3058 if error or errcode and errcode != errno.ENOENT:
3045 if error or errcode and errcode != errno.ENOENT:
3059 self.ui.warn(
3046 self.ui.warn(
3060 _(b"trouble committing %s!\n") % uipathfn(f)
3047 _(b"trouble committing %s!\n") % uipathfn(f)
3061 )
3048 )
3062 raise
3049 raise
3063
3050
3064 # update manifest
3051 # update manifest
3065 removed = [f for f in removed if f in m1 or f in m2]
3052 removed = [f for f in removed if f in m1 or f in m2]
3066 drop = sorted([f for f in removed if f in m])
3053 drop = sorted([f for f in removed if f in m])
3067 for f in drop:
3054 for f in drop:
3068 del m[f]
3055 del m[f]
3069 if p2.rev() != nullrev:
3056 if p2.rev() != nullrev:
3070
3057
3071 @util.cachefunc
3058 @util.cachefunc
3072 def mas():
3059 def mas():
3073 p1n = p1.node()
3060 p1n = p1.node()
3074 p2n = p2.node()
3061 p2n = p2.node()
3075 cahs = self.changelog.commonancestorsheads(p1n, p2n)
3062 cahs = self.changelog.commonancestorsheads(p1n, p2n)
3076 if not cahs:
3063 if not cahs:
3077 cahs = [nullrev]
3064 cahs = [nullrev]
3078 return [self[r].manifest() for r in cahs]
3065 return [self[r].manifest() for r in cahs]
3079
3066
3080 def deletionfromparent(f):
3067 def deletionfromparent(f):
3081 # When a file is removed relative to p1 in a merge, this
3068 # When a file is removed relative to p1 in a merge, this
3082 # function determines whether the absence is due to a
3069 # function determines whether the absence is due to a
3083 # deletion from a parent, or whether the merge commit
3070 # deletion from a parent, or whether the merge commit
3084 # itself deletes the file. We decide this by doing a
3071 # itself deletes the file. We decide this by doing a
3085 # simplified three way merge of the manifest entry for
3072 # simplified three way merge of the manifest entry for
3086 # the file. There are two ways we decide the merge
3073 # the file. There are two ways we decide the merge
3087 # itself didn't delete a file:
3074 # itself didn't delete a file:
3088 # - neither parent (nor the merge) contain the file
3075 # - neither parent (nor the merge) contain the file
3089 # - exactly one parent contains the file, and that
3076 # - exactly one parent contains the file, and that
3090 # parent has the same filelog entry as the merge
3077 # parent has the same filelog entry as the merge
3091 # ancestor (or all of them if there two). In other
3078 # ancestor (or all of them if there two). In other
3092 # words, that parent left the file unchanged while the
3079 # words, that parent left the file unchanged while the
3093 # other one deleted it.
3080 # other one deleted it.
3094 # One way to think about this is that deleting a file is
3081 # One way to think about this is that deleting a file is
3095 # similar to emptying it, so the list of changed files
3082 # similar to emptying it, so the list of changed files
3096 # should be similar either way. The computation
3083 # should be similar either way. The computation
3097 # described above is not done directly in _filecommit
3084 # described above is not done directly in _filecommit
3098 # when creating the list of changed files, however
3085 # when creating the list of changed files, however
3099 # it does something very similar by comparing filelog
3086 # it does something very similar by comparing filelog
3100 # nodes.
3087 # nodes.
3101 if f in m1:
3088 if f in m1:
3102 return f not in m2 and all(
3089 return f not in m2 and all(
3103 f in ma and ma.find(f) == m1.find(f)
3090 f in ma and ma.find(f) == m1.find(f)
3104 for ma in mas()
3091 for ma in mas()
3105 )
3092 )
3106 elif f in m2:
3093 elif f in m2:
3107 return all(
3094 return all(
3108 f in ma and ma.find(f) == m2.find(f)
3095 f in ma and ma.find(f) == m2.find(f)
3109 for ma in mas()
3096 for ma in mas()
3110 )
3097 )
3111 else:
3098 else:
3112 return True
3099 return True
3113
3100
3114 removed = [f for f in removed if not deletionfromparent(f)]
3101 removed = [f for f in removed if not deletionfromparent(f)]
3115
3102
3116 files = changed + removed
3103 files = changed + removed
3117 md = None
3104 md = None
3118 if not files:
3105 if not files:
3119 # if no "files" actually changed in terms of the changelog,
3106 # if no "files" actually changed in terms of the changelog,
3120 # try hard to detect unmodified manifest entry so that the
3107 # try hard to detect unmodified manifest entry so that the
3121 # exact same commit can be reproduced later on convert.
3108 # exact same commit can be reproduced later on convert.
3122 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
3109 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
3123 if not files and md:
3110 if not files and md:
3124 self.ui.debug(
3111 self.ui.debug(
3125 b'not reusing manifest (no file change in '
3112 b'not reusing manifest (no file change in '
3126 b'changelog, but manifest differs)\n'
3113 b'changelog, but manifest differs)\n'
3127 )
3114 )
3128 if files or md:
3115 if files or md:
3129 self.ui.note(_(b"committing manifest\n"))
3116 self.ui.note(_(b"committing manifest\n"))
3130 # we're using narrowmatch here since it's already applied at
3117 # we're using narrowmatch here since it's already applied at
3131 # other stages (such as dirstate.walk), so we're already
3118 # other stages (such as dirstate.walk), so we're already
3132 # ignoring things outside of narrowspec in most cases. The
3119 # ignoring things outside of narrowspec in most cases. The
3133 # one case where we might have files outside the narrowspec
3120 # one case where we might have files outside the narrowspec
3134 # at this point is merges, and we already error out in the
3121 # at this point is merges, and we already error out in the
3135 # case where the merge has files outside of the narrowspec,
3122 # case where the merge has files outside of the narrowspec,
3136 # so this is safe.
3123 # so this is safe.
3137 mn = mctx.write(
3124 mn = mctx.write(
3138 trp,
3125 trp,
3139 linkrev,
3126 linkrev,
3140 p1.manifestnode(),
3127 p1.manifestnode(),
3141 p2.manifestnode(),
3128 p2.manifestnode(),
3142 added,
3129 added,
3143 drop,
3130 drop,
3144 match=self.narrowmatch(),
3131 match=self.narrowmatch(),
3145 )
3132 )
3146
3133
3147 if writechangesetcopy:
3134 if writechangesetcopy:
3148 filesadded = [
3135 filesadded = [
3149 f for f in changed if not (f in m1 or f in m2)
3136 f for f in changed if not (f in m1 or f in m2)
3150 ]
3137 ]
3151 filesremoved = removed
3138 filesremoved = removed
3152 else:
3139 else:
3153 self.ui.debug(
3140 self.ui.debug(
3154 b'reusing manifest from p1 (listed files '
3141 b'reusing manifest from p1 (listed files '
3155 b'actually unchanged)\n'
3142 b'actually unchanged)\n'
3156 )
3143 )
3157 mn = p1.manifestnode()
3144 mn = p1.manifestnode()
3158 else:
3145 else:
3159 self.ui.debug(b'reusing manifest from p1 (no file change)\n')
3146 self.ui.debug(b'reusing manifest from p1 (no file change)\n')
3160 mn = p1.manifestnode()
3147 mn = p1.manifestnode()
3161 files = []
3148 files = []
3162
3149
3163 if writecopiesto == b'changeset-only':
3150 if writecopiesto == b'changeset-only':
3164 # If writing only to changeset extras, use None to indicate that
3151 # If writing only to changeset extras, use None to indicate that
3165 # no entry should be written. If writing to both, write an empty
3152 # no entry should be written. If writing to both, write an empty
3166 # entry to prevent the reader from falling back to reading
3153 # entry to prevent the reader from falling back to reading
3167 # filelogs.
3154 # filelogs.
3168 p1copies = p1copies or None
3155 p1copies = p1copies or None
3169 p2copies = p2copies or None
3156 p2copies = p2copies or None
3170 filesadded = filesadded or None
3157 filesadded = filesadded or None
3171 filesremoved = filesremoved or None
3158 filesremoved = filesremoved or None
3172
3159
3173 if origctx and origctx.manifestnode() == mn:
3160 if origctx and origctx.manifestnode() == mn:
3174 files = origctx.files()
3161 files = origctx.files()
3175
3162
3176 # update changelog
3163 # update changelog
3177 self.ui.note(_(b"committing changelog\n"))
3164 self.ui.note(_(b"committing changelog\n"))
3178 self.changelog.delayupdate(tr)
3165 self.changelog.delayupdate(tr)
3179 n = self.changelog.add(
3166 n = self.changelog.add(
3180 mn,
3167 mn,
3181 files,
3168 files,
3182 ctx.description(),
3169 ctx.description(),
3183 trp,
3170 trp,
3184 p1.node(),
3171 p1.node(),
3185 p2.node(),
3172 p2.node(),
3186 user,
3173 user,
3187 ctx.date(),
3174 ctx.date(),
3188 ctx.extra().copy(),
3175 ctx.extra().copy(),
3189 p1copies,
3176 p1copies,
3190 p2copies,
3177 p2copies,
3191 filesadded,
3178 filesadded,
3192 filesremoved,
3179 filesremoved,
3193 )
3180 )
3194 xp1, xp2 = p1.hex(), p2 and p2.hex() or b''
3181 xp1, xp2 = p1.hex(), p2 and p2.hex() or b''
3195 self.hook(
3182 self.hook(
3196 b'pretxncommit',
3183 b'pretxncommit',
3197 throw=True,
3184 throw=True,
3198 node=hex(n),
3185 node=hex(n),
3199 parent1=xp1,
3186 parent1=xp1,
3200 parent2=xp2,
3187 parent2=xp2,
3201 )
3188 )
3202 # set the new commit is proper phase
3189 # set the new commit is proper phase
3203 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
3190 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
3204 if targetphase:
3191 if targetphase:
3205 # retract boundary do not alter parent changeset.
3192 # retract boundary do not alter parent changeset.
3206 # if a parent have higher the resulting phase will
3193 # if a parent have higher the resulting phase will
3207 # be compliant anyway
3194 # be compliant anyway
3208 #
3195 #
3209 # if minimal phase was 0 we don't need to retract anything
3196 # if minimal phase was 0 we don't need to retract anything
3210 phases.registernew(self, tr, targetphase, [n])
3197 phases.registernew(self, tr, targetphase, [n])
3211 return n
3198 return n
3212
3199
3213 @unfilteredmethod
3200 @unfilteredmethod
3214 def destroying(self):
3201 def destroying(self):
3215 '''Inform the repository that nodes are about to be destroyed.
3202 '''Inform the repository that nodes are about to be destroyed.
3216 Intended for use by strip and rollback, so there's a common
3203 Intended for use by strip and rollback, so there's a common
3217 place for anything that has to be done before destroying history.
3204 place for anything that has to be done before destroying history.
3218
3205
3219 This is mostly useful for saving state that is in memory and waiting
3206 This is mostly useful for saving state that is in memory and waiting
3220 to be flushed when the current lock is released. Because a call to
3207 to be flushed when the current lock is released. Because a call to
3221 destroyed is imminent, the repo will be invalidated causing those
3208 destroyed is imminent, the repo will be invalidated causing those
3222 changes to stay in memory (waiting for the next unlock), or vanish
3209 changes to stay in memory (waiting for the next unlock), or vanish
3223 completely.
3210 completely.
3224 '''
3211 '''
3225 # When using the same lock to commit and strip, the phasecache is left
3212 # When using the same lock to commit and strip, the phasecache is left
3226 # dirty after committing. Then when we strip, the repo is invalidated,
3213 # dirty after committing. Then when we strip, the repo is invalidated,
3227 # causing those changes to disappear.
3214 # causing those changes to disappear.
3228 if '_phasecache' in vars(self):
3215 if '_phasecache' in vars(self):
3229 self._phasecache.write()
3216 self._phasecache.write()
3230
3217
3231 @unfilteredmethod
3218 @unfilteredmethod
3232 def destroyed(self):
3219 def destroyed(self):
3233 '''Inform the repository that nodes have been destroyed.
3220 '''Inform the repository that nodes have been destroyed.
3234 Intended for use by strip and rollback, so there's a common
3221 Intended for use by strip and rollback, so there's a common
3235 place for anything that has to be done after destroying history.
3222 place for anything that has to be done after destroying history.
3236 '''
3223 '''
3237 # When one tries to:
3224 # When one tries to:
3238 # 1) destroy nodes thus calling this method (e.g. strip)
3225 # 1) destroy nodes thus calling this method (e.g. strip)
3239 # 2) use phasecache somewhere (e.g. commit)
3226 # 2) use phasecache somewhere (e.g. commit)
3240 #
3227 #
3241 # then 2) will fail because the phasecache contains nodes that were
3228 # then 2) will fail because the phasecache contains nodes that were
3242 # removed. We can either remove phasecache from the filecache,
3229 # removed. We can either remove phasecache from the filecache,
3243 # causing it to reload next time it is accessed, or simply filter
3230 # causing it to reload next time it is accessed, or simply filter
3244 # the removed nodes now and write the updated cache.
3231 # the removed nodes now and write the updated cache.
3245 self._phasecache.filterunknown(self)
3232 self._phasecache.filterunknown(self)
3246 self._phasecache.write()
3233 self._phasecache.write()
3247
3234
3248 # refresh all repository caches
3235 # refresh all repository caches
3249 self.updatecaches()
3236 self.updatecaches()
3250
3237
3251 # Ensure the persistent tag cache is updated. Doing it now
3238 # Ensure the persistent tag cache is updated. Doing it now
3252 # means that the tag cache only has to worry about destroyed
3239 # means that the tag cache only has to worry about destroyed
3253 # heads immediately after a strip/rollback. That in turn
3240 # heads immediately after a strip/rollback. That in turn
3254 # guarantees that "cachetip == currenttip" (comparing both rev
3241 # guarantees that "cachetip == currenttip" (comparing both rev
3255 # and node) always means no nodes have been added or destroyed.
3242 # and node) always means no nodes have been added or destroyed.
3256
3243
3257 # XXX this is suboptimal when qrefresh'ing: we strip the current
3244 # XXX this is suboptimal when qrefresh'ing: we strip the current
3258 # head, refresh the tag cache, then immediately add a new head.
3245 # head, refresh the tag cache, then immediately add a new head.
3259 # But I think doing it this way is necessary for the "instant
3246 # But I think doing it this way is necessary for the "instant
3260 # tag cache retrieval" case to work.
3247 # tag cache retrieval" case to work.
3261 self.invalidate()
3248 self.invalidate()
3262
3249
3263 def status(
3250 def status(
3264 self,
3251 self,
3265 node1=b'.',
3252 node1=b'.',
3266 node2=None,
3253 node2=None,
3267 match=None,
3254 match=None,
3268 ignored=False,
3255 ignored=False,
3269 clean=False,
3256 clean=False,
3270 unknown=False,
3257 unknown=False,
3271 listsubrepos=False,
3258 listsubrepos=False,
3272 ):
3259 ):
3273 '''a convenience method that calls node1.status(node2)'''
3260 '''a convenience method that calls node1.status(node2)'''
3274 return self[node1].status(
3261 return self[node1].status(
3275 node2, match, ignored, clean, unknown, listsubrepos
3262 node2, match, ignored, clean, unknown, listsubrepos
3276 )
3263 )
3277
3264
3278 def addpostdsstatus(self, ps):
3265 def addpostdsstatus(self, ps):
3279 """Add a callback to run within the wlock, at the point at which status
3266 """Add a callback to run within the wlock, at the point at which status
3280 fixups happen.
3267 fixups happen.
3281
3268
3282 On status completion, callback(wctx, status) will be called with the
3269 On status completion, callback(wctx, status) will be called with the
3283 wlock held, unless the dirstate has changed from underneath or the wlock
3270 wlock held, unless the dirstate has changed from underneath or the wlock
3284 couldn't be grabbed.
3271 couldn't be grabbed.
3285
3272
3286 Callbacks should not capture and use a cached copy of the dirstate --
3273 Callbacks should not capture and use a cached copy of the dirstate --
3287 it might change in the meanwhile. Instead, they should access the
3274 it might change in the meanwhile. Instead, they should access the
3288 dirstate via wctx.repo().dirstate.
3275 dirstate via wctx.repo().dirstate.
3289
3276
3290 This list is emptied out after each status run -- extensions should
3277 This list is emptied out after each status run -- extensions should
3291 make sure it adds to this list each time dirstate.status is called.
3278 make sure it adds to this list each time dirstate.status is called.
3292 Extensions should also make sure they don't call this for statuses
3279 Extensions should also make sure they don't call this for statuses
3293 that don't involve the dirstate.
3280 that don't involve the dirstate.
3294 """
3281 """
3295
3282
3296 # The list is located here for uniqueness reasons -- it is actually
3283 # The list is located here for uniqueness reasons -- it is actually
3297 # managed by the workingctx, but that isn't unique per-repo.
3284 # managed by the workingctx, but that isn't unique per-repo.
3298 self._postdsstatus.append(ps)
3285 self._postdsstatus.append(ps)
3299
3286
3300 def postdsstatus(self):
3287 def postdsstatus(self):
3301 """Used by workingctx to get the list of post-dirstate-status hooks."""
3288 """Used by workingctx to get the list of post-dirstate-status hooks."""
3302 return self._postdsstatus
3289 return self._postdsstatus
3303
3290
3304 def clearpostdsstatus(self):
3291 def clearpostdsstatus(self):
3305 """Used by workingctx to clear post-dirstate-status hooks."""
3292 """Used by workingctx to clear post-dirstate-status hooks."""
3306 del self._postdsstatus[:]
3293 del self._postdsstatus[:]
3307
3294
3308 def heads(self, start=None):
3295 def heads(self, start=None):
3309 if start is None:
3296 if start is None:
3310 cl = self.changelog
3297 cl = self.changelog
3311 headrevs = reversed(cl.headrevs())
3298 headrevs = reversed(cl.headrevs())
3312 return [cl.node(rev) for rev in headrevs]
3299 return [cl.node(rev) for rev in headrevs]
3313
3300
3314 heads = self.changelog.heads(start)
3301 heads = self.changelog.heads(start)
3315 # sort the output in rev descending order
3302 # sort the output in rev descending order
3316 return sorted(heads, key=self.changelog.rev, reverse=True)
3303 return sorted(heads, key=self.changelog.rev, reverse=True)
3317
3304
3318 def branchheads(self, branch=None, start=None, closed=False):
3305 def branchheads(self, branch=None, start=None, closed=False):
3319 '''return a (possibly filtered) list of heads for the given branch
3306 '''return a (possibly filtered) list of heads for the given branch
3320
3307
3321 Heads are returned in topological order, from newest to oldest.
3308 Heads are returned in topological order, from newest to oldest.
3322 If branch is None, use the dirstate branch.
3309 If branch is None, use the dirstate branch.
3323 If start is not None, return only heads reachable from start.
3310 If start is not None, return only heads reachable from start.
3324 If closed is True, return heads that are marked as closed as well.
3311 If closed is True, return heads that are marked as closed as well.
3325 '''
3312 '''
3326 if branch is None:
3313 if branch is None:
3327 branch = self[None].branch()
3314 branch = self[None].branch()
3328 branches = self.branchmap()
3315 branches = self.branchmap()
3329 if not branches.hasbranch(branch):
3316 if not branches.hasbranch(branch):
3330 return []
3317 return []
3331 # the cache returns heads ordered lowest to highest
3318 # the cache returns heads ordered lowest to highest
3332 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3319 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3333 if start is not None:
3320 if start is not None:
3334 # filter out the heads that cannot be reached from startrev
3321 # filter out the heads that cannot be reached from startrev
3335 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3322 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3336 bheads = [h for h in bheads if h in fbheads]
3323 bheads = [h for h in bheads if h in fbheads]
3337 return bheads
3324 return bheads
3338
3325
3339 def branches(self, nodes):
3326 def branches(self, nodes):
3340 if not nodes:
3327 if not nodes:
3341 nodes = [self.changelog.tip()]
3328 nodes = [self.changelog.tip()]
3342 b = []
3329 b = []
3343 for n in nodes:
3330 for n in nodes:
3344 t = n
3331 t = n
3345 while True:
3332 while True:
3346 p = self.changelog.parents(n)
3333 p = self.changelog.parents(n)
3347 if p[1] != nullid or p[0] == nullid:
3334 if p[1] != nullid or p[0] == nullid:
3348 b.append((t, n, p[0], p[1]))
3335 b.append((t, n, p[0], p[1]))
3349 break
3336 break
3350 n = p[0]
3337 n = p[0]
3351 return b
3338 return b
3352
3339
3353 def between(self, pairs):
3340 def between(self, pairs):
3354 r = []
3341 r = []
3355
3342
3356 for top, bottom in pairs:
3343 for top, bottom in pairs:
3357 n, l, i = top, [], 0
3344 n, l, i = top, [], 0
3358 f = 1
3345 f = 1
3359
3346
3360 while n != bottom and n != nullid:
3347 while n != bottom and n != nullid:
3361 p = self.changelog.parents(n)[0]
3348 p = self.changelog.parents(n)[0]
3362 if i == f:
3349 if i == f:
3363 l.append(n)
3350 l.append(n)
3364 f = f * 2
3351 f = f * 2
3365 n = p
3352 n = p
3366 i += 1
3353 i += 1
3367
3354
3368 r.append(l)
3355 r.append(l)
3369
3356
3370 return r
3357 return r
3371
3358
3372 def checkpush(self, pushop):
3359 def checkpush(self, pushop):
3373 """Extensions can override this function if additional checks have
3360 """Extensions can override this function if additional checks have
3374 to be performed before pushing, or call it if they override push
3361 to be performed before pushing, or call it if they override push
3375 command.
3362 command.
3376 """
3363 """
3377
3364
3378 @unfilteredpropertycache
3365 @unfilteredpropertycache
3379 def prepushoutgoinghooks(self):
3366 def prepushoutgoinghooks(self):
3380 """Return util.hooks consists of a pushop with repo, remote, outgoing
3367 """Return util.hooks consists of a pushop with repo, remote, outgoing
3381 methods, which are called before pushing changesets.
3368 methods, which are called before pushing changesets.
3382 """
3369 """
3383 return util.hooks()
3370 return util.hooks()
3384
3371
3385 def pushkey(self, namespace, key, old, new):
3372 def pushkey(self, namespace, key, old, new):
3386 try:
3373 try:
3387 tr = self.currenttransaction()
3374 tr = self.currenttransaction()
3388 hookargs = {}
3375 hookargs = {}
3389 if tr is not None:
3376 if tr is not None:
3390 hookargs.update(tr.hookargs)
3377 hookargs.update(tr.hookargs)
3391 hookargs = pycompat.strkwargs(hookargs)
3378 hookargs = pycompat.strkwargs(hookargs)
3392 hookargs['namespace'] = namespace
3379 hookargs['namespace'] = namespace
3393 hookargs['key'] = key
3380 hookargs['key'] = key
3394 hookargs['old'] = old
3381 hookargs['old'] = old
3395 hookargs['new'] = new
3382 hookargs['new'] = new
3396 self.hook(b'prepushkey', throw=True, **hookargs)
3383 self.hook(b'prepushkey', throw=True, **hookargs)
3397 except error.HookAbort as exc:
3384 except error.HookAbort as exc:
3398 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3385 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3399 if exc.hint:
3386 if exc.hint:
3400 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3387 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3401 return False
3388 return False
3402 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3389 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3403 ret = pushkey.push(self, namespace, key, old, new)
3390 ret = pushkey.push(self, namespace, key, old, new)
3404
3391
3405 def runhook(unused_success):
3392 def runhook(unused_success):
3406 self.hook(
3393 self.hook(
3407 b'pushkey',
3394 b'pushkey',
3408 namespace=namespace,
3395 namespace=namespace,
3409 key=key,
3396 key=key,
3410 old=old,
3397 old=old,
3411 new=new,
3398 new=new,
3412 ret=ret,
3399 ret=ret,
3413 )
3400 )
3414
3401
3415 self._afterlock(runhook)
3402 self._afterlock(runhook)
3416 return ret
3403 return ret
3417
3404
3418 def listkeys(self, namespace):
3405 def listkeys(self, namespace):
3419 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3406 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3420 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3407 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3421 values = pushkey.list(self, namespace)
3408 values = pushkey.list(self, namespace)
3422 self.hook(b'listkeys', namespace=namespace, values=values)
3409 self.hook(b'listkeys', namespace=namespace, values=values)
3423 return values
3410 return values
3424
3411
3425 def debugwireargs(self, one, two, three=None, four=None, five=None):
3412 def debugwireargs(self, one, two, three=None, four=None, five=None):
3426 '''used to test argument passing over the wire'''
3413 '''used to test argument passing over the wire'''
3427 return b"%s %s %s %s %s" % (
3414 return b"%s %s %s %s %s" % (
3428 one,
3415 one,
3429 two,
3416 two,
3430 pycompat.bytestr(three),
3417 pycompat.bytestr(three),
3431 pycompat.bytestr(four),
3418 pycompat.bytestr(four),
3432 pycompat.bytestr(five),
3419 pycompat.bytestr(five),
3433 )
3420 )
3434
3421
3435 def savecommitmessage(self, text):
3422 def savecommitmessage(self, text):
3436 fp = self.vfs(b'last-message.txt', b'wb')
3423 fp = self.vfs(b'last-message.txt', b'wb')
3437 try:
3424 try:
3438 fp.write(text)
3425 fp.write(text)
3439 finally:
3426 finally:
3440 fp.close()
3427 fp.close()
3441 return self.pathto(fp.name[len(self.root) + 1 :])
3428 return self.pathto(fp.name[len(self.root) + 1 :])
3442
3429
3443
3430
3444 # used to avoid circular references so destructors work
3431 # used to avoid circular references so destructors work
3445 def aftertrans(files):
3432 def aftertrans(files):
3446 renamefiles = [tuple(t) for t in files]
3433 renamefiles = [tuple(t) for t in files]
3447
3434
3448 def a():
3435 def a():
3449 for vfs, src, dest in renamefiles:
3436 for vfs, src, dest in renamefiles:
3450 # if src and dest refer to a same file, vfs.rename is a no-op,
3437 # if src and dest refer to a same file, vfs.rename is a no-op,
3451 # leaving both src and dest on disk. delete dest to make sure
3438 # leaving both src and dest on disk. delete dest to make sure
3452 # the rename couldn't be such a no-op.
3439 # the rename couldn't be such a no-op.
3453 vfs.tryunlink(dest)
3440 vfs.tryunlink(dest)
3454 try:
3441 try:
3455 vfs.rename(src, dest)
3442 vfs.rename(src, dest)
3456 except OSError: # journal file does not yet exist
3443 except OSError: # journal file does not yet exist
3457 pass
3444 pass
3458
3445
3459 return a
3446 return a
3460
3447
3461
3448
3462 def undoname(fn):
3449 def undoname(fn):
3463 base, name = os.path.split(fn)
3450 base, name = os.path.split(fn)
3464 assert name.startswith(b'journal')
3451 assert name.startswith(b'journal')
3465 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3452 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3466
3453
3467
3454
3468 def instance(ui, path, create, intents=None, createopts=None):
3455 def instance(ui, path, create, intents=None, createopts=None):
3469 localpath = util.urllocalpath(path)
3456 localpath = util.urllocalpath(path)
3470 if create:
3457 if create:
3471 createrepository(ui, localpath, createopts=createopts)
3458 createrepository(ui, localpath, createopts=createopts)
3472
3459
3473 return makelocalrepository(ui, localpath, intents=intents)
3460 return makelocalrepository(ui, localpath, intents=intents)
3474
3461
3475
3462
3476 def islocal(path):
3463 def islocal(path):
3477 return True
3464 return True
3478
3465
3479
3466
3480 def defaultcreateopts(ui, createopts=None):
3467 def defaultcreateopts(ui, createopts=None):
3481 """Populate the default creation options for a repository.
3468 """Populate the default creation options for a repository.
3482
3469
3483 A dictionary of explicitly requested creation options can be passed
3470 A dictionary of explicitly requested creation options can be passed
3484 in. Missing keys will be populated.
3471 in. Missing keys will be populated.
3485 """
3472 """
3486 createopts = dict(createopts or {})
3473 createopts = dict(createopts or {})
3487
3474
3488 if b'backend' not in createopts:
3475 if b'backend' not in createopts:
3489 # experimental config: storage.new-repo-backend
3476 # experimental config: storage.new-repo-backend
3490 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3477 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3491
3478
3492 return createopts
3479 return createopts
3493
3480
3494
3481
3495 def newreporequirements(ui, createopts):
3482 def newreporequirements(ui, createopts):
3496 """Determine the set of requirements for a new local repository.
3483 """Determine the set of requirements for a new local repository.
3497
3484
3498 Extensions can wrap this function to specify custom requirements for
3485 Extensions can wrap this function to specify custom requirements for
3499 new repositories.
3486 new repositories.
3500 """
3487 """
3501 # If the repo is being created from a shared repository, we copy
3488 # If the repo is being created from a shared repository, we copy
3502 # its requirements.
3489 # its requirements.
3503 if b'sharedrepo' in createopts:
3490 if b'sharedrepo' in createopts:
3504 requirements = set(createopts[b'sharedrepo'].requirements)
3491 requirements = set(createopts[b'sharedrepo'].requirements)
3505 if createopts.get(b'sharedrelative'):
3492 if createopts.get(b'sharedrelative'):
3506 requirements.add(b'relshared')
3493 requirements.add(b'relshared')
3507 else:
3494 else:
3508 requirements.add(b'shared')
3495 requirements.add(b'shared')
3509
3496
3510 return requirements
3497 return requirements
3511
3498
3512 if b'backend' not in createopts:
3499 if b'backend' not in createopts:
3513 raise error.ProgrammingError(
3500 raise error.ProgrammingError(
3514 b'backend key not present in createopts; '
3501 b'backend key not present in createopts; '
3515 b'was defaultcreateopts() called?'
3502 b'was defaultcreateopts() called?'
3516 )
3503 )
3517
3504
3518 if createopts[b'backend'] != b'revlogv1':
3505 if createopts[b'backend'] != b'revlogv1':
3519 raise error.Abort(
3506 raise error.Abort(
3520 _(
3507 _(
3521 b'unable to determine repository requirements for '
3508 b'unable to determine repository requirements for '
3522 b'storage backend: %s'
3509 b'storage backend: %s'
3523 )
3510 )
3524 % createopts[b'backend']
3511 % createopts[b'backend']
3525 )
3512 )
3526
3513
3527 requirements = {b'revlogv1'}
3514 requirements = {b'revlogv1'}
3528 if ui.configbool(b'format', b'usestore'):
3515 if ui.configbool(b'format', b'usestore'):
3529 requirements.add(b'store')
3516 requirements.add(b'store')
3530 if ui.configbool(b'format', b'usefncache'):
3517 if ui.configbool(b'format', b'usefncache'):
3531 requirements.add(b'fncache')
3518 requirements.add(b'fncache')
3532 if ui.configbool(b'format', b'dotencode'):
3519 if ui.configbool(b'format', b'dotencode'):
3533 requirements.add(b'dotencode')
3520 requirements.add(b'dotencode')
3534
3521
3535 compengine = ui.config(b'format', b'revlog-compression')
3522 compengine = ui.config(b'format', b'revlog-compression')
3536 if compengine not in util.compengines:
3523 if compengine not in util.compengines:
3537 raise error.Abort(
3524 raise error.Abort(
3538 _(
3525 _(
3539 b'compression engine %s defined by '
3526 b'compression engine %s defined by '
3540 b'format.revlog-compression not available'
3527 b'format.revlog-compression not available'
3541 )
3528 )
3542 % compengine,
3529 % compengine,
3543 hint=_(
3530 hint=_(
3544 b'run "hg debuginstall" to list available '
3531 b'run "hg debuginstall" to list available '
3545 b'compression engines'
3532 b'compression engines'
3546 ),
3533 ),
3547 )
3534 )
3548
3535
3549 # zlib is the historical default and doesn't need an explicit requirement.
3536 # zlib is the historical default and doesn't need an explicit requirement.
3550 elif compengine == b'zstd':
3537 elif compengine == b'zstd':
3551 requirements.add(b'revlog-compression-zstd')
3538 requirements.add(b'revlog-compression-zstd')
3552 elif compengine != b'zlib':
3539 elif compengine != b'zlib':
3553 requirements.add(b'exp-compression-%s' % compengine)
3540 requirements.add(b'exp-compression-%s' % compengine)
3554
3541
3555 if scmutil.gdinitconfig(ui):
3542 if scmutil.gdinitconfig(ui):
3556 requirements.add(b'generaldelta')
3543 requirements.add(b'generaldelta')
3557 if ui.configbool(b'format', b'sparse-revlog'):
3544 if ui.configbool(b'format', b'sparse-revlog'):
3558 requirements.add(SPARSEREVLOG_REQUIREMENT)
3545 requirements.add(SPARSEREVLOG_REQUIREMENT)
3559
3546
3560 # experimental config: format.exp-use-side-data
3547 # experimental config: format.exp-use-side-data
3561 if ui.configbool(b'format', b'exp-use-side-data'):
3548 if ui.configbool(b'format', b'exp-use-side-data'):
3562 requirements.add(SIDEDATA_REQUIREMENT)
3549 requirements.add(SIDEDATA_REQUIREMENT)
3563 # experimental config: format.exp-use-copies-side-data-changeset
3550 # experimental config: format.exp-use-copies-side-data-changeset
3564 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3551 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3565 requirements.add(SIDEDATA_REQUIREMENT)
3552 requirements.add(SIDEDATA_REQUIREMENT)
3566 requirements.add(COPIESSDC_REQUIREMENT)
3553 requirements.add(COPIESSDC_REQUIREMENT)
3567 if ui.configbool(b'experimental', b'treemanifest'):
3554 if ui.configbool(b'experimental', b'treemanifest'):
3568 requirements.add(b'treemanifest')
3555 requirements.add(b'treemanifest')
3569
3556
3570 revlogv2 = ui.config(b'experimental', b'revlogv2')
3557 revlogv2 = ui.config(b'experimental', b'revlogv2')
3571 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3558 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3572 requirements.remove(b'revlogv1')
3559 requirements.remove(b'revlogv1')
3573 # generaldelta is implied by revlogv2.
3560 # generaldelta is implied by revlogv2.
3574 requirements.discard(b'generaldelta')
3561 requirements.discard(b'generaldelta')
3575 requirements.add(REVLOGV2_REQUIREMENT)
3562 requirements.add(REVLOGV2_REQUIREMENT)
3576 # experimental config: format.internal-phase
3563 # experimental config: format.internal-phase
3577 if ui.configbool(b'format', b'internal-phase'):
3564 if ui.configbool(b'format', b'internal-phase'):
3578 requirements.add(b'internal-phase')
3565 requirements.add(b'internal-phase')
3579
3566
3580 if createopts.get(b'narrowfiles'):
3567 if createopts.get(b'narrowfiles'):
3581 requirements.add(repository.NARROW_REQUIREMENT)
3568 requirements.add(repository.NARROW_REQUIREMENT)
3582
3569
3583 if createopts.get(b'lfs'):
3570 if createopts.get(b'lfs'):
3584 requirements.add(b'lfs')
3571 requirements.add(b'lfs')
3585
3572
3586 if ui.configbool(b'format', b'bookmarks-in-store'):
3573 if ui.configbool(b'format', b'bookmarks-in-store'):
3587 requirements.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3574 requirements.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3588
3575
3589 return requirements
3576 return requirements
3590
3577
3591
3578
3592 def filterknowncreateopts(ui, createopts):
3579 def filterknowncreateopts(ui, createopts):
3593 """Filters a dict of repo creation options against options that are known.
3580 """Filters a dict of repo creation options against options that are known.
3594
3581
3595 Receives a dict of repo creation options and returns a dict of those
3582 Receives a dict of repo creation options and returns a dict of those
3596 options that we don't know how to handle.
3583 options that we don't know how to handle.
3597
3584
3598 This function is called as part of repository creation. If the
3585 This function is called as part of repository creation. If the
3599 returned dict contains any items, repository creation will not
3586 returned dict contains any items, repository creation will not
3600 be allowed, as it means there was a request to create a repository
3587 be allowed, as it means there was a request to create a repository
3601 with options not recognized by loaded code.
3588 with options not recognized by loaded code.
3602
3589
3603 Extensions can wrap this function to filter out creation options
3590 Extensions can wrap this function to filter out creation options
3604 they know how to handle.
3591 they know how to handle.
3605 """
3592 """
3606 known = {
3593 known = {
3607 b'backend',
3594 b'backend',
3608 b'lfs',
3595 b'lfs',
3609 b'narrowfiles',
3596 b'narrowfiles',
3610 b'sharedrepo',
3597 b'sharedrepo',
3611 b'sharedrelative',
3598 b'sharedrelative',
3612 b'shareditems',
3599 b'shareditems',
3613 b'shallowfilestore',
3600 b'shallowfilestore',
3614 }
3601 }
3615
3602
3616 return {k: v for k, v in createopts.items() if k not in known}
3603 return {k: v for k, v in createopts.items() if k not in known}
3617
3604
3618
3605
3619 def createrepository(ui, path, createopts=None):
3606 def createrepository(ui, path, createopts=None):
3620 """Create a new repository in a vfs.
3607 """Create a new repository in a vfs.
3621
3608
3622 ``path`` path to the new repo's working directory.
3609 ``path`` path to the new repo's working directory.
3623 ``createopts`` options for the new repository.
3610 ``createopts`` options for the new repository.
3624
3611
3625 The following keys for ``createopts`` are recognized:
3612 The following keys for ``createopts`` are recognized:
3626
3613
3627 backend
3614 backend
3628 The storage backend to use.
3615 The storage backend to use.
3629 lfs
3616 lfs
3630 Repository will be created with ``lfs`` requirement. The lfs extension
3617 Repository will be created with ``lfs`` requirement. The lfs extension
3631 will automatically be loaded when the repository is accessed.
3618 will automatically be loaded when the repository is accessed.
3632 narrowfiles
3619 narrowfiles
3633 Set up repository to support narrow file storage.
3620 Set up repository to support narrow file storage.
3634 sharedrepo
3621 sharedrepo
3635 Repository object from which storage should be shared.
3622 Repository object from which storage should be shared.
3636 sharedrelative
3623 sharedrelative
3637 Boolean indicating if the path to the shared repo should be
3624 Boolean indicating if the path to the shared repo should be
3638 stored as relative. By default, the pointer to the "parent" repo
3625 stored as relative. By default, the pointer to the "parent" repo
3639 is stored as an absolute path.
3626 is stored as an absolute path.
3640 shareditems
3627 shareditems
3641 Set of items to share to the new repository (in addition to storage).
3628 Set of items to share to the new repository (in addition to storage).
3642 shallowfilestore
3629 shallowfilestore
3643 Indicates that storage for files should be shallow (not all ancestor
3630 Indicates that storage for files should be shallow (not all ancestor
3644 revisions are known).
3631 revisions are known).
3645 """
3632 """
3646 createopts = defaultcreateopts(ui, createopts=createopts)
3633 createopts = defaultcreateopts(ui, createopts=createopts)
3647
3634
3648 unknownopts = filterknowncreateopts(ui, createopts)
3635 unknownopts = filterknowncreateopts(ui, createopts)
3649
3636
3650 if not isinstance(unknownopts, dict):
3637 if not isinstance(unknownopts, dict):
3651 raise error.ProgrammingError(
3638 raise error.ProgrammingError(
3652 b'filterknowncreateopts() did not return a dict'
3639 b'filterknowncreateopts() did not return a dict'
3653 )
3640 )
3654
3641
3655 if unknownopts:
3642 if unknownopts:
3656 raise error.Abort(
3643 raise error.Abort(
3657 _(
3644 _(
3658 b'unable to create repository because of unknown '
3645 b'unable to create repository because of unknown '
3659 b'creation option: %s'
3646 b'creation option: %s'
3660 )
3647 )
3661 % b', '.join(sorted(unknownopts)),
3648 % b', '.join(sorted(unknownopts)),
3662 hint=_(b'is a required extension not loaded?'),
3649 hint=_(b'is a required extension not loaded?'),
3663 )
3650 )
3664
3651
3665 requirements = newreporequirements(ui, createopts=createopts)
3652 requirements = newreporequirements(ui, createopts=createopts)
3666
3653
3667 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3654 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3668
3655
3669 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3656 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3670 if hgvfs.exists():
3657 if hgvfs.exists():
3671 raise error.RepoError(_(b'repository %s already exists') % path)
3658 raise error.RepoError(_(b'repository %s already exists') % path)
3672
3659
3673 if b'sharedrepo' in createopts:
3660 if b'sharedrepo' in createopts:
3674 sharedpath = createopts[b'sharedrepo'].sharedpath
3661 sharedpath = createopts[b'sharedrepo'].sharedpath
3675
3662
3676 if createopts.get(b'sharedrelative'):
3663 if createopts.get(b'sharedrelative'):
3677 try:
3664 try:
3678 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3665 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3679 except (IOError, ValueError) as e:
3666 except (IOError, ValueError) as e:
3680 # ValueError is raised on Windows if the drive letters differ
3667 # ValueError is raised on Windows if the drive letters differ
3681 # on each path.
3668 # on each path.
3682 raise error.Abort(
3669 raise error.Abort(
3683 _(b'cannot calculate relative path'),
3670 _(b'cannot calculate relative path'),
3684 hint=stringutil.forcebytestr(e),
3671 hint=stringutil.forcebytestr(e),
3685 )
3672 )
3686
3673
3687 if not wdirvfs.exists():
3674 if not wdirvfs.exists():
3688 wdirvfs.makedirs()
3675 wdirvfs.makedirs()
3689
3676
3690 hgvfs.makedir(notindexed=True)
3677 hgvfs.makedir(notindexed=True)
3691 if b'sharedrepo' not in createopts:
3678 if b'sharedrepo' not in createopts:
3692 hgvfs.mkdir(b'cache')
3679 hgvfs.mkdir(b'cache')
3693 hgvfs.mkdir(b'wcache')
3680 hgvfs.mkdir(b'wcache')
3694
3681
3695 if b'store' in requirements and b'sharedrepo' not in createopts:
3682 if b'store' in requirements and b'sharedrepo' not in createopts:
3696 hgvfs.mkdir(b'store')
3683 hgvfs.mkdir(b'store')
3697
3684
3698 # We create an invalid changelog outside the store so very old
3685 # We create an invalid changelog outside the store so very old
3699 # Mercurial versions (which didn't know about the requirements
3686 # Mercurial versions (which didn't know about the requirements
3700 # file) encounter an error on reading the changelog. This
3687 # file) encounter an error on reading the changelog. This
3701 # effectively locks out old clients and prevents them from
3688 # effectively locks out old clients and prevents them from
3702 # mucking with a repo in an unknown format.
3689 # mucking with a repo in an unknown format.
3703 #
3690 #
3704 # The revlog header has version 2, which won't be recognized by
3691 # The revlog header has version 2, which won't be recognized by
3705 # such old clients.
3692 # such old clients.
3706 hgvfs.append(
3693 hgvfs.append(
3707 b'00changelog.i',
3694 b'00changelog.i',
3708 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3695 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3709 b'layout',
3696 b'layout',
3710 )
3697 )
3711
3698
3712 scmutil.writerequires(hgvfs, requirements)
3699 scmutil.writerequires(hgvfs, requirements)
3713
3700
3714 # Write out file telling readers where to find the shared store.
3701 # Write out file telling readers where to find the shared store.
3715 if b'sharedrepo' in createopts:
3702 if b'sharedrepo' in createopts:
3716 hgvfs.write(b'sharedpath', sharedpath)
3703 hgvfs.write(b'sharedpath', sharedpath)
3717
3704
3718 if createopts.get(b'shareditems'):
3705 if createopts.get(b'shareditems'):
3719 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3706 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3720 hgvfs.write(b'shared', shared)
3707 hgvfs.write(b'shared', shared)
3721
3708
3722
3709
3723 def poisonrepository(repo):
3710 def poisonrepository(repo):
3724 """Poison a repository instance so it can no longer be used."""
3711 """Poison a repository instance so it can no longer be used."""
3725 # Perform any cleanup on the instance.
3712 # Perform any cleanup on the instance.
3726 repo.close()
3713 repo.close()
3727
3714
3728 # Our strategy is to replace the type of the object with one that
3715 # Our strategy is to replace the type of the object with one that
3729 # has all attribute lookups result in error.
3716 # has all attribute lookups result in error.
3730 #
3717 #
3731 # But we have to allow the close() method because some constructors
3718 # But we have to allow the close() method because some constructors
3732 # of repos call close() on repo references.
3719 # of repos call close() on repo references.
3733 class poisonedrepository(object):
3720 class poisonedrepository(object):
3734 def __getattribute__(self, item):
3721 def __getattribute__(self, item):
3735 if item == 'close':
3722 if item == 'close':
3736 return object.__getattribute__(self, item)
3723 return object.__getattribute__(self, item)
3737
3724
3738 raise error.ProgrammingError(
3725 raise error.ProgrammingError(
3739 b'repo instances should not be used after unshare'
3726 b'repo instances should not be used after unshare'
3740 )
3727 )
3741
3728
3742 def close(self):
3729 def close(self):
3743 pass
3730 pass
3744
3731
3745 # We may have a repoview, which intercepts __setattr__. So be sure
3732 # We may have a repoview, which intercepts __setattr__. So be sure
3746 # we operate at the lowest level possible.
3733 # we operate at the lowest level possible.
3747 object.__setattr__(repo, '__class__', poisonedrepository)
3734 object.__setattr__(repo, '__class__', poisonedrepository)
General Comments 0
You need to be logged in to leave comments. Login now