##// END OF EJS Templates
status: pre-indent the dirstate status code...
marmoute -
r51028:21b6ce3a default
parent child Browse files
Show More
@@ -1,3144 +1,3145 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 Olivia Mackall <olivia@selenic.com>
3 # Copyright 2006, 2007 Olivia Mackall <olivia@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8
8
9 import filecmp
9 import filecmp
10 import os
10 import os
11 import stat
11 import stat
12
12
13 from .i18n import _
13 from .i18n import _
14 from .node import (
14 from .node import (
15 hex,
15 hex,
16 nullrev,
16 nullrev,
17 short,
17 short,
18 )
18 )
19 from .pycompat import (
19 from .pycompat import (
20 getattr,
20 getattr,
21 )
21 )
22 from . import (
22 from . import (
23 dagop,
23 dagop,
24 encoding,
24 encoding,
25 error,
25 error,
26 fileset,
26 fileset,
27 match as matchmod,
27 match as matchmod,
28 mergestate as mergestatemod,
28 mergestate as mergestatemod,
29 metadata,
29 metadata,
30 obsolete as obsmod,
30 obsolete as obsmod,
31 patch,
31 patch,
32 pathutil,
32 pathutil,
33 phases,
33 phases,
34 repoview,
34 repoview,
35 scmutil,
35 scmutil,
36 sparse,
36 sparse,
37 subrepo,
37 subrepo,
38 subrepoutil,
38 subrepoutil,
39 util,
39 util,
40 )
40 )
41 from .utils import (
41 from .utils import (
42 dateutil,
42 dateutil,
43 stringutil,
43 stringutil,
44 )
44 )
45 from .dirstateutils import (
45 from .dirstateutils import (
46 timestamp,
46 timestamp,
47 )
47 )
48
48
49 propertycache = util.propertycache
49 propertycache = util.propertycache
50
50
51
51
52 class basectx:
52 class basectx:
53 """A basectx object represents the common logic for its children:
53 """A basectx object represents the common logic for its children:
54 changectx: read-only context that is already present in the repo,
54 changectx: read-only context that is already present in the repo,
55 workingctx: a context that represents the working directory and can
55 workingctx: a context that represents the working directory and can
56 be committed,
56 be committed,
57 memctx: a context that represents changes in-memory and can also
57 memctx: a context that represents changes in-memory and can also
58 be committed."""
58 be committed."""
59
59
60 def __init__(self, repo):
60 def __init__(self, repo):
61 self._repo = repo
61 self._repo = repo
62
62
63 def __bytes__(self):
63 def __bytes__(self):
64 return short(self.node())
64 return short(self.node())
65
65
66 __str__ = encoding.strmethod(__bytes__)
66 __str__ = encoding.strmethod(__bytes__)
67
67
68 def __repr__(self):
68 def __repr__(self):
69 return "<%s %s>" % (type(self).__name__, str(self))
69 return "<%s %s>" % (type(self).__name__, str(self))
70
70
71 def __eq__(self, other):
71 def __eq__(self, other):
72 try:
72 try:
73 return type(self) == type(other) and self._rev == other._rev
73 return type(self) == type(other) and self._rev == other._rev
74 except AttributeError:
74 except AttributeError:
75 return False
75 return False
76
76
77 def __ne__(self, other):
77 def __ne__(self, other):
78 return not (self == other)
78 return not (self == other)
79
79
80 def __contains__(self, key):
80 def __contains__(self, key):
81 return key in self._manifest
81 return key in self._manifest
82
82
83 def __getitem__(self, key):
83 def __getitem__(self, key):
84 return self.filectx(key)
84 return self.filectx(key)
85
85
86 def __iter__(self):
86 def __iter__(self):
87 return iter(self._manifest)
87 return iter(self._manifest)
88
88
89 def _buildstatusmanifest(self, status):
89 def _buildstatusmanifest(self, status):
90 """Builds a manifest that includes the given status results, if this is
90 """Builds a manifest that includes the given status results, if this is
91 a working copy context. For non-working copy contexts, it just returns
91 a working copy context. For non-working copy contexts, it just returns
92 the normal manifest."""
92 the normal manifest."""
93 return self.manifest()
93 return self.manifest()
94
94
95 def _matchstatus(self, other, match):
95 def _matchstatus(self, other, match):
96 """This internal method provides a way for child objects to override the
96 """This internal method provides a way for child objects to override the
97 match operator.
97 match operator.
98 """
98 """
99 return match
99 return match
100
100
101 def _buildstatus(
101 def _buildstatus(
102 self, other, s, match, listignored, listclean, listunknown
102 self, other, s, match, listignored, listclean, listunknown
103 ):
103 ):
104 """build a status with respect to another context"""
104 """build a status with respect to another context"""
105 # Load earliest manifest first for caching reasons. More specifically,
105 # Load earliest manifest first for caching reasons. More specifically,
106 # if you have revisions 1000 and 1001, 1001 is probably stored as a
106 # if you have revisions 1000 and 1001, 1001 is probably stored as a
107 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
107 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
108 # 1000 and cache it so that when you read 1001, we just need to apply a
108 # 1000 and cache it so that when you read 1001, we just need to apply a
109 # delta to what's in the cache. So that's one full reconstruction + one
109 # delta to what's in the cache. So that's one full reconstruction + one
110 # delta application.
110 # delta application.
111 mf2 = None
111 mf2 = None
112 if self.rev() is not None and self.rev() < other.rev():
112 if self.rev() is not None and self.rev() < other.rev():
113 mf2 = self._buildstatusmanifest(s)
113 mf2 = self._buildstatusmanifest(s)
114 mf1 = other._buildstatusmanifest(s)
114 mf1 = other._buildstatusmanifest(s)
115 if mf2 is None:
115 if mf2 is None:
116 mf2 = self._buildstatusmanifest(s)
116 mf2 = self._buildstatusmanifest(s)
117
117
118 modified, added = [], []
118 modified, added = [], []
119 removed = []
119 removed = []
120 clean = []
120 clean = []
121 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
121 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
122 deletedset = set(deleted)
122 deletedset = set(deleted)
123 d = mf1.diff(mf2, match=match, clean=listclean)
123 d = mf1.diff(mf2, match=match, clean=listclean)
124 for fn, value in d.items():
124 for fn, value in d.items():
125 if fn in deletedset:
125 if fn in deletedset:
126 continue
126 continue
127 if value is None:
127 if value is None:
128 clean.append(fn)
128 clean.append(fn)
129 continue
129 continue
130 (node1, flag1), (node2, flag2) = value
130 (node1, flag1), (node2, flag2) = value
131 if node1 is None:
131 if node1 is None:
132 added.append(fn)
132 added.append(fn)
133 elif node2 is None:
133 elif node2 is None:
134 removed.append(fn)
134 removed.append(fn)
135 elif flag1 != flag2:
135 elif flag1 != flag2:
136 modified.append(fn)
136 modified.append(fn)
137 elif node2 not in self._repo.nodeconstants.wdirfilenodeids:
137 elif node2 not in self._repo.nodeconstants.wdirfilenodeids:
138 # When comparing files between two commits, we save time by
138 # When comparing files between two commits, we save time by
139 # not comparing the file contents when the nodeids differ.
139 # not comparing the file contents when the nodeids differ.
140 # Note that this means we incorrectly report a reverted change
140 # Note that this means we incorrectly report a reverted change
141 # to a file as a modification.
141 # to a file as a modification.
142 modified.append(fn)
142 modified.append(fn)
143 elif self[fn].cmp(other[fn]):
143 elif self[fn].cmp(other[fn]):
144 modified.append(fn)
144 modified.append(fn)
145 else:
145 else:
146 clean.append(fn)
146 clean.append(fn)
147
147
148 if removed:
148 if removed:
149 # need to filter files if they are already reported as removed
149 # need to filter files if they are already reported as removed
150 unknown = [
150 unknown = [
151 fn
151 fn
152 for fn in unknown
152 for fn in unknown
153 if fn not in mf1 and (not match or match(fn))
153 if fn not in mf1 and (not match or match(fn))
154 ]
154 ]
155 ignored = [
155 ignored = [
156 fn
156 fn
157 for fn in ignored
157 for fn in ignored
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 # if they're deleted, don't report them as removed
160 # if they're deleted, don't report them as removed
161 removed = [fn for fn in removed if fn not in deletedset]
161 removed = [fn for fn in removed if fn not in deletedset]
162
162
163 return scmutil.status(
163 return scmutil.status(
164 modified, added, removed, deleted, unknown, ignored, clean
164 modified, added, removed, deleted, unknown, ignored, clean
165 )
165 )
166
166
167 @propertycache
167 @propertycache
168 def substate(self):
168 def substate(self):
169 return subrepoutil.state(self, self._repo.ui)
169 return subrepoutil.state(self, self._repo.ui)
170
170
171 def subrev(self, subpath):
171 def subrev(self, subpath):
172 return self.substate[subpath][1]
172 return self.substate[subpath][1]
173
173
174 def rev(self):
174 def rev(self):
175 return self._rev
175 return self._rev
176
176
177 def node(self):
177 def node(self):
178 return self._node
178 return self._node
179
179
180 def hex(self):
180 def hex(self):
181 return hex(self.node())
181 return hex(self.node())
182
182
183 def manifest(self):
183 def manifest(self):
184 return self._manifest
184 return self._manifest
185
185
186 def manifestctx(self):
186 def manifestctx(self):
187 return self._manifestctx
187 return self._manifestctx
188
188
189 def repo(self):
189 def repo(self):
190 return self._repo
190 return self._repo
191
191
192 def phasestr(self):
192 def phasestr(self):
193 return phases.phasenames[self.phase()]
193 return phases.phasenames[self.phase()]
194
194
195 def mutable(self):
195 def mutable(self):
196 return self.phase() > phases.public
196 return self.phase() > phases.public
197
197
198 def matchfileset(self, cwd, expr, badfn=None):
198 def matchfileset(self, cwd, expr, badfn=None):
199 return fileset.match(self, cwd, expr, badfn=badfn)
199 return fileset.match(self, cwd, expr, badfn=badfn)
200
200
201 def obsolete(self):
201 def obsolete(self):
202 """True if the changeset is obsolete"""
202 """True if the changeset is obsolete"""
203 return self.rev() in obsmod.getrevs(self._repo, b'obsolete')
203 return self.rev() in obsmod.getrevs(self._repo, b'obsolete')
204
204
205 def extinct(self):
205 def extinct(self):
206 """True if the changeset is extinct"""
206 """True if the changeset is extinct"""
207 return self.rev() in obsmod.getrevs(self._repo, b'extinct')
207 return self.rev() in obsmod.getrevs(self._repo, b'extinct')
208
208
209 def orphan(self):
209 def orphan(self):
210 """True if the changeset is not obsolete, but its ancestor is"""
210 """True if the changeset is not obsolete, but its ancestor is"""
211 return self.rev() in obsmod.getrevs(self._repo, b'orphan')
211 return self.rev() in obsmod.getrevs(self._repo, b'orphan')
212
212
213 def phasedivergent(self):
213 def phasedivergent(self):
214 """True if the changeset tries to be a successor of a public changeset
214 """True if the changeset tries to be a successor of a public changeset
215
215
216 Only non-public and non-obsolete changesets may be phase-divergent.
216 Only non-public and non-obsolete changesets may be phase-divergent.
217 """
217 """
218 return self.rev() in obsmod.getrevs(self._repo, b'phasedivergent')
218 return self.rev() in obsmod.getrevs(self._repo, b'phasedivergent')
219
219
220 def contentdivergent(self):
220 def contentdivergent(self):
221 """Is a successor of a changeset with multiple possible successor sets
221 """Is a successor of a changeset with multiple possible successor sets
222
222
223 Only non-public and non-obsolete changesets may be content-divergent.
223 Only non-public and non-obsolete changesets may be content-divergent.
224 """
224 """
225 return self.rev() in obsmod.getrevs(self._repo, b'contentdivergent')
225 return self.rev() in obsmod.getrevs(self._repo, b'contentdivergent')
226
226
227 def isunstable(self):
227 def isunstable(self):
228 """True if the changeset is either orphan, phase-divergent or
228 """True if the changeset is either orphan, phase-divergent or
229 content-divergent"""
229 content-divergent"""
230 return self.orphan() or self.phasedivergent() or self.contentdivergent()
230 return self.orphan() or self.phasedivergent() or self.contentdivergent()
231
231
232 def instabilities(self):
232 def instabilities(self):
233 """return the list of instabilities affecting this changeset.
233 """return the list of instabilities affecting this changeset.
234
234
235 Instabilities are returned as strings. possible values are:
235 Instabilities are returned as strings. possible values are:
236 - orphan,
236 - orphan,
237 - phase-divergent,
237 - phase-divergent,
238 - content-divergent.
238 - content-divergent.
239 """
239 """
240 instabilities = []
240 instabilities = []
241 if self.orphan():
241 if self.orphan():
242 instabilities.append(b'orphan')
242 instabilities.append(b'orphan')
243 if self.phasedivergent():
243 if self.phasedivergent():
244 instabilities.append(b'phase-divergent')
244 instabilities.append(b'phase-divergent')
245 if self.contentdivergent():
245 if self.contentdivergent():
246 instabilities.append(b'content-divergent')
246 instabilities.append(b'content-divergent')
247 return instabilities
247 return instabilities
248
248
249 def parents(self):
249 def parents(self):
250 """return contexts for each parent changeset"""
250 """return contexts for each parent changeset"""
251 return self._parents
251 return self._parents
252
252
253 def p1(self):
253 def p1(self):
254 return self._parents[0]
254 return self._parents[0]
255
255
256 def p2(self):
256 def p2(self):
257 parents = self._parents
257 parents = self._parents
258 if len(parents) == 2:
258 if len(parents) == 2:
259 return parents[1]
259 return parents[1]
260 return self._repo[nullrev]
260 return self._repo[nullrev]
261
261
262 def _fileinfo(self, path):
262 def _fileinfo(self, path):
263 if '_manifest' in self.__dict__:
263 if '_manifest' in self.__dict__:
264 try:
264 try:
265 return self._manifest.find(path)
265 return self._manifest.find(path)
266 except KeyError:
266 except KeyError:
267 raise error.ManifestLookupError(
267 raise error.ManifestLookupError(
268 self._node or b'None', path, _(b'not found in manifest')
268 self._node or b'None', path, _(b'not found in manifest')
269 )
269 )
270 if '_manifestdelta' in self.__dict__ or path in self.files():
270 if '_manifestdelta' in self.__dict__ or path in self.files():
271 if path in self._manifestdelta:
271 if path in self._manifestdelta:
272 return (
272 return (
273 self._manifestdelta[path],
273 self._manifestdelta[path],
274 self._manifestdelta.flags(path),
274 self._manifestdelta.flags(path),
275 )
275 )
276 mfl = self._repo.manifestlog
276 mfl = self._repo.manifestlog
277 try:
277 try:
278 node, flag = mfl[self._changeset.manifest].find(path)
278 node, flag = mfl[self._changeset.manifest].find(path)
279 except KeyError:
279 except KeyError:
280 raise error.ManifestLookupError(
280 raise error.ManifestLookupError(
281 self._node or b'None', path, _(b'not found in manifest')
281 self._node or b'None', path, _(b'not found in manifest')
282 )
282 )
283
283
284 return node, flag
284 return node, flag
285
285
286 def filenode(self, path):
286 def filenode(self, path):
287 return self._fileinfo(path)[0]
287 return self._fileinfo(path)[0]
288
288
289 def flags(self, path):
289 def flags(self, path):
290 try:
290 try:
291 return self._fileinfo(path)[1]
291 return self._fileinfo(path)[1]
292 except error.LookupError:
292 except error.LookupError:
293 return b''
293 return b''
294
294
295 @propertycache
295 @propertycache
296 def _copies(self):
296 def _copies(self):
297 return metadata.computechangesetcopies(self)
297 return metadata.computechangesetcopies(self)
298
298
299 def p1copies(self):
299 def p1copies(self):
300 return self._copies[0]
300 return self._copies[0]
301
301
302 def p2copies(self):
302 def p2copies(self):
303 return self._copies[1]
303 return self._copies[1]
304
304
305 def sub(self, path, allowcreate=True):
305 def sub(self, path, allowcreate=True):
306 '''return a subrepo for the stored revision of path, never wdir()'''
306 '''return a subrepo for the stored revision of path, never wdir()'''
307 return subrepo.subrepo(self, path, allowcreate=allowcreate)
307 return subrepo.subrepo(self, path, allowcreate=allowcreate)
308
308
309 def nullsub(self, path, pctx):
309 def nullsub(self, path, pctx):
310 return subrepo.nullsubrepo(self, path, pctx)
310 return subrepo.nullsubrepo(self, path, pctx)
311
311
312 def workingsub(self, path):
312 def workingsub(self, path):
313 """return a subrepo for the stored revision, or wdir if this is a wdir
313 """return a subrepo for the stored revision, or wdir if this is a wdir
314 context.
314 context.
315 """
315 """
316 return subrepo.subrepo(self, path, allowwdir=True)
316 return subrepo.subrepo(self, path, allowwdir=True)
317
317
318 def match(
318 def match(
319 self,
319 self,
320 pats=None,
320 pats=None,
321 include=None,
321 include=None,
322 exclude=None,
322 exclude=None,
323 default=b'glob',
323 default=b'glob',
324 listsubrepos=False,
324 listsubrepos=False,
325 badfn=None,
325 badfn=None,
326 cwd=None,
326 cwd=None,
327 ):
327 ):
328 r = self._repo
328 r = self._repo
329 if not cwd:
329 if not cwd:
330 cwd = r.getcwd()
330 cwd = r.getcwd()
331 return matchmod.match(
331 return matchmod.match(
332 r.root,
332 r.root,
333 cwd,
333 cwd,
334 pats,
334 pats,
335 include,
335 include,
336 exclude,
336 exclude,
337 default,
337 default,
338 auditor=r.nofsauditor,
338 auditor=r.nofsauditor,
339 ctx=self,
339 ctx=self,
340 listsubrepos=listsubrepos,
340 listsubrepos=listsubrepos,
341 badfn=badfn,
341 badfn=badfn,
342 )
342 )
343
343
344 def diff(
344 def diff(
345 self,
345 self,
346 ctx2=None,
346 ctx2=None,
347 match=None,
347 match=None,
348 changes=None,
348 changes=None,
349 opts=None,
349 opts=None,
350 losedatafn=None,
350 losedatafn=None,
351 pathfn=None,
351 pathfn=None,
352 copy=None,
352 copy=None,
353 copysourcematch=None,
353 copysourcematch=None,
354 hunksfilterfn=None,
354 hunksfilterfn=None,
355 ):
355 ):
356 """Returns a diff generator for the given contexts and matcher"""
356 """Returns a diff generator for the given contexts and matcher"""
357 if ctx2 is None:
357 if ctx2 is None:
358 ctx2 = self.p1()
358 ctx2 = self.p1()
359 if ctx2 is not None:
359 if ctx2 is not None:
360 ctx2 = self._repo[ctx2]
360 ctx2 = self._repo[ctx2]
361 return patch.diff(
361 return patch.diff(
362 self._repo,
362 self._repo,
363 ctx2,
363 ctx2,
364 self,
364 self,
365 match=match,
365 match=match,
366 changes=changes,
366 changes=changes,
367 opts=opts,
367 opts=opts,
368 losedatafn=losedatafn,
368 losedatafn=losedatafn,
369 pathfn=pathfn,
369 pathfn=pathfn,
370 copy=copy,
370 copy=copy,
371 copysourcematch=copysourcematch,
371 copysourcematch=copysourcematch,
372 hunksfilterfn=hunksfilterfn,
372 hunksfilterfn=hunksfilterfn,
373 )
373 )
374
374
375 def dirs(self):
375 def dirs(self):
376 return self._manifest.dirs()
376 return self._manifest.dirs()
377
377
378 def hasdir(self, dir):
378 def hasdir(self, dir):
379 return self._manifest.hasdir(dir)
379 return self._manifest.hasdir(dir)
380
380
381 def status(
381 def status(
382 self,
382 self,
383 other=None,
383 other=None,
384 match=None,
384 match=None,
385 listignored=False,
385 listignored=False,
386 listclean=False,
386 listclean=False,
387 listunknown=False,
387 listunknown=False,
388 listsubrepos=False,
388 listsubrepos=False,
389 ):
389 ):
390 """return status of files between two nodes or node and working
390 """return status of files between two nodes or node and working
391 directory.
391 directory.
392
392
393 If other is None, compare this node with working directory.
393 If other is None, compare this node with working directory.
394
394
395 ctx1.status(ctx2) returns the status of change from ctx1 to ctx2
395 ctx1.status(ctx2) returns the status of change from ctx1 to ctx2
396
396
397 Returns a mercurial.scmutils.status object.
397 Returns a mercurial.scmutils.status object.
398
398
399 Data can be accessed using either tuple notation:
399 Data can be accessed using either tuple notation:
400
400
401 (modified, added, removed, deleted, unknown, ignored, clean)
401 (modified, added, removed, deleted, unknown, ignored, clean)
402
402
403 or direct attribute access:
403 or direct attribute access:
404
404
405 s.modified, s.added, ...
405 s.modified, s.added, ...
406 """
406 """
407
407
408 ctx1 = self
408 ctx1 = self
409 ctx2 = self._repo[other]
409 ctx2 = self._repo[other]
410
410
411 # This next code block is, admittedly, fragile logic that tests for
411 # This next code block is, admittedly, fragile logic that tests for
412 # reversing the contexts and wouldn't need to exist if it weren't for
412 # reversing the contexts and wouldn't need to exist if it weren't for
413 # the fast (and common) code path of comparing the working directory
413 # the fast (and common) code path of comparing the working directory
414 # with its first parent.
414 # with its first parent.
415 #
415 #
416 # What we're aiming for here is the ability to call:
416 # What we're aiming for here is the ability to call:
417 #
417 #
418 # workingctx.status(parentctx)
418 # workingctx.status(parentctx)
419 #
419 #
420 # If we always built the manifest for each context and compared those,
420 # If we always built the manifest for each context and compared those,
421 # then we'd be done. But the special case of the above call means we
421 # then we'd be done. But the special case of the above call means we
422 # just copy the manifest of the parent.
422 # just copy the manifest of the parent.
423 reversed = False
423 reversed = False
424 if not isinstance(ctx1, changectx) and isinstance(ctx2, changectx):
424 if not isinstance(ctx1, changectx) and isinstance(ctx2, changectx):
425 reversed = True
425 reversed = True
426 ctx1, ctx2 = ctx2, ctx1
426 ctx1, ctx2 = ctx2, ctx1
427
427
428 match = self._repo.narrowmatch(match)
428 match = self._repo.narrowmatch(match)
429 match = ctx2._matchstatus(ctx1, match)
429 match = ctx2._matchstatus(ctx1, match)
430 r = scmutil.status([], [], [], [], [], [], [])
430 r = scmutil.status([], [], [], [], [], [], [])
431 r = ctx2._buildstatus(
431 r = ctx2._buildstatus(
432 ctx1, r, match, listignored, listclean, listunknown
432 ctx1, r, match, listignored, listclean, listunknown
433 )
433 )
434
434
435 if reversed:
435 if reversed:
436 # Reverse added and removed. Clear deleted, unknown and ignored as
436 # Reverse added and removed. Clear deleted, unknown and ignored as
437 # these make no sense to reverse.
437 # these make no sense to reverse.
438 r = scmutil.status(
438 r = scmutil.status(
439 r.modified, r.removed, r.added, [], [], [], r.clean
439 r.modified, r.removed, r.added, [], [], [], r.clean
440 )
440 )
441
441
442 if listsubrepos:
442 if listsubrepos:
443 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
443 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
444 try:
444 try:
445 rev2 = ctx2.subrev(subpath)
445 rev2 = ctx2.subrev(subpath)
446 except KeyError:
446 except KeyError:
447 # A subrepo that existed in node1 was deleted between
447 # A subrepo that existed in node1 was deleted between
448 # node1 and node2 (inclusive). Thus, ctx2's substate
448 # node1 and node2 (inclusive). Thus, ctx2's substate
449 # won't contain that subpath. The best we can do ignore it.
449 # won't contain that subpath. The best we can do ignore it.
450 rev2 = None
450 rev2 = None
451 submatch = matchmod.subdirmatcher(subpath, match)
451 submatch = matchmod.subdirmatcher(subpath, match)
452 s = sub.status(
452 s = sub.status(
453 rev2,
453 rev2,
454 match=submatch,
454 match=submatch,
455 ignored=listignored,
455 ignored=listignored,
456 clean=listclean,
456 clean=listclean,
457 unknown=listunknown,
457 unknown=listunknown,
458 listsubrepos=True,
458 listsubrepos=True,
459 )
459 )
460 for k in (
460 for k in (
461 'modified',
461 'modified',
462 'added',
462 'added',
463 'removed',
463 'removed',
464 'deleted',
464 'deleted',
465 'unknown',
465 'unknown',
466 'ignored',
466 'ignored',
467 'clean',
467 'clean',
468 ):
468 ):
469 rfiles, sfiles = getattr(r, k), getattr(s, k)
469 rfiles, sfiles = getattr(r, k), getattr(s, k)
470 rfiles.extend(b"%s/%s" % (subpath, f) for f in sfiles)
470 rfiles.extend(b"%s/%s" % (subpath, f) for f in sfiles)
471
471
472 r.modified.sort()
472 r.modified.sort()
473 r.added.sort()
473 r.added.sort()
474 r.removed.sort()
474 r.removed.sort()
475 r.deleted.sort()
475 r.deleted.sort()
476 r.unknown.sort()
476 r.unknown.sort()
477 r.ignored.sort()
477 r.ignored.sort()
478 r.clean.sort()
478 r.clean.sort()
479
479
480 return r
480 return r
481
481
482 def mergestate(self, clean=False):
482 def mergestate(self, clean=False):
483 """Get a mergestate object for this context."""
483 """Get a mergestate object for this context."""
484 raise NotImplementedError(
484 raise NotImplementedError(
485 '%s does not implement mergestate()' % self.__class__
485 '%s does not implement mergestate()' % self.__class__
486 )
486 )
487
487
488 def isempty(self):
488 def isempty(self):
489 return not (
489 return not (
490 len(self.parents()) > 1
490 len(self.parents()) > 1
491 or self.branch() != self.p1().branch()
491 or self.branch() != self.p1().branch()
492 or self.closesbranch()
492 or self.closesbranch()
493 or self.files()
493 or self.files()
494 )
494 )
495
495
496
496
497 class changectx(basectx):
497 class changectx(basectx):
498 """A changecontext object makes access to data related to a particular
498 """A changecontext object makes access to data related to a particular
499 changeset convenient. It represents a read-only context already present in
499 changeset convenient. It represents a read-only context already present in
500 the repo."""
500 the repo."""
501
501
502 def __init__(self, repo, rev, node, maybe_filtered=True):
502 def __init__(self, repo, rev, node, maybe_filtered=True):
503 super(changectx, self).__init__(repo)
503 super(changectx, self).__init__(repo)
504 self._rev = rev
504 self._rev = rev
505 self._node = node
505 self._node = node
506 # When maybe_filtered is True, the revision might be affected by
506 # When maybe_filtered is True, the revision might be affected by
507 # changelog filtering and operation through the filtered changelog must be used.
507 # changelog filtering and operation through the filtered changelog must be used.
508 #
508 #
509 # When maybe_filtered is False, the revision has already been checked
509 # When maybe_filtered is False, the revision has already been checked
510 # against filtering and is not filtered. Operation through the
510 # against filtering and is not filtered. Operation through the
511 # unfiltered changelog might be used in some case.
511 # unfiltered changelog might be used in some case.
512 self._maybe_filtered = maybe_filtered
512 self._maybe_filtered = maybe_filtered
513
513
514 def __hash__(self):
514 def __hash__(self):
515 try:
515 try:
516 return hash(self._rev)
516 return hash(self._rev)
517 except AttributeError:
517 except AttributeError:
518 return id(self)
518 return id(self)
519
519
520 def __nonzero__(self):
520 def __nonzero__(self):
521 return self._rev != nullrev
521 return self._rev != nullrev
522
522
523 __bool__ = __nonzero__
523 __bool__ = __nonzero__
524
524
525 @propertycache
525 @propertycache
526 def _changeset(self):
526 def _changeset(self):
527 if self._maybe_filtered:
527 if self._maybe_filtered:
528 repo = self._repo
528 repo = self._repo
529 else:
529 else:
530 repo = self._repo.unfiltered()
530 repo = self._repo.unfiltered()
531 return repo.changelog.changelogrevision(self.rev())
531 return repo.changelog.changelogrevision(self.rev())
532
532
533 @propertycache
533 @propertycache
534 def _manifest(self):
534 def _manifest(self):
535 return self._manifestctx.read()
535 return self._manifestctx.read()
536
536
537 @property
537 @property
538 def _manifestctx(self):
538 def _manifestctx(self):
539 return self._repo.manifestlog[self._changeset.manifest]
539 return self._repo.manifestlog[self._changeset.manifest]
540
540
541 @propertycache
541 @propertycache
542 def _manifestdelta(self):
542 def _manifestdelta(self):
543 return self._manifestctx.readdelta()
543 return self._manifestctx.readdelta()
544
544
545 @propertycache
545 @propertycache
546 def _parents(self):
546 def _parents(self):
547 repo = self._repo
547 repo = self._repo
548 if self._maybe_filtered:
548 if self._maybe_filtered:
549 cl = repo.changelog
549 cl = repo.changelog
550 else:
550 else:
551 cl = repo.unfiltered().changelog
551 cl = repo.unfiltered().changelog
552
552
553 p1, p2 = cl.parentrevs(self._rev)
553 p1, p2 = cl.parentrevs(self._rev)
554 if p2 == nullrev:
554 if p2 == nullrev:
555 return [changectx(repo, p1, cl.node(p1), maybe_filtered=False)]
555 return [changectx(repo, p1, cl.node(p1), maybe_filtered=False)]
556 return [
556 return [
557 changectx(repo, p1, cl.node(p1), maybe_filtered=False),
557 changectx(repo, p1, cl.node(p1), maybe_filtered=False),
558 changectx(repo, p2, cl.node(p2), maybe_filtered=False),
558 changectx(repo, p2, cl.node(p2), maybe_filtered=False),
559 ]
559 ]
560
560
561 def changeset(self):
561 def changeset(self):
562 c = self._changeset
562 c = self._changeset
563 return (
563 return (
564 c.manifest,
564 c.manifest,
565 c.user,
565 c.user,
566 c.date,
566 c.date,
567 c.files,
567 c.files,
568 c.description,
568 c.description,
569 c.extra,
569 c.extra,
570 )
570 )
571
571
572 def manifestnode(self):
572 def manifestnode(self):
573 return self._changeset.manifest
573 return self._changeset.manifest
574
574
575 def user(self):
575 def user(self):
576 return self._changeset.user
576 return self._changeset.user
577
577
578 def date(self):
578 def date(self):
579 return self._changeset.date
579 return self._changeset.date
580
580
581 def files(self):
581 def files(self):
582 return self._changeset.files
582 return self._changeset.files
583
583
584 def filesmodified(self):
584 def filesmodified(self):
585 modified = set(self.files())
585 modified = set(self.files())
586 modified.difference_update(self.filesadded())
586 modified.difference_update(self.filesadded())
587 modified.difference_update(self.filesremoved())
587 modified.difference_update(self.filesremoved())
588 return sorted(modified)
588 return sorted(modified)
589
589
590 def filesadded(self):
590 def filesadded(self):
591 filesadded = self._changeset.filesadded
591 filesadded = self._changeset.filesadded
592 compute_on_none = True
592 compute_on_none = True
593 if self._repo.filecopiesmode == b'changeset-sidedata':
593 if self._repo.filecopiesmode == b'changeset-sidedata':
594 compute_on_none = False
594 compute_on_none = False
595 else:
595 else:
596 source = self._repo.ui.config(b'experimental', b'copies.read-from')
596 source = self._repo.ui.config(b'experimental', b'copies.read-from')
597 if source == b'changeset-only':
597 if source == b'changeset-only':
598 compute_on_none = False
598 compute_on_none = False
599 elif source != b'compatibility':
599 elif source != b'compatibility':
600 # filelog mode, ignore any changelog content
600 # filelog mode, ignore any changelog content
601 filesadded = None
601 filesadded = None
602 if filesadded is None:
602 if filesadded is None:
603 if compute_on_none:
603 if compute_on_none:
604 filesadded = metadata.computechangesetfilesadded(self)
604 filesadded = metadata.computechangesetfilesadded(self)
605 else:
605 else:
606 filesadded = []
606 filesadded = []
607 return filesadded
607 return filesadded
608
608
609 def filesremoved(self):
609 def filesremoved(self):
610 filesremoved = self._changeset.filesremoved
610 filesremoved = self._changeset.filesremoved
611 compute_on_none = True
611 compute_on_none = True
612 if self._repo.filecopiesmode == b'changeset-sidedata':
612 if self._repo.filecopiesmode == b'changeset-sidedata':
613 compute_on_none = False
613 compute_on_none = False
614 else:
614 else:
615 source = self._repo.ui.config(b'experimental', b'copies.read-from')
615 source = self._repo.ui.config(b'experimental', b'copies.read-from')
616 if source == b'changeset-only':
616 if source == b'changeset-only':
617 compute_on_none = False
617 compute_on_none = False
618 elif source != b'compatibility':
618 elif source != b'compatibility':
619 # filelog mode, ignore any changelog content
619 # filelog mode, ignore any changelog content
620 filesremoved = None
620 filesremoved = None
621 if filesremoved is None:
621 if filesremoved is None:
622 if compute_on_none:
622 if compute_on_none:
623 filesremoved = metadata.computechangesetfilesremoved(self)
623 filesremoved = metadata.computechangesetfilesremoved(self)
624 else:
624 else:
625 filesremoved = []
625 filesremoved = []
626 return filesremoved
626 return filesremoved
627
627
628 @propertycache
628 @propertycache
629 def _copies(self):
629 def _copies(self):
630 p1copies = self._changeset.p1copies
630 p1copies = self._changeset.p1copies
631 p2copies = self._changeset.p2copies
631 p2copies = self._changeset.p2copies
632 compute_on_none = True
632 compute_on_none = True
633 if self._repo.filecopiesmode == b'changeset-sidedata':
633 if self._repo.filecopiesmode == b'changeset-sidedata':
634 compute_on_none = False
634 compute_on_none = False
635 else:
635 else:
636 source = self._repo.ui.config(b'experimental', b'copies.read-from')
636 source = self._repo.ui.config(b'experimental', b'copies.read-from')
637 # If config says to get copy metadata only from changeset, then
637 # If config says to get copy metadata only from changeset, then
638 # return that, defaulting to {} if there was no copy metadata. In
638 # return that, defaulting to {} if there was no copy metadata. In
639 # compatibility mode, we return copy data from the changeset if it
639 # compatibility mode, we return copy data from the changeset if it
640 # was recorded there, and otherwise we fall back to getting it from
640 # was recorded there, and otherwise we fall back to getting it from
641 # the filelogs (below).
641 # the filelogs (below).
642 #
642 #
643 # If we are in compatiblity mode and there is not data in the
643 # If we are in compatiblity mode and there is not data in the
644 # changeset), we get the copy metadata from the filelogs.
644 # changeset), we get the copy metadata from the filelogs.
645 #
645 #
646 # otherwise, when config said to read only from filelog, we get the
646 # otherwise, when config said to read only from filelog, we get the
647 # copy metadata from the filelogs.
647 # copy metadata from the filelogs.
648 if source == b'changeset-only':
648 if source == b'changeset-only':
649 compute_on_none = False
649 compute_on_none = False
650 elif source != b'compatibility':
650 elif source != b'compatibility':
651 # filelog mode, ignore any changelog content
651 # filelog mode, ignore any changelog content
652 p1copies = p2copies = None
652 p1copies = p2copies = None
653 if p1copies is None:
653 if p1copies is None:
654 if compute_on_none:
654 if compute_on_none:
655 p1copies, p2copies = super(changectx, self)._copies
655 p1copies, p2copies = super(changectx, self)._copies
656 else:
656 else:
657 if p1copies is None:
657 if p1copies is None:
658 p1copies = {}
658 p1copies = {}
659 if p2copies is None:
659 if p2copies is None:
660 p2copies = {}
660 p2copies = {}
661 return p1copies, p2copies
661 return p1copies, p2copies
662
662
663 def description(self):
663 def description(self):
664 return self._changeset.description
664 return self._changeset.description
665
665
666 def branch(self):
666 def branch(self):
667 return encoding.tolocal(self._changeset.extra.get(b"branch"))
667 return encoding.tolocal(self._changeset.extra.get(b"branch"))
668
668
669 def closesbranch(self):
669 def closesbranch(self):
670 return b'close' in self._changeset.extra
670 return b'close' in self._changeset.extra
671
671
672 def extra(self):
672 def extra(self):
673 """Return a dict of extra information."""
673 """Return a dict of extra information."""
674 return self._changeset.extra
674 return self._changeset.extra
675
675
676 def tags(self):
676 def tags(self):
677 """Return a list of byte tag names"""
677 """Return a list of byte tag names"""
678 return self._repo.nodetags(self._node)
678 return self._repo.nodetags(self._node)
679
679
680 def bookmarks(self):
680 def bookmarks(self):
681 """Return a list of byte bookmark names."""
681 """Return a list of byte bookmark names."""
682 return self._repo.nodebookmarks(self._node)
682 return self._repo.nodebookmarks(self._node)
683
683
684 def fast_rank(self):
684 def fast_rank(self):
685 repo = self._repo
685 repo = self._repo
686 if self._maybe_filtered:
686 if self._maybe_filtered:
687 cl = repo.changelog
687 cl = repo.changelog
688 else:
688 else:
689 cl = repo.unfiltered().changelog
689 cl = repo.unfiltered().changelog
690 return cl.fast_rank(self._rev)
690 return cl.fast_rank(self._rev)
691
691
692 def phase(self):
692 def phase(self):
693 return self._repo._phasecache.phase(self._repo, self._rev)
693 return self._repo._phasecache.phase(self._repo, self._rev)
694
694
695 def hidden(self):
695 def hidden(self):
696 return self._rev in repoview.filterrevs(self._repo, b'visible')
696 return self._rev in repoview.filterrevs(self._repo, b'visible')
697
697
698 def isinmemory(self):
698 def isinmemory(self):
699 return False
699 return False
700
700
701 def children(self):
701 def children(self):
702 """return list of changectx contexts for each child changeset.
702 """return list of changectx contexts for each child changeset.
703
703
704 This returns only the immediate child changesets. Use descendants() to
704 This returns only the immediate child changesets. Use descendants() to
705 recursively walk children.
705 recursively walk children.
706 """
706 """
707 c = self._repo.changelog.children(self._node)
707 c = self._repo.changelog.children(self._node)
708 return [self._repo[x] for x in c]
708 return [self._repo[x] for x in c]
709
709
710 def ancestors(self):
710 def ancestors(self):
711 for a in self._repo.changelog.ancestors([self._rev]):
711 for a in self._repo.changelog.ancestors([self._rev]):
712 yield self._repo[a]
712 yield self._repo[a]
713
713
714 def descendants(self):
714 def descendants(self):
715 """Recursively yield all children of the changeset.
715 """Recursively yield all children of the changeset.
716
716
717 For just the immediate children, use children()
717 For just the immediate children, use children()
718 """
718 """
719 for d in self._repo.changelog.descendants([self._rev]):
719 for d in self._repo.changelog.descendants([self._rev]):
720 yield self._repo[d]
720 yield self._repo[d]
721
721
722 def filectx(self, path, fileid=None, filelog=None):
722 def filectx(self, path, fileid=None, filelog=None):
723 """get a file context from this changeset"""
723 """get a file context from this changeset"""
724 if fileid is None:
724 if fileid is None:
725 fileid = self.filenode(path)
725 fileid = self.filenode(path)
726 return filectx(
726 return filectx(
727 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
727 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
728 )
728 )
729
729
730 def ancestor(self, c2, warn=False):
730 def ancestor(self, c2, warn=False):
731 """return the "best" ancestor context of self and c2
731 """return the "best" ancestor context of self and c2
732
732
733 If there are multiple candidates, it will show a message and check
733 If there are multiple candidates, it will show a message and check
734 merge.preferancestor configuration before falling back to the
734 merge.preferancestor configuration before falling back to the
735 revlog ancestor."""
735 revlog ancestor."""
736 # deal with workingctxs
736 # deal with workingctxs
737 n2 = c2._node
737 n2 = c2._node
738 if n2 is None:
738 if n2 is None:
739 n2 = c2._parents[0]._node
739 n2 = c2._parents[0]._node
740 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
740 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
741 if not cahs:
741 if not cahs:
742 anc = self._repo.nodeconstants.nullid
742 anc = self._repo.nodeconstants.nullid
743 elif len(cahs) == 1:
743 elif len(cahs) == 1:
744 anc = cahs[0]
744 anc = cahs[0]
745 else:
745 else:
746 # experimental config: merge.preferancestor
746 # experimental config: merge.preferancestor
747 for r in self._repo.ui.configlist(b'merge', b'preferancestor'):
747 for r in self._repo.ui.configlist(b'merge', b'preferancestor'):
748 try:
748 try:
749 ctx = scmutil.revsymbol(self._repo, r)
749 ctx = scmutil.revsymbol(self._repo, r)
750 except error.RepoLookupError:
750 except error.RepoLookupError:
751 continue
751 continue
752 anc = ctx.node()
752 anc = ctx.node()
753 if anc in cahs:
753 if anc in cahs:
754 break
754 break
755 else:
755 else:
756 anc = self._repo.changelog.ancestor(self._node, n2)
756 anc = self._repo.changelog.ancestor(self._node, n2)
757 if warn:
757 if warn:
758 self._repo.ui.status(
758 self._repo.ui.status(
759 (
759 (
760 _(b"note: using %s as ancestor of %s and %s\n")
760 _(b"note: using %s as ancestor of %s and %s\n")
761 % (short(anc), short(self._node), short(n2))
761 % (short(anc), short(self._node), short(n2))
762 )
762 )
763 + b''.join(
763 + b''.join(
764 _(
764 _(
765 b" alternatively, use --config "
765 b" alternatively, use --config "
766 b"merge.preferancestor=%s\n"
766 b"merge.preferancestor=%s\n"
767 )
767 )
768 % short(n)
768 % short(n)
769 for n in sorted(cahs)
769 for n in sorted(cahs)
770 if n != anc
770 if n != anc
771 )
771 )
772 )
772 )
773 return self._repo[anc]
773 return self._repo[anc]
774
774
775 def isancestorof(self, other):
775 def isancestorof(self, other):
776 """True if this changeset is an ancestor of other"""
776 """True if this changeset is an ancestor of other"""
777 return self._repo.changelog.isancestorrev(self._rev, other._rev)
777 return self._repo.changelog.isancestorrev(self._rev, other._rev)
778
778
779 def walk(self, match):
779 def walk(self, match):
780 '''Generates matching file names.'''
780 '''Generates matching file names.'''
781
781
782 # Wrap match.bad method to have message with nodeid
782 # Wrap match.bad method to have message with nodeid
783 def bad(fn, msg):
783 def bad(fn, msg):
784 # The manifest doesn't know about subrepos, so don't complain about
784 # The manifest doesn't know about subrepos, so don't complain about
785 # paths into valid subrepos.
785 # paths into valid subrepos.
786 if any(fn == s or fn.startswith(s + b'/') for s in self.substate):
786 if any(fn == s or fn.startswith(s + b'/') for s in self.substate):
787 return
787 return
788 match.bad(fn, _(b'no such file in rev %s') % self)
788 match.bad(fn, _(b'no such file in rev %s') % self)
789
789
790 m = matchmod.badmatch(self._repo.narrowmatch(match), bad)
790 m = matchmod.badmatch(self._repo.narrowmatch(match), bad)
791 return self._manifest.walk(m)
791 return self._manifest.walk(m)
792
792
793 def matches(self, match):
793 def matches(self, match):
794 return self.walk(match)
794 return self.walk(match)
795
795
796
796
797 class basefilectx:
797 class basefilectx:
798 """A filecontext object represents the common logic for its children:
798 """A filecontext object represents the common logic for its children:
799 filectx: read-only access to a filerevision that is already present
799 filectx: read-only access to a filerevision that is already present
800 in the repo,
800 in the repo,
801 workingfilectx: a filecontext that represents files from the working
801 workingfilectx: a filecontext that represents files from the working
802 directory,
802 directory,
803 memfilectx: a filecontext that represents files in-memory,
803 memfilectx: a filecontext that represents files in-memory,
804 """
804 """
805
805
806 @propertycache
806 @propertycache
807 def _filelog(self):
807 def _filelog(self):
808 return self._repo.file(self._path)
808 return self._repo.file(self._path)
809
809
810 @propertycache
810 @propertycache
811 def _changeid(self):
811 def _changeid(self):
812 if '_changectx' in self.__dict__:
812 if '_changectx' in self.__dict__:
813 return self._changectx.rev()
813 return self._changectx.rev()
814 elif '_descendantrev' in self.__dict__:
814 elif '_descendantrev' in self.__dict__:
815 # this file context was created from a revision with a known
815 # this file context was created from a revision with a known
816 # descendant, we can (lazily) correct for linkrev aliases
816 # descendant, we can (lazily) correct for linkrev aliases
817 return self._adjustlinkrev(self._descendantrev)
817 return self._adjustlinkrev(self._descendantrev)
818 else:
818 else:
819 return self._filelog.linkrev(self._filerev)
819 return self._filelog.linkrev(self._filerev)
820
820
821 @propertycache
821 @propertycache
822 def _filenode(self):
822 def _filenode(self):
823 if '_fileid' in self.__dict__:
823 if '_fileid' in self.__dict__:
824 return self._filelog.lookup(self._fileid)
824 return self._filelog.lookup(self._fileid)
825 else:
825 else:
826 return self._changectx.filenode(self._path)
826 return self._changectx.filenode(self._path)
827
827
828 @propertycache
828 @propertycache
829 def _filerev(self):
829 def _filerev(self):
830 return self._filelog.rev(self._filenode)
830 return self._filelog.rev(self._filenode)
831
831
832 @propertycache
832 @propertycache
833 def _repopath(self):
833 def _repopath(self):
834 return self._path
834 return self._path
835
835
836 def __nonzero__(self):
836 def __nonzero__(self):
837 try:
837 try:
838 self._filenode
838 self._filenode
839 return True
839 return True
840 except error.LookupError:
840 except error.LookupError:
841 # file is missing
841 # file is missing
842 return False
842 return False
843
843
844 __bool__ = __nonzero__
844 __bool__ = __nonzero__
845
845
846 def __bytes__(self):
846 def __bytes__(self):
847 try:
847 try:
848 return b"%s@%s" % (self.path(), self._changectx)
848 return b"%s@%s" % (self.path(), self._changectx)
849 except error.LookupError:
849 except error.LookupError:
850 return b"%s@???" % self.path()
850 return b"%s@???" % self.path()
851
851
852 __str__ = encoding.strmethod(__bytes__)
852 __str__ = encoding.strmethod(__bytes__)
853
853
854 def __repr__(self):
854 def __repr__(self):
855 return "<%s %s>" % (type(self).__name__, str(self))
855 return "<%s %s>" % (type(self).__name__, str(self))
856
856
857 def __hash__(self):
857 def __hash__(self):
858 try:
858 try:
859 return hash((self._path, self._filenode))
859 return hash((self._path, self._filenode))
860 except AttributeError:
860 except AttributeError:
861 return id(self)
861 return id(self)
862
862
863 def __eq__(self, other):
863 def __eq__(self, other):
864 try:
864 try:
865 return (
865 return (
866 type(self) == type(other)
866 type(self) == type(other)
867 and self._path == other._path
867 and self._path == other._path
868 and self._filenode == other._filenode
868 and self._filenode == other._filenode
869 )
869 )
870 except AttributeError:
870 except AttributeError:
871 return False
871 return False
872
872
873 def __ne__(self, other):
873 def __ne__(self, other):
874 return not (self == other)
874 return not (self == other)
875
875
876 def filerev(self):
876 def filerev(self):
877 return self._filerev
877 return self._filerev
878
878
879 def filenode(self):
879 def filenode(self):
880 return self._filenode
880 return self._filenode
881
881
882 @propertycache
882 @propertycache
883 def _flags(self):
883 def _flags(self):
884 return self._changectx.flags(self._path)
884 return self._changectx.flags(self._path)
885
885
886 def flags(self):
886 def flags(self):
887 return self._flags
887 return self._flags
888
888
889 def filelog(self):
889 def filelog(self):
890 return self._filelog
890 return self._filelog
891
891
892 def rev(self):
892 def rev(self):
893 return self._changeid
893 return self._changeid
894
894
895 def linkrev(self):
895 def linkrev(self):
896 return self._filelog.linkrev(self._filerev)
896 return self._filelog.linkrev(self._filerev)
897
897
898 def node(self):
898 def node(self):
899 return self._changectx.node()
899 return self._changectx.node()
900
900
901 def hex(self):
901 def hex(self):
902 return self._changectx.hex()
902 return self._changectx.hex()
903
903
904 def user(self):
904 def user(self):
905 return self._changectx.user()
905 return self._changectx.user()
906
906
907 def date(self):
907 def date(self):
908 return self._changectx.date()
908 return self._changectx.date()
909
909
910 def files(self):
910 def files(self):
911 return self._changectx.files()
911 return self._changectx.files()
912
912
913 def description(self):
913 def description(self):
914 return self._changectx.description()
914 return self._changectx.description()
915
915
916 def branch(self):
916 def branch(self):
917 return self._changectx.branch()
917 return self._changectx.branch()
918
918
919 def extra(self):
919 def extra(self):
920 return self._changectx.extra()
920 return self._changectx.extra()
921
921
922 def phase(self):
922 def phase(self):
923 return self._changectx.phase()
923 return self._changectx.phase()
924
924
925 def phasestr(self):
925 def phasestr(self):
926 return self._changectx.phasestr()
926 return self._changectx.phasestr()
927
927
928 def obsolete(self):
928 def obsolete(self):
929 return self._changectx.obsolete()
929 return self._changectx.obsolete()
930
930
931 def instabilities(self):
931 def instabilities(self):
932 return self._changectx.instabilities()
932 return self._changectx.instabilities()
933
933
934 def manifest(self):
934 def manifest(self):
935 return self._changectx.manifest()
935 return self._changectx.manifest()
936
936
937 def changectx(self):
937 def changectx(self):
938 return self._changectx
938 return self._changectx
939
939
940 def renamed(self):
940 def renamed(self):
941 return self._copied
941 return self._copied
942
942
943 def copysource(self):
943 def copysource(self):
944 return self._copied and self._copied[0]
944 return self._copied and self._copied[0]
945
945
946 def repo(self):
946 def repo(self):
947 return self._repo
947 return self._repo
948
948
949 def size(self):
949 def size(self):
950 return len(self.data())
950 return len(self.data())
951
951
952 def path(self):
952 def path(self):
953 return self._path
953 return self._path
954
954
955 def isbinary(self):
955 def isbinary(self):
956 try:
956 try:
957 return stringutil.binary(self.data())
957 return stringutil.binary(self.data())
958 except IOError:
958 except IOError:
959 return False
959 return False
960
960
961 def isexec(self):
961 def isexec(self):
962 return b'x' in self.flags()
962 return b'x' in self.flags()
963
963
964 def islink(self):
964 def islink(self):
965 return b'l' in self.flags()
965 return b'l' in self.flags()
966
966
967 def isabsent(self):
967 def isabsent(self):
968 """whether this filectx represents a file not in self._changectx
968 """whether this filectx represents a file not in self._changectx
969
969
970 This is mainly for merge code to detect change/delete conflicts. This is
970 This is mainly for merge code to detect change/delete conflicts. This is
971 expected to be True for all subclasses of basectx."""
971 expected to be True for all subclasses of basectx."""
972 return False
972 return False
973
973
974 _customcmp = False
974 _customcmp = False
975
975
976 def cmp(self, fctx):
976 def cmp(self, fctx):
977 """compare with other file context
977 """compare with other file context
978
978
979 returns True if different than fctx.
979 returns True if different than fctx.
980 """
980 """
981 if fctx._customcmp:
981 if fctx._customcmp:
982 return fctx.cmp(self)
982 return fctx.cmp(self)
983
983
984 if self._filenode is None:
984 if self._filenode is None:
985 raise error.ProgrammingError(
985 raise error.ProgrammingError(
986 b'filectx.cmp() must be reimplemented if not backed by revlog'
986 b'filectx.cmp() must be reimplemented if not backed by revlog'
987 )
987 )
988
988
989 if fctx._filenode is None:
989 if fctx._filenode is None:
990 if self._repo._encodefilterpats:
990 if self._repo._encodefilterpats:
991 # can't rely on size() because wdir content may be decoded
991 # can't rely on size() because wdir content may be decoded
992 return self._filelog.cmp(self._filenode, fctx.data())
992 return self._filelog.cmp(self._filenode, fctx.data())
993 # filelog.size() has two special cases:
993 # filelog.size() has two special cases:
994 # - censored metadata
994 # - censored metadata
995 # - copy/rename tracking
995 # - copy/rename tracking
996 # The first is detected by peaking into the delta,
996 # The first is detected by peaking into the delta,
997 # the second is detected by abusing parent order
997 # the second is detected by abusing parent order
998 # in the revlog index as flag bit. This leaves files using
998 # in the revlog index as flag bit. This leaves files using
999 # the dummy encoding and non-standard meta attributes.
999 # the dummy encoding and non-standard meta attributes.
1000 # The following check is a special case for the empty
1000 # The following check is a special case for the empty
1001 # metadata block used if the raw file content starts with '\1\n'.
1001 # metadata block used if the raw file content starts with '\1\n'.
1002 # Cases of arbitrary metadata flags are currently mishandled.
1002 # Cases of arbitrary metadata flags are currently mishandled.
1003 if self.size() - 4 == fctx.size():
1003 if self.size() - 4 == fctx.size():
1004 # size() can match:
1004 # size() can match:
1005 # if file data starts with '\1\n', empty metadata block is
1005 # if file data starts with '\1\n', empty metadata block is
1006 # prepended, which adds 4 bytes to filelog.size().
1006 # prepended, which adds 4 bytes to filelog.size().
1007 return self._filelog.cmp(self._filenode, fctx.data())
1007 return self._filelog.cmp(self._filenode, fctx.data())
1008 if self.size() == fctx.size() or self.flags() == b'l':
1008 if self.size() == fctx.size() or self.flags() == b'l':
1009 # size() matches: need to compare content
1009 # size() matches: need to compare content
1010 # issue6456: Always compare symlinks because size can represent
1010 # issue6456: Always compare symlinks because size can represent
1011 # encrypted string for EXT-4 encryption(fscrypt).
1011 # encrypted string for EXT-4 encryption(fscrypt).
1012 return self._filelog.cmp(self._filenode, fctx.data())
1012 return self._filelog.cmp(self._filenode, fctx.data())
1013
1013
1014 # size() differs
1014 # size() differs
1015 return True
1015 return True
1016
1016
1017 def _adjustlinkrev(self, srcrev, inclusive=False, stoprev=None):
1017 def _adjustlinkrev(self, srcrev, inclusive=False, stoprev=None):
1018 """return the first ancestor of <srcrev> introducing <fnode>
1018 """return the first ancestor of <srcrev> introducing <fnode>
1019
1019
1020 If the linkrev of the file revision does not point to an ancestor of
1020 If the linkrev of the file revision does not point to an ancestor of
1021 srcrev, we'll walk down the ancestors until we find one introducing
1021 srcrev, we'll walk down the ancestors until we find one introducing
1022 this file revision.
1022 this file revision.
1023
1023
1024 :srcrev: the changeset revision we search ancestors from
1024 :srcrev: the changeset revision we search ancestors from
1025 :inclusive: if true, the src revision will also be checked
1025 :inclusive: if true, the src revision will also be checked
1026 :stoprev: an optional revision to stop the walk at. If no introduction
1026 :stoprev: an optional revision to stop the walk at. If no introduction
1027 of this file content could be found before this floor
1027 of this file content could be found before this floor
1028 revision, the function will returns "None" and stops its
1028 revision, the function will returns "None" and stops its
1029 iteration.
1029 iteration.
1030 """
1030 """
1031 repo = self._repo
1031 repo = self._repo
1032 cl = repo.unfiltered().changelog
1032 cl = repo.unfiltered().changelog
1033 mfl = repo.manifestlog
1033 mfl = repo.manifestlog
1034 # fetch the linkrev
1034 # fetch the linkrev
1035 lkr = self.linkrev()
1035 lkr = self.linkrev()
1036 if srcrev == lkr:
1036 if srcrev == lkr:
1037 return lkr
1037 return lkr
1038 # hack to reuse ancestor computation when searching for renames
1038 # hack to reuse ancestor computation when searching for renames
1039 memberanc = getattr(self, '_ancestrycontext', None)
1039 memberanc = getattr(self, '_ancestrycontext', None)
1040 iteranc = None
1040 iteranc = None
1041 if srcrev is None:
1041 if srcrev is None:
1042 # wctx case, used by workingfilectx during mergecopy
1042 # wctx case, used by workingfilectx during mergecopy
1043 revs = [p.rev() for p in self._repo[None].parents()]
1043 revs = [p.rev() for p in self._repo[None].parents()]
1044 inclusive = True # we skipped the real (revless) source
1044 inclusive = True # we skipped the real (revless) source
1045 else:
1045 else:
1046 revs = [srcrev]
1046 revs = [srcrev]
1047 if memberanc is None:
1047 if memberanc is None:
1048 memberanc = iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1048 memberanc = iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1049 # check if this linkrev is an ancestor of srcrev
1049 # check if this linkrev is an ancestor of srcrev
1050 if lkr not in memberanc:
1050 if lkr not in memberanc:
1051 if iteranc is None:
1051 if iteranc is None:
1052 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1052 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1053 fnode = self._filenode
1053 fnode = self._filenode
1054 path = self._path
1054 path = self._path
1055 for a in iteranc:
1055 for a in iteranc:
1056 if stoprev is not None and a < stoprev:
1056 if stoprev is not None and a < stoprev:
1057 return None
1057 return None
1058 ac = cl.read(a) # get changeset data (we avoid object creation)
1058 ac = cl.read(a) # get changeset data (we avoid object creation)
1059 if path in ac[3]: # checking the 'files' field.
1059 if path in ac[3]: # checking the 'files' field.
1060 # The file has been touched, check if the content is
1060 # The file has been touched, check if the content is
1061 # similar to the one we search for.
1061 # similar to the one we search for.
1062 if fnode == mfl[ac[0]].readfast().get(path):
1062 if fnode == mfl[ac[0]].readfast().get(path):
1063 return a
1063 return a
1064 # In theory, we should never get out of that loop without a result.
1064 # In theory, we should never get out of that loop without a result.
1065 # But if manifest uses a buggy file revision (not children of the
1065 # But if manifest uses a buggy file revision (not children of the
1066 # one it replaces) we could. Such a buggy situation will likely
1066 # one it replaces) we could. Such a buggy situation will likely
1067 # result is crash somewhere else at to some point.
1067 # result is crash somewhere else at to some point.
1068 return lkr
1068 return lkr
1069
1069
1070 def isintroducedafter(self, changelogrev):
1070 def isintroducedafter(self, changelogrev):
1071 """True if a filectx has been introduced after a given floor revision"""
1071 """True if a filectx has been introduced after a given floor revision"""
1072 if self.linkrev() >= changelogrev:
1072 if self.linkrev() >= changelogrev:
1073 return True
1073 return True
1074 introrev = self._introrev(stoprev=changelogrev)
1074 introrev = self._introrev(stoprev=changelogrev)
1075 if introrev is None:
1075 if introrev is None:
1076 return False
1076 return False
1077 return introrev >= changelogrev
1077 return introrev >= changelogrev
1078
1078
1079 def introrev(self):
1079 def introrev(self):
1080 """return the rev of the changeset which introduced this file revision
1080 """return the rev of the changeset which introduced this file revision
1081
1081
1082 This method is different from linkrev because it take into account the
1082 This method is different from linkrev because it take into account the
1083 changeset the filectx was created from. It ensures the returned
1083 changeset the filectx was created from. It ensures the returned
1084 revision is one of its ancestors. This prevents bugs from
1084 revision is one of its ancestors. This prevents bugs from
1085 'linkrev-shadowing' when a file revision is used by multiple
1085 'linkrev-shadowing' when a file revision is used by multiple
1086 changesets.
1086 changesets.
1087 """
1087 """
1088 return self._introrev()
1088 return self._introrev()
1089
1089
1090 def _introrev(self, stoprev=None):
1090 def _introrev(self, stoprev=None):
1091 """
1091 """
1092 Same as `introrev` but, with an extra argument to limit changelog
1092 Same as `introrev` but, with an extra argument to limit changelog
1093 iteration range in some internal usecase.
1093 iteration range in some internal usecase.
1094
1094
1095 If `stoprev` is set, the `introrev` will not be searched past that
1095 If `stoprev` is set, the `introrev` will not be searched past that
1096 `stoprev` revision and "None" might be returned. This is useful to
1096 `stoprev` revision and "None" might be returned. This is useful to
1097 limit the iteration range.
1097 limit the iteration range.
1098 """
1098 """
1099 toprev = None
1099 toprev = None
1100 attrs = vars(self)
1100 attrs = vars(self)
1101 if '_changeid' in attrs:
1101 if '_changeid' in attrs:
1102 # We have a cached value already
1102 # We have a cached value already
1103 toprev = self._changeid
1103 toprev = self._changeid
1104 elif '_changectx' in attrs:
1104 elif '_changectx' in attrs:
1105 # We know which changelog entry we are coming from
1105 # We know which changelog entry we are coming from
1106 toprev = self._changectx.rev()
1106 toprev = self._changectx.rev()
1107
1107
1108 if toprev is not None:
1108 if toprev is not None:
1109 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1109 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1110 elif '_descendantrev' in attrs:
1110 elif '_descendantrev' in attrs:
1111 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1111 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1112 # be nice and cache the result of the computation
1112 # be nice and cache the result of the computation
1113 if introrev is not None:
1113 if introrev is not None:
1114 self._changeid = introrev
1114 self._changeid = introrev
1115 return introrev
1115 return introrev
1116 else:
1116 else:
1117 return self.linkrev()
1117 return self.linkrev()
1118
1118
1119 def introfilectx(self):
1119 def introfilectx(self):
1120 """Return filectx having identical contents, but pointing to the
1120 """Return filectx having identical contents, but pointing to the
1121 changeset revision where this filectx was introduced"""
1121 changeset revision where this filectx was introduced"""
1122 introrev = self.introrev()
1122 introrev = self.introrev()
1123 if self.rev() == introrev:
1123 if self.rev() == introrev:
1124 return self
1124 return self
1125 return self.filectx(self.filenode(), changeid=introrev)
1125 return self.filectx(self.filenode(), changeid=introrev)
1126
1126
1127 def _parentfilectx(self, path, fileid, filelog):
1127 def _parentfilectx(self, path, fileid, filelog):
1128 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1128 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1129 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1129 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1130 if '_changeid' in vars(self) or '_changectx' in vars(self):
1130 if '_changeid' in vars(self) or '_changectx' in vars(self):
1131 # If self is associated with a changeset (probably explicitly
1131 # If self is associated with a changeset (probably explicitly
1132 # fed), ensure the created filectx is associated with a
1132 # fed), ensure the created filectx is associated with a
1133 # changeset that is an ancestor of self.changectx.
1133 # changeset that is an ancestor of self.changectx.
1134 # This lets us later use _adjustlinkrev to get a correct link.
1134 # This lets us later use _adjustlinkrev to get a correct link.
1135 fctx._descendantrev = self.rev()
1135 fctx._descendantrev = self.rev()
1136 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1136 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1137 elif '_descendantrev' in vars(self):
1137 elif '_descendantrev' in vars(self):
1138 # Otherwise propagate _descendantrev if we have one associated.
1138 # Otherwise propagate _descendantrev if we have one associated.
1139 fctx._descendantrev = self._descendantrev
1139 fctx._descendantrev = self._descendantrev
1140 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1140 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1141 return fctx
1141 return fctx
1142
1142
1143 def parents(self):
1143 def parents(self):
1144 _path = self._path
1144 _path = self._path
1145 fl = self._filelog
1145 fl = self._filelog
1146 parents = self._filelog.parents(self._filenode)
1146 parents = self._filelog.parents(self._filenode)
1147 pl = [
1147 pl = [
1148 (_path, node, fl)
1148 (_path, node, fl)
1149 for node in parents
1149 for node in parents
1150 if node != self._repo.nodeconstants.nullid
1150 if node != self._repo.nodeconstants.nullid
1151 ]
1151 ]
1152
1152
1153 r = fl.renamed(self._filenode)
1153 r = fl.renamed(self._filenode)
1154 if r:
1154 if r:
1155 # - In the simple rename case, both parent are nullid, pl is empty.
1155 # - In the simple rename case, both parent are nullid, pl is empty.
1156 # - In case of merge, only one of the parent is null id and should
1156 # - In case of merge, only one of the parent is null id and should
1157 # be replaced with the rename information. This parent is -always-
1157 # be replaced with the rename information. This parent is -always-
1158 # the first one.
1158 # the first one.
1159 #
1159 #
1160 # As null id have always been filtered out in the previous list
1160 # As null id have always been filtered out in the previous list
1161 # comprehension, inserting to 0 will always result in "replacing
1161 # comprehension, inserting to 0 will always result in "replacing
1162 # first nullid parent with rename information.
1162 # first nullid parent with rename information.
1163 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
1163 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
1164
1164
1165 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
1165 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
1166
1166
1167 def p1(self):
1167 def p1(self):
1168 return self.parents()[0]
1168 return self.parents()[0]
1169
1169
1170 def p2(self):
1170 def p2(self):
1171 p = self.parents()
1171 p = self.parents()
1172 if len(p) == 2:
1172 if len(p) == 2:
1173 return p[1]
1173 return p[1]
1174 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
1174 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
1175
1175
1176 def annotate(self, follow=False, skiprevs=None, diffopts=None):
1176 def annotate(self, follow=False, skiprevs=None, diffopts=None):
1177 """Returns a list of annotateline objects for each line in the file
1177 """Returns a list of annotateline objects for each line in the file
1178
1178
1179 - line.fctx is the filectx of the node where that line was last changed
1179 - line.fctx is the filectx of the node where that line was last changed
1180 - line.lineno is the line number at the first appearance in the managed
1180 - line.lineno is the line number at the first appearance in the managed
1181 file
1181 file
1182 - line.text is the data on that line (including newline character)
1182 - line.text is the data on that line (including newline character)
1183 """
1183 """
1184 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
1184 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
1185
1185
1186 def parents(f):
1186 def parents(f):
1187 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
1187 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
1188 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1188 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1189 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1189 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1190 # isn't an ancestor of the srcrev.
1190 # isn't an ancestor of the srcrev.
1191 f._changeid
1191 f._changeid
1192 pl = f.parents()
1192 pl = f.parents()
1193
1193
1194 # Don't return renamed parents if we aren't following.
1194 # Don't return renamed parents if we aren't following.
1195 if not follow:
1195 if not follow:
1196 pl = [p for p in pl if p.path() == f.path()]
1196 pl = [p for p in pl if p.path() == f.path()]
1197
1197
1198 # renamed filectx won't have a filelog yet, so set it
1198 # renamed filectx won't have a filelog yet, so set it
1199 # from the cache to save time
1199 # from the cache to save time
1200 for p in pl:
1200 for p in pl:
1201 if not '_filelog' in p.__dict__:
1201 if not '_filelog' in p.__dict__:
1202 p._filelog = getlog(p.path())
1202 p._filelog = getlog(p.path())
1203
1203
1204 return pl
1204 return pl
1205
1205
1206 # use linkrev to find the first changeset where self appeared
1206 # use linkrev to find the first changeset where self appeared
1207 base = self.introfilectx()
1207 base = self.introfilectx()
1208 if getattr(base, '_ancestrycontext', None) is None:
1208 if getattr(base, '_ancestrycontext', None) is None:
1209 # it is safe to use an unfiltered repository here because we are
1209 # it is safe to use an unfiltered repository here because we are
1210 # walking ancestors only.
1210 # walking ancestors only.
1211 cl = self._repo.unfiltered().changelog
1211 cl = self._repo.unfiltered().changelog
1212 if base.rev() is None:
1212 if base.rev() is None:
1213 # wctx is not inclusive, but works because _ancestrycontext
1213 # wctx is not inclusive, but works because _ancestrycontext
1214 # is used to test filelog revisions
1214 # is used to test filelog revisions
1215 ac = cl.ancestors(
1215 ac = cl.ancestors(
1216 [p.rev() for p in base.parents()], inclusive=True
1216 [p.rev() for p in base.parents()], inclusive=True
1217 )
1217 )
1218 else:
1218 else:
1219 ac = cl.ancestors([base.rev()], inclusive=True)
1219 ac = cl.ancestors([base.rev()], inclusive=True)
1220 base._ancestrycontext = ac
1220 base._ancestrycontext = ac
1221
1221
1222 return dagop.annotate(
1222 return dagop.annotate(
1223 base, parents, skiprevs=skiprevs, diffopts=diffopts
1223 base, parents, skiprevs=skiprevs, diffopts=diffopts
1224 )
1224 )
1225
1225
1226 def ancestors(self, followfirst=False):
1226 def ancestors(self, followfirst=False):
1227 visit = {}
1227 visit = {}
1228 c = self
1228 c = self
1229 if followfirst:
1229 if followfirst:
1230 cut = 1
1230 cut = 1
1231 else:
1231 else:
1232 cut = None
1232 cut = None
1233
1233
1234 while True:
1234 while True:
1235 for parent in c.parents()[:cut]:
1235 for parent in c.parents()[:cut]:
1236 visit[(parent.linkrev(), parent.filenode())] = parent
1236 visit[(parent.linkrev(), parent.filenode())] = parent
1237 if not visit:
1237 if not visit:
1238 break
1238 break
1239 c = visit.pop(max(visit))
1239 c = visit.pop(max(visit))
1240 yield c
1240 yield c
1241
1241
1242 def decodeddata(self):
1242 def decodeddata(self):
1243 """Returns `data()` after running repository decoding filters.
1243 """Returns `data()` after running repository decoding filters.
1244
1244
1245 This is often equivalent to how the data would be expressed on disk.
1245 This is often equivalent to how the data would be expressed on disk.
1246 """
1246 """
1247 return self._repo.wwritedata(self.path(), self.data())
1247 return self._repo.wwritedata(self.path(), self.data())
1248
1248
1249
1249
1250 class filectx(basefilectx):
1250 class filectx(basefilectx):
1251 """A filecontext object makes access to data related to a particular
1251 """A filecontext object makes access to data related to a particular
1252 filerevision convenient."""
1252 filerevision convenient."""
1253
1253
1254 def __init__(
1254 def __init__(
1255 self,
1255 self,
1256 repo,
1256 repo,
1257 path,
1257 path,
1258 changeid=None,
1258 changeid=None,
1259 fileid=None,
1259 fileid=None,
1260 filelog=None,
1260 filelog=None,
1261 changectx=None,
1261 changectx=None,
1262 ):
1262 ):
1263 """changeid must be a revision number, if specified.
1263 """changeid must be a revision number, if specified.
1264 fileid can be a file revision or node."""
1264 fileid can be a file revision or node."""
1265 self._repo = repo
1265 self._repo = repo
1266 self._path = path
1266 self._path = path
1267
1267
1268 assert (
1268 assert (
1269 changeid is not None or fileid is not None or changectx is not None
1269 changeid is not None or fileid is not None or changectx is not None
1270 ), b"bad args: changeid=%r, fileid=%r, changectx=%r" % (
1270 ), b"bad args: changeid=%r, fileid=%r, changectx=%r" % (
1271 changeid,
1271 changeid,
1272 fileid,
1272 fileid,
1273 changectx,
1273 changectx,
1274 )
1274 )
1275
1275
1276 if filelog is not None:
1276 if filelog is not None:
1277 self._filelog = filelog
1277 self._filelog = filelog
1278
1278
1279 if changeid is not None:
1279 if changeid is not None:
1280 self._changeid = changeid
1280 self._changeid = changeid
1281 if changectx is not None:
1281 if changectx is not None:
1282 self._changectx = changectx
1282 self._changectx = changectx
1283 if fileid is not None:
1283 if fileid is not None:
1284 self._fileid = fileid
1284 self._fileid = fileid
1285
1285
1286 @propertycache
1286 @propertycache
1287 def _changectx(self):
1287 def _changectx(self):
1288 try:
1288 try:
1289 return self._repo[self._changeid]
1289 return self._repo[self._changeid]
1290 except error.FilteredRepoLookupError:
1290 except error.FilteredRepoLookupError:
1291 # Linkrev may point to any revision in the repository. When the
1291 # Linkrev may point to any revision in the repository. When the
1292 # repository is filtered this may lead to `filectx` trying to build
1292 # repository is filtered this may lead to `filectx` trying to build
1293 # `changectx` for filtered revision. In such case we fallback to
1293 # `changectx` for filtered revision. In such case we fallback to
1294 # creating `changectx` on the unfiltered version of the reposition.
1294 # creating `changectx` on the unfiltered version of the reposition.
1295 # This fallback should not be an issue because `changectx` from
1295 # This fallback should not be an issue because `changectx` from
1296 # `filectx` are not used in complex operations that care about
1296 # `filectx` are not used in complex operations that care about
1297 # filtering.
1297 # filtering.
1298 #
1298 #
1299 # This fallback is a cheap and dirty fix that prevent several
1299 # This fallback is a cheap and dirty fix that prevent several
1300 # crashes. It does not ensure the behavior is correct. However the
1300 # crashes. It does not ensure the behavior is correct. However the
1301 # behavior was not correct before filtering either and "incorrect
1301 # behavior was not correct before filtering either and "incorrect
1302 # behavior" is seen as better as "crash"
1302 # behavior" is seen as better as "crash"
1303 #
1303 #
1304 # Linkrevs have several serious troubles with filtering that are
1304 # Linkrevs have several serious troubles with filtering that are
1305 # complicated to solve. Proper handling of the issue here should be
1305 # complicated to solve. Proper handling of the issue here should be
1306 # considered when solving linkrev issue are on the table.
1306 # considered when solving linkrev issue are on the table.
1307 return self._repo.unfiltered()[self._changeid]
1307 return self._repo.unfiltered()[self._changeid]
1308
1308
1309 def filectx(self, fileid, changeid=None):
1309 def filectx(self, fileid, changeid=None):
1310 """opens an arbitrary revision of the file without
1310 """opens an arbitrary revision of the file without
1311 opening a new filelog"""
1311 opening a new filelog"""
1312 return filectx(
1312 return filectx(
1313 self._repo,
1313 self._repo,
1314 self._path,
1314 self._path,
1315 fileid=fileid,
1315 fileid=fileid,
1316 filelog=self._filelog,
1316 filelog=self._filelog,
1317 changeid=changeid,
1317 changeid=changeid,
1318 )
1318 )
1319
1319
1320 def rawdata(self):
1320 def rawdata(self):
1321 return self._filelog.rawdata(self._filenode)
1321 return self._filelog.rawdata(self._filenode)
1322
1322
1323 def rawflags(self):
1323 def rawflags(self):
1324 """low-level revlog flags"""
1324 """low-level revlog flags"""
1325 return self._filelog.flags(self._filerev)
1325 return self._filelog.flags(self._filerev)
1326
1326
1327 def data(self):
1327 def data(self):
1328 try:
1328 try:
1329 return self._filelog.read(self._filenode)
1329 return self._filelog.read(self._filenode)
1330 except error.CensoredNodeError:
1330 except error.CensoredNodeError:
1331 if self._repo.ui.config(b"censor", b"policy") == b"ignore":
1331 if self._repo.ui.config(b"censor", b"policy") == b"ignore":
1332 return b""
1332 return b""
1333 raise error.Abort(
1333 raise error.Abort(
1334 _(b"censored node: %s") % short(self._filenode),
1334 _(b"censored node: %s") % short(self._filenode),
1335 hint=_(b"set censor.policy to ignore errors"),
1335 hint=_(b"set censor.policy to ignore errors"),
1336 )
1336 )
1337
1337
1338 def size(self):
1338 def size(self):
1339 return self._filelog.size(self._filerev)
1339 return self._filelog.size(self._filerev)
1340
1340
1341 @propertycache
1341 @propertycache
1342 def _copied(self):
1342 def _copied(self):
1343 """check if file was actually renamed in this changeset revision
1343 """check if file was actually renamed in this changeset revision
1344
1344
1345 If rename logged in file revision, we report copy for changeset only
1345 If rename logged in file revision, we report copy for changeset only
1346 if file revisions linkrev points back to the changeset in question
1346 if file revisions linkrev points back to the changeset in question
1347 or both changeset parents contain different file revisions.
1347 or both changeset parents contain different file revisions.
1348 """
1348 """
1349
1349
1350 renamed = self._filelog.renamed(self._filenode)
1350 renamed = self._filelog.renamed(self._filenode)
1351 if not renamed:
1351 if not renamed:
1352 return None
1352 return None
1353
1353
1354 if self.rev() == self.linkrev():
1354 if self.rev() == self.linkrev():
1355 return renamed
1355 return renamed
1356
1356
1357 name = self.path()
1357 name = self.path()
1358 fnode = self._filenode
1358 fnode = self._filenode
1359 for p in self._changectx.parents():
1359 for p in self._changectx.parents():
1360 try:
1360 try:
1361 if fnode == p.filenode(name):
1361 if fnode == p.filenode(name):
1362 return None
1362 return None
1363 except error.LookupError:
1363 except error.LookupError:
1364 pass
1364 pass
1365 return renamed
1365 return renamed
1366
1366
1367 def children(self):
1367 def children(self):
1368 # hard for renames
1368 # hard for renames
1369 c = self._filelog.children(self._filenode)
1369 c = self._filelog.children(self._filenode)
1370 return [
1370 return [
1371 filectx(self._repo, self._path, fileid=x, filelog=self._filelog)
1371 filectx(self._repo, self._path, fileid=x, filelog=self._filelog)
1372 for x in c
1372 for x in c
1373 ]
1373 ]
1374
1374
1375
1375
1376 class committablectx(basectx):
1376 class committablectx(basectx):
1377 """A committablectx object provides common functionality for a context that
1377 """A committablectx object provides common functionality for a context that
1378 wants the ability to commit, e.g. workingctx or memctx."""
1378 wants the ability to commit, e.g. workingctx or memctx."""
1379
1379
1380 def __init__(
1380 def __init__(
1381 self,
1381 self,
1382 repo,
1382 repo,
1383 text=b"",
1383 text=b"",
1384 user=None,
1384 user=None,
1385 date=None,
1385 date=None,
1386 extra=None,
1386 extra=None,
1387 changes=None,
1387 changes=None,
1388 branch=None,
1388 branch=None,
1389 ):
1389 ):
1390 super(committablectx, self).__init__(repo)
1390 super(committablectx, self).__init__(repo)
1391 self._rev = None
1391 self._rev = None
1392 self._node = None
1392 self._node = None
1393 self._text = text
1393 self._text = text
1394 if date:
1394 if date:
1395 self._date = dateutil.parsedate(date)
1395 self._date = dateutil.parsedate(date)
1396 if user:
1396 if user:
1397 self._user = user
1397 self._user = user
1398 if changes:
1398 if changes:
1399 self._status = changes
1399 self._status = changes
1400
1400
1401 self._extra = {}
1401 self._extra = {}
1402 if extra:
1402 if extra:
1403 self._extra = extra.copy()
1403 self._extra = extra.copy()
1404 if branch is not None:
1404 if branch is not None:
1405 self._extra[b'branch'] = encoding.fromlocal(branch)
1405 self._extra[b'branch'] = encoding.fromlocal(branch)
1406 if not self._extra.get(b'branch'):
1406 if not self._extra.get(b'branch'):
1407 self._extra[b'branch'] = b'default'
1407 self._extra[b'branch'] = b'default'
1408
1408
1409 def __bytes__(self):
1409 def __bytes__(self):
1410 return bytes(self._parents[0]) + b"+"
1410 return bytes(self._parents[0]) + b"+"
1411
1411
1412 def hex(self):
1412 def hex(self):
1413 self._repo.nodeconstants.wdirhex
1413 self._repo.nodeconstants.wdirhex
1414
1414
1415 __str__ = encoding.strmethod(__bytes__)
1415 __str__ = encoding.strmethod(__bytes__)
1416
1416
1417 def __nonzero__(self):
1417 def __nonzero__(self):
1418 return True
1418 return True
1419
1419
1420 __bool__ = __nonzero__
1420 __bool__ = __nonzero__
1421
1421
1422 @propertycache
1422 @propertycache
1423 def _status(self):
1423 def _status(self):
1424 return self._repo.status()
1424 return self._repo.status()
1425
1425
1426 @propertycache
1426 @propertycache
1427 def _user(self):
1427 def _user(self):
1428 return self._repo.ui.username()
1428 return self._repo.ui.username()
1429
1429
1430 @propertycache
1430 @propertycache
1431 def _date(self):
1431 def _date(self):
1432 ui = self._repo.ui
1432 ui = self._repo.ui
1433 date = ui.configdate(b'devel', b'default-date')
1433 date = ui.configdate(b'devel', b'default-date')
1434 if date is None:
1434 if date is None:
1435 date = dateutil.makedate()
1435 date = dateutil.makedate()
1436 return date
1436 return date
1437
1437
1438 def subrev(self, subpath):
1438 def subrev(self, subpath):
1439 return None
1439 return None
1440
1440
1441 def manifestnode(self):
1441 def manifestnode(self):
1442 return None
1442 return None
1443
1443
1444 def user(self):
1444 def user(self):
1445 return self._user or self._repo.ui.username()
1445 return self._user or self._repo.ui.username()
1446
1446
1447 def date(self):
1447 def date(self):
1448 return self._date
1448 return self._date
1449
1449
1450 def description(self):
1450 def description(self):
1451 return self._text
1451 return self._text
1452
1452
1453 def files(self):
1453 def files(self):
1454 return sorted(
1454 return sorted(
1455 self._status.modified + self._status.added + self._status.removed
1455 self._status.modified + self._status.added + self._status.removed
1456 )
1456 )
1457
1457
1458 def modified(self):
1458 def modified(self):
1459 return self._status.modified
1459 return self._status.modified
1460
1460
1461 def added(self):
1461 def added(self):
1462 return self._status.added
1462 return self._status.added
1463
1463
1464 def removed(self):
1464 def removed(self):
1465 return self._status.removed
1465 return self._status.removed
1466
1466
1467 def deleted(self):
1467 def deleted(self):
1468 return self._status.deleted
1468 return self._status.deleted
1469
1469
1470 filesmodified = modified
1470 filesmodified = modified
1471 filesadded = added
1471 filesadded = added
1472 filesremoved = removed
1472 filesremoved = removed
1473
1473
1474 def branch(self):
1474 def branch(self):
1475 return encoding.tolocal(self._extra[b'branch'])
1475 return encoding.tolocal(self._extra[b'branch'])
1476
1476
1477 def closesbranch(self):
1477 def closesbranch(self):
1478 return b'close' in self._extra
1478 return b'close' in self._extra
1479
1479
1480 def extra(self):
1480 def extra(self):
1481 return self._extra
1481 return self._extra
1482
1482
1483 def isinmemory(self):
1483 def isinmemory(self):
1484 return False
1484 return False
1485
1485
1486 def tags(self):
1486 def tags(self):
1487 return []
1487 return []
1488
1488
1489 def bookmarks(self):
1489 def bookmarks(self):
1490 b = []
1490 b = []
1491 for p in self.parents():
1491 for p in self.parents():
1492 b.extend(p.bookmarks())
1492 b.extend(p.bookmarks())
1493 return b
1493 return b
1494
1494
1495 def phase(self):
1495 def phase(self):
1496 phase = phases.newcommitphase(self._repo.ui)
1496 phase = phases.newcommitphase(self._repo.ui)
1497 for p in self.parents():
1497 for p in self.parents():
1498 phase = max(phase, p.phase())
1498 phase = max(phase, p.phase())
1499 return phase
1499 return phase
1500
1500
1501 def hidden(self):
1501 def hidden(self):
1502 return False
1502 return False
1503
1503
1504 def children(self):
1504 def children(self):
1505 return []
1505 return []
1506
1506
1507 def flags(self, path):
1507 def flags(self, path):
1508 if '_manifest' in self.__dict__:
1508 if '_manifest' in self.__dict__:
1509 try:
1509 try:
1510 return self._manifest.flags(path)
1510 return self._manifest.flags(path)
1511 except KeyError:
1511 except KeyError:
1512 return b''
1512 return b''
1513
1513
1514 try:
1514 try:
1515 return self._flagfunc(path)
1515 return self._flagfunc(path)
1516 except OSError:
1516 except OSError:
1517 return b''
1517 return b''
1518
1518
1519 def ancestor(self, c2):
1519 def ancestor(self, c2):
1520 """return the "best" ancestor context of self and c2"""
1520 """return the "best" ancestor context of self and c2"""
1521 return self._parents[0].ancestor(c2) # punt on two parents for now
1521 return self._parents[0].ancestor(c2) # punt on two parents for now
1522
1522
1523 def ancestors(self):
1523 def ancestors(self):
1524 for p in self._parents:
1524 for p in self._parents:
1525 yield p
1525 yield p
1526 for a in self._repo.changelog.ancestors(
1526 for a in self._repo.changelog.ancestors(
1527 [p.rev() for p in self._parents]
1527 [p.rev() for p in self._parents]
1528 ):
1528 ):
1529 yield self._repo[a]
1529 yield self._repo[a]
1530
1530
1531 def markcommitted(self, node):
1531 def markcommitted(self, node):
1532 """Perform post-commit cleanup necessary after committing this ctx
1532 """Perform post-commit cleanup necessary after committing this ctx
1533
1533
1534 Specifically, this updates backing stores this working context
1534 Specifically, this updates backing stores this working context
1535 wraps to reflect the fact that the changes reflected by this
1535 wraps to reflect the fact that the changes reflected by this
1536 workingctx have been committed. For example, it marks
1536 workingctx have been committed. For example, it marks
1537 modified and added files as normal in the dirstate.
1537 modified and added files as normal in the dirstate.
1538
1538
1539 """
1539 """
1540
1540
1541 def dirty(self, missing=False, merge=True, branch=True):
1541 def dirty(self, missing=False, merge=True, branch=True):
1542 return False
1542 return False
1543
1543
1544
1544
1545 class workingctx(committablectx):
1545 class workingctx(committablectx):
1546 """A workingctx object makes access to data related to
1546 """A workingctx object makes access to data related to
1547 the current working directory convenient.
1547 the current working directory convenient.
1548 date - any valid date string or (unixtime, offset), or None.
1548 date - any valid date string or (unixtime, offset), or None.
1549 user - username string, or None.
1549 user - username string, or None.
1550 extra - a dictionary of extra values, or None.
1550 extra - a dictionary of extra values, or None.
1551 changes - a list of file lists as returned by localrepo.status()
1551 changes - a list of file lists as returned by localrepo.status()
1552 or None to use the repository status.
1552 or None to use the repository status.
1553 """
1553 """
1554
1554
1555 def __init__(
1555 def __init__(
1556 self, repo, text=b"", user=None, date=None, extra=None, changes=None
1556 self, repo, text=b"", user=None, date=None, extra=None, changes=None
1557 ):
1557 ):
1558 branch = None
1558 branch = None
1559 if not extra or b'branch' not in extra:
1559 if not extra or b'branch' not in extra:
1560 try:
1560 try:
1561 branch = repo.dirstate.branch()
1561 branch = repo.dirstate.branch()
1562 except UnicodeDecodeError:
1562 except UnicodeDecodeError:
1563 raise error.Abort(_(b'branch name not in UTF-8!'))
1563 raise error.Abort(_(b'branch name not in UTF-8!'))
1564 super(workingctx, self).__init__(
1564 super(workingctx, self).__init__(
1565 repo, text, user, date, extra, changes, branch=branch
1565 repo, text, user, date, extra, changes, branch=branch
1566 )
1566 )
1567
1567
1568 def __iter__(self):
1568 def __iter__(self):
1569 d = self._repo.dirstate
1569 d = self._repo.dirstate
1570 for f in d:
1570 for f in d:
1571 if d.get_entry(f).tracked:
1571 if d.get_entry(f).tracked:
1572 yield f
1572 yield f
1573
1573
1574 def __contains__(self, key):
1574 def __contains__(self, key):
1575 return self._repo.dirstate.get_entry(key).tracked
1575 return self._repo.dirstate.get_entry(key).tracked
1576
1576
1577 def hex(self):
1577 def hex(self):
1578 return self._repo.nodeconstants.wdirhex
1578 return self._repo.nodeconstants.wdirhex
1579
1579
1580 @propertycache
1580 @propertycache
1581 def _parents(self):
1581 def _parents(self):
1582 p = self._repo.dirstate.parents()
1582 p = self._repo.dirstate.parents()
1583 if p[1] == self._repo.nodeconstants.nullid:
1583 if p[1] == self._repo.nodeconstants.nullid:
1584 p = p[:-1]
1584 p = p[:-1]
1585 # use unfiltered repo to delay/avoid loading obsmarkers
1585 # use unfiltered repo to delay/avoid loading obsmarkers
1586 unfi = self._repo.unfiltered()
1586 unfi = self._repo.unfiltered()
1587 return [
1587 return [
1588 changectx(
1588 changectx(
1589 self._repo, unfi.changelog.rev(n), n, maybe_filtered=False
1589 self._repo, unfi.changelog.rev(n), n, maybe_filtered=False
1590 )
1590 )
1591 for n in p
1591 for n in p
1592 ]
1592 ]
1593
1593
1594 def setparents(self, p1node, p2node=None):
1594 def setparents(self, p1node, p2node=None):
1595 if p2node is None:
1595 if p2node is None:
1596 p2node = self._repo.nodeconstants.nullid
1596 p2node = self._repo.nodeconstants.nullid
1597 dirstate = self._repo.dirstate
1597 dirstate = self._repo.dirstate
1598 with dirstate.changing_parents(self._repo):
1598 with dirstate.changing_parents(self._repo):
1599 copies = dirstate.setparents(p1node, p2node)
1599 copies = dirstate.setparents(p1node, p2node)
1600 pctx = self._repo[p1node]
1600 pctx = self._repo[p1node]
1601 if copies:
1601 if copies:
1602 # Adjust copy records, the dirstate cannot do it, it
1602 # Adjust copy records, the dirstate cannot do it, it
1603 # requires access to parents manifests. Preserve them
1603 # requires access to parents manifests. Preserve them
1604 # only for entries added to first parent.
1604 # only for entries added to first parent.
1605 for f in copies:
1605 for f in copies:
1606 if f not in pctx and copies[f] in pctx:
1606 if f not in pctx and copies[f] in pctx:
1607 dirstate.copy(copies[f], f)
1607 dirstate.copy(copies[f], f)
1608 if p2node == self._repo.nodeconstants.nullid:
1608 if p2node == self._repo.nodeconstants.nullid:
1609 for f, s in sorted(dirstate.copies().items()):
1609 for f, s in sorted(dirstate.copies().items()):
1610 if f not in pctx and s not in pctx:
1610 if f not in pctx and s not in pctx:
1611 dirstate.copy(None, f)
1611 dirstate.copy(None, f)
1612
1612
1613 def _fileinfo(self, path):
1613 def _fileinfo(self, path):
1614 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1614 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1615 self._manifest
1615 self._manifest
1616 return super(workingctx, self)._fileinfo(path)
1616 return super(workingctx, self)._fileinfo(path)
1617
1617
1618 def _buildflagfunc(self):
1618 def _buildflagfunc(self):
1619 # Create a fallback function for getting file flags when the
1619 # Create a fallback function for getting file flags when the
1620 # filesystem doesn't support them
1620 # filesystem doesn't support them
1621
1621
1622 copiesget = self._repo.dirstate.copies().get
1622 copiesget = self._repo.dirstate.copies().get
1623 parents = self.parents()
1623 parents = self.parents()
1624 if len(parents) < 2:
1624 if len(parents) < 2:
1625 # when we have one parent, it's easy: copy from parent
1625 # when we have one parent, it's easy: copy from parent
1626 man = parents[0].manifest()
1626 man = parents[0].manifest()
1627
1627
1628 def func(f):
1628 def func(f):
1629 f = copiesget(f, f)
1629 f = copiesget(f, f)
1630 return man.flags(f)
1630 return man.flags(f)
1631
1631
1632 else:
1632 else:
1633 # merges are tricky: we try to reconstruct the unstored
1633 # merges are tricky: we try to reconstruct the unstored
1634 # result from the merge (issue1802)
1634 # result from the merge (issue1802)
1635 p1, p2 = parents
1635 p1, p2 = parents
1636 pa = p1.ancestor(p2)
1636 pa = p1.ancestor(p2)
1637 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1637 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1638
1638
1639 def func(f):
1639 def func(f):
1640 f = copiesget(f, f) # may be wrong for merges with copies
1640 f = copiesget(f, f) # may be wrong for merges with copies
1641 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1641 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1642 if fl1 == fl2:
1642 if fl1 == fl2:
1643 return fl1
1643 return fl1
1644 if fl1 == fla:
1644 if fl1 == fla:
1645 return fl2
1645 return fl2
1646 if fl2 == fla:
1646 if fl2 == fla:
1647 return fl1
1647 return fl1
1648 return b'' # punt for conflicts
1648 return b'' # punt for conflicts
1649
1649
1650 return func
1650 return func
1651
1651
1652 @propertycache
1652 @propertycache
1653 def _flagfunc(self):
1653 def _flagfunc(self):
1654 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1654 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1655
1655
1656 def flags(self, path):
1656 def flags(self, path):
1657 try:
1657 try:
1658 return self._flagfunc(path)
1658 return self._flagfunc(path)
1659 except OSError:
1659 except OSError:
1660 return b''
1660 return b''
1661
1661
1662 def filectx(self, path, filelog=None):
1662 def filectx(self, path, filelog=None):
1663 """get a file context from the working directory"""
1663 """get a file context from the working directory"""
1664 return workingfilectx(
1664 return workingfilectx(
1665 self._repo, path, workingctx=self, filelog=filelog
1665 self._repo, path, workingctx=self, filelog=filelog
1666 )
1666 )
1667
1667
1668 def dirty(self, missing=False, merge=True, branch=True):
1668 def dirty(self, missing=False, merge=True, branch=True):
1669 """check whether a working directory is modified"""
1669 """check whether a working directory is modified"""
1670 # check subrepos first
1670 # check subrepos first
1671 for s in sorted(self.substate):
1671 for s in sorted(self.substate):
1672 if self.sub(s).dirty(missing=missing):
1672 if self.sub(s).dirty(missing=missing):
1673 return True
1673 return True
1674 # check current working dir
1674 # check current working dir
1675 return (
1675 return (
1676 (merge and self.p2())
1676 (merge and self.p2())
1677 or (branch and self.branch() != self.p1().branch())
1677 or (branch and self.branch() != self.p1().branch())
1678 or self.modified()
1678 or self.modified()
1679 or self.added()
1679 or self.added()
1680 or self.removed()
1680 or self.removed()
1681 or (missing and self.deleted())
1681 or (missing and self.deleted())
1682 )
1682 )
1683
1683
1684 def add(self, list, prefix=b""):
1684 def add(self, list, prefix=b""):
1685 with self._repo.wlock():
1685 with self._repo.wlock():
1686 ui, ds = self._repo.ui, self._repo.dirstate
1686 ui, ds = self._repo.ui, self._repo.dirstate
1687 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1687 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1688 rejected = []
1688 rejected = []
1689 lstat = self._repo.wvfs.lstat
1689 lstat = self._repo.wvfs.lstat
1690 for f in list:
1690 for f in list:
1691 # ds.pathto() returns an absolute file when this is invoked from
1691 # ds.pathto() returns an absolute file when this is invoked from
1692 # the keyword extension. That gets flagged as non-portable on
1692 # the keyword extension. That gets flagged as non-portable on
1693 # Windows, since it contains the drive letter and colon.
1693 # Windows, since it contains the drive letter and colon.
1694 scmutil.checkportable(ui, os.path.join(prefix, f))
1694 scmutil.checkportable(ui, os.path.join(prefix, f))
1695 try:
1695 try:
1696 st = lstat(f)
1696 st = lstat(f)
1697 except OSError:
1697 except OSError:
1698 ui.warn(_(b"%s does not exist!\n") % uipath(f))
1698 ui.warn(_(b"%s does not exist!\n") % uipath(f))
1699 rejected.append(f)
1699 rejected.append(f)
1700 continue
1700 continue
1701 limit = ui.configbytes(b'ui', b'large-file-limit')
1701 limit = ui.configbytes(b'ui', b'large-file-limit')
1702 if limit != 0 and st.st_size > limit:
1702 if limit != 0 and st.st_size > limit:
1703 ui.warn(
1703 ui.warn(
1704 _(
1704 _(
1705 b"%s: up to %d MB of RAM may be required "
1705 b"%s: up to %d MB of RAM may be required "
1706 b"to manage this file\n"
1706 b"to manage this file\n"
1707 b"(use 'hg revert %s' to cancel the "
1707 b"(use 'hg revert %s' to cancel the "
1708 b"pending addition)\n"
1708 b"pending addition)\n"
1709 )
1709 )
1710 % (f, 3 * st.st_size // 1000000, uipath(f))
1710 % (f, 3 * st.st_size // 1000000, uipath(f))
1711 )
1711 )
1712 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1712 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1713 ui.warn(
1713 ui.warn(
1714 _(
1714 _(
1715 b"%s not added: only files and symlinks "
1715 b"%s not added: only files and symlinks "
1716 b"supported currently\n"
1716 b"supported currently\n"
1717 )
1717 )
1718 % uipath(f)
1718 % uipath(f)
1719 )
1719 )
1720 rejected.append(f)
1720 rejected.append(f)
1721 elif not ds.set_tracked(f):
1721 elif not ds.set_tracked(f):
1722 ui.warn(_(b"%s already tracked!\n") % uipath(f))
1722 ui.warn(_(b"%s already tracked!\n") % uipath(f))
1723 return rejected
1723 return rejected
1724
1724
1725 def forget(self, files, prefix=b""):
1725 def forget(self, files, prefix=b""):
1726 with self._repo.wlock():
1726 with self._repo.wlock():
1727 ds = self._repo.dirstate
1727 ds = self._repo.dirstate
1728 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1728 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1729 rejected = []
1729 rejected = []
1730 for f in files:
1730 for f in files:
1731 if not ds.set_untracked(f):
1731 if not ds.set_untracked(f):
1732 self._repo.ui.warn(_(b"%s not tracked!\n") % uipath(f))
1732 self._repo.ui.warn(_(b"%s not tracked!\n") % uipath(f))
1733 rejected.append(f)
1733 rejected.append(f)
1734 return rejected
1734 return rejected
1735
1735
1736 def copy(self, source, dest):
1736 def copy(self, source, dest):
1737 try:
1737 try:
1738 st = self._repo.wvfs.lstat(dest)
1738 st = self._repo.wvfs.lstat(dest)
1739 except FileNotFoundError:
1739 except FileNotFoundError:
1740 self._repo.ui.warn(
1740 self._repo.ui.warn(
1741 _(b"%s does not exist!\n") % self._repo.dirstate.pathto(dest)
1741 _(b"%s does not exist!\n") % self._repo.dirstate.pathto(dest)
1742 )
1742 )
1743 return
1743 return
1744 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1744 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1745 self._repo.ui.warn(
1745 self._repo.ui.warn(
1746 _(b"copy failed: %s is not a file or a symbolic link\n")
1746 _(b"copy failed: %s is not a file or a symbolic link\n")
1747 % self._repo.dirstate.pathto(dest)
1747 % self._repo.dirstate.pathto(dest)
1748 )
1748 )
1749 else:
1749 else:
1750 with self._repo.wlock():
1750 with self._repo.wlock():
1751 ds = self._repo.dirstate
1751 ds = self._repo.dirstate
1752 ds.set_tracked(dest)
1752 ds.set_tracked(dest)
1753 ds.copy(source, dest)
1753 ds.copy(source, dest)
1754
1754
1755 def match(
1755 def match(
1756 self,
1756 self,
1757 pats=None,
1757 pats=None,
1758 include=None,
1758 include=None,
1759 exclude=None,
1759 exclude=None,
1760 default=b'glob',
1760 default=b'glob',
1761 listsubrepos=False,
1761 listsubrepos=False,
1762 badfn=None,
1762 badfn=None,
1763 cwd=None,
1763 cwd=None,
1764 ):
1764 ):
1765 r = self._repo
1765 r = self._repo
1766 if not cwd:
1766 if not cwd:
1767 cwd = r.getcwd()
1767 cwd = r.getcwd()
1768
1768
1769 # Only a case insensitive filesystem needs magic to translate user input
1769 # Only a case insensitive filesystem needs magic to translate user input
1770 # to actual case in the filesystem.
1770 # to actual case in the filesystem.
1771 icasefs = not util.fscasesensitive(r.root)
1771 icasefs = not util.fscasesensitive(r.root)
1772 return matchmod.match(
1772 return matchmod.match(
1773 r.root,
1773 r.root,
1774 cwd,
1774 cwd,
1775 pats,
1775 pats,
1776 include,
1776 include,
1777 exclude,
1777 exclude,
1778 default,
1778 default,
1779 auditor=r.auditor,
1779 auditor=r.auditor,
1780 ctx=self,
1780 ctx=self,
1781 listsubrepos=listsubrepos,
1781 listsubrepos=listsubrepos,
1782 badfn=badfn,
1782 badfn=badfn,
1783 icasefs=icasefs,
1783 icasefs=icasefs,
1784 )
1784 )
1785
1785
1786 def _filtersuspectsymlink(self, files):
1786 def _filtersuspectsymlink(self, files):
1787 if not files or self._repo.dirstate._checklink:
1787 if not files or self._repo.dirstate._checklink:
1788 return files
1788 return files
1789
1789
1790 # Symlink placeholders may get non-symlink-like contents
1790 # Symlink placeholders may get non-symlink-like contents
1791 # via user error or dereferencing by NFS or Samba servers,
1791 # via user error or dereferencing by NFS or Samba servers,
1792 # so we filter out any placeholders that don't look like a
1792 # so we filter out any placeholders that don't look like a
1793 # symlink
1793 # symlink
1794 sane = []
1794 sane = []
1795 for f in files:
1795 for f in files:
1796 if self.flags(f) == b'l':
1796 if self.flags(f) == b'l':
1797 d = self[f].data()
1797 d = self[f].data()
1798 if (
1798 if (
1799 d == b''
1799 d == b''
1800 or len(d) >= 1024
1800 or len(d) >= 1024
1801 or b'\n' in d
1801 or b'\n' in d
1802 or stringutil.binary(d)
1802 or stringutil.binary(d)
1803 ):
1803 ):
1804 self._repo.ui.debug(
1804 self._repo.ui.debug(
1805 b'ignoring suspect symlink placeholder "%s"\n' % f
1805 b'ignoring suspect symlink placeholder "%s"\n' % f
1806 )
1806 )
1807 continue
1807 continue
1808 sane.append(f)
1808 sane.append(f)
1809 return sane
1809 return sane
1810
1810
1811 def _checklookup(self, files, mtime_boundary):
1811 def _checklookup(self, files, mtime_boundary):
1812 # check for any possibly clean files
1812 # check for any possibly clean files
1813 if not files:
1813 if not files:
1814 return [], [], [], []
1814 return [], [], [], []
1815
1815
1816 modified = []
1816 modified = []
1817 deleted = []
1817 deleted = []
1818 clean = []
1818 clean = []
1819 fixup = []
1819 fixup = []
1820 pctx = self._parents[0]
1820 pctx = self._parents[0]
1821 # do a full compare of any files that might have changed
1821 # do a full compare of any files that might have changed
1822 for f in sorted(files):
1822 for f in sorted(files):
1823 try:
1823 try:
1824 # This will return True for a file that got replaced by a
1824 # This will return True for a file that got replaced by a
1825 # directory in the interim, but fixing that is pretty hard.
1825 # directory in the interim, but fixing that is pretty hard.
1826 if (
1826 if (
1827 f not in pctx
1827 f not in pctx
1828 or self.flags(f) != pctx.flags(f)
1828 or self.flags(f) != pctx.flags(f)
1829 or pctx[f].cmp(self[f])
1829 or pctx[f].cmp(self[f])
1830 ):
1830 ):
1831 modified.append(f)
1831 modified.append(f)
1832 elif mtime_boundary is None:
1832 elif mtime_boundary is None:
1833 clean.append(f)
1833 clean.append(f)
1834 else:
1834 else:
1835 s = self[f].lstat()
1835 s = self[f].lstat()
1836 mode = s.st_mode
1836 mode = s.st_mode
1837 size = s.st_size
1837 size = s.st_size
1838 file_mtime = timestamp.reliable_mtime_of(s, mtime_boundary)
1838 file_mtime = timestamp.reliable_mtime_of(s, mtime_boundary)
1839 if file_mtime is not None:
1839 if file_mtime is not None:
1840 cache_info = (mode, size, file_mtime)
1840 cache_info = (mode, size, file_mtime)
1841 fixup.append((f, cache_info))
1841 fixup.append((f, cache_info))
1842 else:
1842 else:
1843 clean.append(f)
1843 clean.append(f)
1844 except (IOError, OSError):
1844 except (IOError, OSError):
1845 # A file become inaccessible in between? Mark it as deleted,
1845 # A file become inaccessible in between? Mark it as deleted,
1846 # matching dirstate behavior (issue5584).
1846 # matching dirstate behavior (issue5584).
1847 # The dirstate has more complex behavior around whether a
1847 # The dirstate has more complex behavior around whether a
1848 # missing file matches a directory, etc, but we don't need to
1848 # missing file matches a directory, etc, but we don't need to
1849 # bother with that: if f has made it to this point, we're sure
1849 # bother with that: if f has made it to this point, we're sure
1850 # it's in the dirstate.
1850 # it's in the dirstate.
1851 deleted.append(f)
1851 deleted.append(f)
1852
1852
1853 return modified, deleted, clean, fixup
1853 return modified, deleted, clean, fixup
1854
1854
1855 def _poststatusfixup(self, status, fixup):
1855 def _poststatusfixup(self, status, fixup):
1856 """update dirstate for files that are actually clean"""
1856 """update dirstate for files that are actually clean"""
1857 dirstate = self._repo.dirstate
1857 dirstate = self._repo.dirstate
1858 poststatus = self._repo.postdsstatus()
1858 poststatus = self._repo.postdsstatus()
1859 if fixup:
1859 if fixup:
1860 if dirstate.is_changing_parents:
1860 if dirstate.is_changing_parents:
1861 normal = lambda f, pfd: dirstate.update_file(
1861 normal = lambda f, pfd: dirstate.update_file(
1862 f,
1862 f,
1863 p1_tracked=True,
1863 p1_tracked=True,
1864 wc_tracked=True,
1864 wc_tracked=True,
1865 )
1865 )
1866 else:
1866 else:
1867 normal = dirstate.set_clean
1867 normal = dirstate.set_clean
1868 for f, pdf in fixup:
1868 for f, pdf in fixup:
1869 normal(f, pdf)
1869 normal(f, pdf)
1870 if poststatus or self._repo.dirstate._dirty:
1870 if poststatus or self._repo.dirstate._dirty:
1871 try:
1871 try:
1872 # updating the dirstate is optional
1872 # updating the dirstate is optional
1873 # so we don't wait on the lock
1873 # so we don't wait on the lock
1874 # wlock can invalidate the dirstate, so cache normal _after_
1874 # wlock can invalidate the dirstate, so cache normal _after_
1875 # taking the lock
1875 # taking the lock
1876 pre_dirty = dirstate._dirty
1876 pre_dirty = dirstate._dirty
1877 with self._repo.wlock(False):
1877 with self._repo.wlock(False):
1878 assert self._repo.dirstate is dirstate
1878 assert self._repo.dirstate is dirstate
1879 post_dirty = dirstate._dirty
1879 post_dirty = dirstate._dirty
1880 if post_dirty:
1880 if post_dirty:
1881 tr = self._repo.currenttransaction()
1881 tr = self._repo.currenttransaction()
1882 dirstate.write(tr)
1882 dirstate.write(tr)
1883 elif pre_dirty:
1883 elif pre_dirty:
1884 # the wlock grabbing detected that dirtate changes
1884 # the wlock grabbing detected that dirtate changes
1885 # needed to be dropped
1885 # needed to be dropped
1886 m = b'skip updating dirstate: identity mismatch\n'
1886 m = b'skip updating dirstate: identity mismatch\n'
1887 self._repo.ui.debug(m)
1887 self._repo.ui.debug(m)
1888 if poststatus:
1888 if poststatus:
1889 for ps in poststatus:
1889 for ps in poststatus:
1890 ps(self, status)
1890 ps(self, status)
1891 except error.LockError:
1891 except error.LockError:
1892 dirstate.invalidate()
1892 dirstate.invalidate()
1893 finally:
1893 finally:
1894 # Even if the wlock couldn't be grabbed, clear out the list.
1894 # Even if the wlock couldn't be grabbed, clear out the list.
1895 self._repo.clearpostdsstatus()
1895 self._repo.clearpostdsstatus()
1896
1896
1897 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1897 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1898 '''Gets the status from the dirstate -- internal use only.'''
1898 '''Gets the status from the dirstate -- internal use only.'''
1899 subrepos = []
1899 subrepos = []
1900 if b'.hgsub' in self:
1900 if b'.hgsub' in self:
1901 subrepos = sorted(self.substate)
1901 subrepos = sorted(self.substate)
1902 cmp, s, mtime_boundary = self._repo.dirstate.status(
1902 if True:
1903 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1903 cmp, s, mtime_boundary = self._repo.dirstate.status(
1904 )
1904 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1905
1906 # check for any possibly clean files
1907 fixup = []
1908 if cmp:
1909 modified2, deleted2, clean_set, fixup = self._checklookup(
1910 cmp, mtime_boundary
1911 )
1905 )
1912 s.modified.extend(modified2)
1906
1913 s.deleted.extend(deleted2)
1907 # check for any possibly clean files
1914
1908 fixup = []
1915 if clean_set and clean:
1909 if cmp:
1916 s.clean.extend(clean_set)
1910 modified2, deleted2, clean_set, fixup = self._checklookup(
1917 if fixup and clean:
1911 cmp, mtime_boundary
1918 s.clean.extend((f for f, _ in fixup))
1912 )
1919
1913 s.modified.extend(modified2)
1920 self._poststatusfixup(s, fixup)
1914 s.deleted.extend(deleted2)
1915
1916 if clean_set and clean:
1917 s.clean.extend(clean_set)
1918 if fixup and clean:
1919 s.clean.extend((f for f, _ in fixup))
1920
1921 self._poststatusfixup(s, fixup)
1921
1922
1922 if match.always():
1923 if match.always():
1923 # cache for performance
1924 # cache for performance
1924 if s.unknown or s.ignored or s.clean:
1925 if s.unknown or s.ignored or s.clean:
1925 # "_status" is cached with list*=False in the normal route
1926 # "_status" is cached with list*=False in the normal route
1926 self._status = scmutil.status(
1927 self._status = scmutil.status(
1927 s.modified, s.added, s.removed, s.deleted, [], [], []
1928 s.modified, s.added, s.removed, s.deleted, [], [], []
1928 )
1929 )
1929 else:
1930 else:
1930 self._status = s
1931 self._status = s
1931
1932
1932 return s
1933 return s
1933
1934
1934 @propertycache
1935 @propertycache
1935 def _copies(self):
1936 def _copies(self):
1936 p1copies = {}
1937 p1copies = {}
1937 p2copies = {}
1938 p2copies = {}
1938 parents = self._repo.dirstate.parents()
1939 parents = self._repo.dirstate.parents()
1939 p1manifest = self._repo[parents[0]].manifest()
1940 p1manifest = self._repo[parents[0]].manifest()
1940 p2manifest = self._repo[parents[1]].manifest()
1941 p2manifest = self._repo[parents[1]].manifest()
1941 changedset = set(self.added()) | set(self.modified())
1942 changedset = set(self.added()) | set(self.modified())
1942 narrowmatch = self._repo.narrowmatch()
1943 narrowmatch = self._repo.narrowmatch()
1943 for dst, src in self._repo.dirstate.copies().items():
1944 for dst, src in self._repo.dirstate.copies().items():
1944 if dst not in changedset or not narrowmatch(dst):
1945 if dst not in changedset or not narrowmatch(dst):
1945 continue
1946 continue
1946 if src in p1manifest:
1947 if src in p1manifest:
1947 p1copies[dst] = src
1948 p1copies[dst] = src
1948 elif src in p2manifest:
1949 elif src in p2manifest:
1949 p2copies[dst] = src
1950 p2copies[dst] = src
1950 return p1copies, p2copies
1951 return p1copies, p2copies
1951
1952
1952 @propertycache
1953 @propertycache
1953 def _manifest(self):
1954 def _manifest(self):
1954 """generate a manifest corresponding to the values in self._status
1955 """generate a manifest corresponding to the values in self._status
1955
1956
1956 This reuse the file nodeid from parent, but we use special node
1957 This reuse the file nodeid from parent, but we use special node
1957 identifiers for added and modified files. This is used by manifests
1958 identifiers for added and modified files. This is used by manifests
1958 merge to see that files are different and by update logic to avoid
1959 merge to see that files are different and by update logic to avoid
1959 deleting newly added files.
1960 deleting newly added files.
1960 """
1961 """
1961 return self._buildstatusmanifest(self._status)
1962 return self._buildstatusmanifest(self._status)
1962
1963
1963 def _buildstatusmanifest(self, status):
1964 def _buildstatusmanifest(self, status):
1964 """Builds a manifest that includes the given status results."""
1965 """Builds a manifest that includes the given status results."""
1965 parents = self.parents()
1966 parents = self.parents()
1966
1967
1967 man = parents[0].manifest().copy()
1968 man = parents[0].manifest().copy()
1968
1969
1969 ff = self._flagfunc
1970 ff = self._flagfunc
1970 for i, l in (
1971 for i, l in (
1971 (self._repo.nodeconstants.addednodeid, status.added),
1972 (self._repo.nodeconstants.addednodeid, status.added),
1972 (self._repo.nodeconstants.modifiednodeid, status.modified),
1973 (self._repo.nodeconstants.modifiednodeid, status.modified),
1973 ):
1974 ):
1974 for f in l:
1975 for f in l:
1975 man[f] = i
1976 man[f] = i
1976 try:
1977 try:
1977 man.setflag(f, ff(f))
1978 man.setflag(f, ff(f))
1978 except OSError:
1979 except OSError:
1979 pass
1980 pass
1980
1981
1981 for f in status.deleted + status.removed:
1982 for f in status.deleted + status.removed:
1982 if f in man:
1983 if f in man:
1983 del man[f]
1984 del man[f]
1984
1985
1985 return man
1986 return man
1986
1987
1987 def _buildstatus(
1988 def _buildstatus(
1988 self, other, s, match, listignored, listclean, listunknown
1989 self, other, s, match, listignored, listclean, listunknown
1989 ):
1990 ):
1990 """build a status with respect to another context
1991 """build a status with respect to another context
1991
1992
1992 This includes logic for maintaining the fast path of status when
1993 This includes logic for maintaining the fast path of status when
1993 comparing the working directory against its parent, which is to skip
1994 comparing the working directory against its parent, which is to skip
1994 building a new manifest if self (working directory) is not comparing
1995 building a new manifest if self (working directory) is not comparing
1995 against its parent (repo['.']).
1996 against its parent (repo['.']).
1996 """
1997 """
1997 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1998 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1998 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1999 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1999 # might have accidentally ended up with the entire contents of the file
2000 # might have accidentally ended up with the entire contents of the file
2000 # they are supposed to be linking to.
2001 # they are supposed to be linking to.
2001 s.modified[:] = self._filtersuspectsymlink(s.modified)
2002 s.modified[:] = self._filtersuspectsymlink(s.modified)
2002 if other != self._repo[b'.']:
2003 if other != self._repo[b'.']:
2003 s = super(workingctx, self)._buildstatus(
2004 s = super(workingctx, self)._buildstatus(
2004 other, s, match, listignored, listclean, listunknown
2005 other, s, match, listignored, listclean, listunknown
2005 )
2006 )
2006 return s
2007 return s
2007
2008
2008 def _matchstatus(self, other, match):
2009 def _matchstatus(self, other, match):
2009 """override the match method with a filter for directory patterns
2010 """override the match method with a filter for directory patterns
2010
2011
2011 We use inheritance to customize the match.bad method only in cases of
2012 We use inheritance to customize the match.bad method only in cases of
2012 workingctx since it belongs only to the working directory when
2013 workingctx since it belongs only to the working directory when
2013 comparing against the parent changeset.
2014 comparing against the parent changeset.
2014
2015
2015 If we aren't comparing against the working directory's parent, then we
2016 If we aren't comparing against the working directory's parent, then we
2016 just use the default match object sent to us.
2017 just use the default match object sent to us.
2017 """
2018 """
2018 if other != self._repo[b'.']:
2019 if other != self._repo[b'.']:
2019
2020
2020 def bad(f, msg):
2021 def bad(f, msg):
2021 # 'f' may be a directory pattern from 'match.files()',
2022 # 'f' may be a directory pattern from 'match.files()',
2022 # so 'f not in ctx1' is not enough
2023 # so 'f not in ctx1' is not enough
2023 if f not in other and not other.hasdir(f):
2024 if f not in other and not other.hasdir(f):
2024 self._repo.ui.warn(
2025 self._repo.ui.warn(
2025 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2026 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2026 )
2027 )
2027
2028
2028 match.bad = bad
2029 match.bad = bad
2029 return match
2030 return match
2030
2031
2031 def walk(self, match):
2032 def walk(self, match):
2032 '''Generates matching file names.'''
2033 '''Generates matching file names.'''
2033 return sorted(
2034 return sorted(
2034 self._repo.dirstate.walk(
2035 self._repo.dirstate.walk(
2035 self._repo.narrowmatch(match),
2036 self._repo.narrowmatch(match),
2036 subrepos=sorted(self.substate),
2037 subrepos=sorted(self.substate),
2037 unknown=True,
2038 unknown=True,
2038 ignored=False,
2039 ignored=False,
2039 )
2040 )
2040 )
2041 )
2041
2042
2042 def matches(self, match):
2043 def matches(self, match):
2043 match = self._repo.narrowmatch(match)
2044 match = self._repo.narrowmatch(match)
2044 ds = self._repo.dirstate
2045 ds = self._repo.dirstate
2045 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2046 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2046
2047
2047 def markcommitted(self, node):
2048 def markcommitted(self, node):
2048 with self._repo.dirstate.changing_parents(self._repo):
2049 with self._repo.dirstate.changing_parents(self._repo):
2049 for f in self.modified() + self.added():
2050 for f in self.modified() + self.added():
2050 self._repo.dirstate.update_file(
2051 self._repo.dirstate.update_file(
2051 f, p1_tracked=True, wc_tracked=True
2052 f, p1_tracked=True, wc_tracked=True
2052 )
2053 )
2053 for f in self.removed():
2054 for f in self.removed():
2054 self._repo.dirstate.update_file(
2055 self._repo.dirstate.update_file(
2055 f, p1_tracked=False, wc_tracked=False
2056 f, p1_tracked=False, wc_tracked=False
2056 )
2057 )
2057 self._repo.dirstate.setparents(node)
2058 self._repo.dirstate.setparents(node)
2058 self._repo._quick_access_changeid_invalidate()
2059 self._repo._quick_access_changeid_invalidate()
2059
2060
2060 sparse.aftercommit(self._repo, node)
2061 sparse.aftercommit(self._repo, node)
2061
2062
2062 # write changes out explicitly, because nesting wlock at
2063 # write changes out explicitly, because nesting wlock at
2063 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2064 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2064 # from immediately doing so for subsequent changing files
2065 # from immediately doing so for subsequent changing files
2065 self._repo.dirstate.write(self._repo.currenttransaction())
2066 self._repo.dirstate.write(self._repo.currenttransaction())
2066
2067
2067 def mergestate(self, clean=False):
2068 def mergestate(self, clean=False):
2068 if clean:
2069 if clean:
2069 return mergestatemod.mergestate.clean(self._repo)
2070 return mergestatemod.mergestate.clean(self._repo)
2070 return mergestatemod.mergestate.read(self._repo)
2071 return mergestatemod.mergestate.read(self._repo)
2071
2072
2072
2073
2073 class committablefilectx(basefilectx):
2074 class committablefilectx(basefilectx):
2074 """A committablefilectx provides common functionality for a file context
2075 """A committablefilectx provides common functionality for a file context
2075 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2076 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2076
2077
2077 def __init__(self, repo, path, filelog=None, ctx=None):
2078 def __init__(self, repo, path, filelog=None, ctx=None):
2078 self._repo = repo
2079 self._repo = repo
2079 self._path = path
2080 self._path = path
2080 self._changeid = None
2081 self._changeid = None
2081 self._filerev = self._filenode = None
2082 self._filerev = self._filenode = None
2082
2083
2083 if filelog is not None:
2084 if filelog is not None:
2084 self._filelog = filelog
2085 self._filelog = filelog
2085 if ctx:
2086 if ctx:
2086 self._changectx = ctx
2087 self._changectx = ctx
2087
2088
2088 def __nonzero__(self):
2089 def __nonzero__(self):
2089 return True
2090 return True
2090
2091
2091 __bool__ = __nonzero__
2092 __bool__ = __nonzero__
2092
2093
2093 def linkrev(self):
2094 def linkrev(self):
2094 # linked to self._changectx no matter if file is modified or not
2095 # linked to self._changectx no matter if file is modified or not
2095 return self.rev()
2096 return self.rev()
2096
2097
2097 def renamed(self):
2098 def renamed(self):
2098 path = self.copysource()
2099 path = self.copysource()
2099 if not path:
2100 if not path:
2100 return None
2101 return None
2101 return (
2102 return (
2102 path,
2103 path,
2103 self._changectx._parents[0]._manifest.get(
2104 self._changectx._parents[0]._manifest.get(
2104 path, self._repo.nodeconstants.nullid
2105 path, self._repo.nodeconstants.nullid
2105 ),
2106 ),
2106 )
2107 )
2107
2108
2108 def parents(self):
2109 def parents(self):
2109 '''return parent filectxs, following copies if necessary'''
2110 '''return parent filectxs, following copies if necessary'''
2110
2111
2111 def filenode(ctx, path):
2112 def filenode(ctx, path):
2112 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2113 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2113
2114
2114 path = self._path
2115 path = self._path
2115 fl = self._filelog
2116 fl = self._filelog
2116 pcl = self._changectx._parents
2117 pcl = self._changectx._parents
2117 renamed = self.renamed()
2118 renamed = self.renamed()
2118
2119
2119 if renamed:
2120 if renamed:
2120 pl = [renamed + (None,)]
2121 pl = [renamed + (None,)]
2121 else:
2122 else:
2122 pl = [(path, filenode(pcl[0], path), fl)]
2123 pl = [(path, filenode(pcl[0], path), fl)]
2123
2124
2124 for pc in pcl[1:]:
2125 for pc in pcl[1:]:
2125 pl.append((path, filenode(pc, path), fl))
2126 pl.append((path, filenode(pc, path), fl))
2126
2127
2127 return [
2128 return [
2128 self._parentfilectx(p, fileid=n, filelog=l)
2129 self._parentfilectx(p, fileid=n, filelog=l)
2129 for p, n, l in pl
2130 for p, n, l in pl
2130 if n != self._repo.nodeconstants.nullid
2131 if n != self._repo.nodeconstants.nullid
2131 ]
2132 ]
2132
2133
2133 def children(self):
2134 def children(self):
2134 return []
2135 return []
2135
2136
2136
2137
2137 class workingfilectx(committablefilectx):
2138 class workingfilectx(committablefilectx):
2138 """A workingfilectx object makes access to data related to a particular
2139 """A workingfilectx object makes access to data related to a particular
2139 file in the working directory convenient."""
2140 file in the working directory convenient."""
2140
2141
2141 def __init__(self, repo, path, filelog=None, workingctx=None):
2142 def __init__(self, repo, path, filelog=None, workingctx=None):
2142 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2143 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2143
2144
2144 @propertycache
2145 @propertycache
2145 def _changectx(self):
2146 def _changectx(self):
2146 return workingctx(self._repo)
2147 return workingctx(self._repo)
2147
2148
2148 def data(self):
2149 def data(self):
2149 return self._repo.wread(self._path)
2150 return self._repo.wread(self._path)
2150
2151
2151 def copysource(self):
2152 def copysource(self):
2152 return self._repo.dirstate.copied(self._path)
2153 return self._repo.dirstate.copied(self._path)
2153
2154
2154 def size(self):
2155 def size(self):
2155 return self._repo.wvfs.lstat(self._path).st_size
2156 return self._repo.wvfs.lstat(self._path).st_size
2156
2157
2157 def lstat(self):
2158 def lstat(self):
2158 return self._repo.wvfs.lstat(self._path)
2159 return self._repo.wvfs.lstat(self._path)
2159
2160
2160 def date(self):
2161 def date(self):
2161 t, tz = self._changectx.date()
2162 t, tz = self._changectx.date()
2162 try:
2163 try:
2163 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2164 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2164 except FileNotFoundError:
2165 except FileNotFoundError:
2165 return (t, tz)
2166 return (t, tz)
2166
2167
2167 def exists(self):
2168 def exists(self):
2168 return self._repo.wvfs.exists(self._path)
2169 return self._repo.wvfs.exists(self._path)
2169
2170
2170 def lexists(self):
2171 def lexists(self):
2171 return self._repo.wvfs.lexists(self._path)
2172 return self._repo.wvfs.lexists(self._path)
2172
2173
2173 def audit(self):
2174 def audit(self):
2174 return self._repo.wvfs.audit(self._path)
2175 return self._repo.wvfs.audit(self._path)
2175
2176
2176 def cmp(self, fctx):
2177 def cmp(self, fctx):
2177 """compare with other file context
2178 """compare with other file context
2178
2179
2179 returns True if different than fctx.
2180 returns True if different than fctx.
2180 """
2181 """
2181 # fctx should be a filectx (not a workingfilectx)
2182 # fctx should be a filectx (not a workingfilectx)
2182 # invert comparison to reuse the same code path
2183 # invert comparison to reuse the same code path
2183 return fctx.cmp(self)
2184 return fctx.cmp(self)
2184
2185
2185 def remove(self, ignoremissing=False):
2186 def remove(self, ignoremissing=False):
2186 """wraps unlink for a repo's working directory"""
2187 """wraps unlink for a repo's working directory"""
2187 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2188 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2188 self._repo.wvfs.unlinkpath(
2189 self._repo.wvfs.unlinkpath(
2189 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2190 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2190 )
2191 )
2191
2192
2192 def write(self, data, flags, backgroundclose=False, **kwargs):
2193 def write(self, data, flags, backgroundclose=False, **kwargs):
2193 """wraps repo.wwrite"""
2194 """wraps repo.wwrite"""
2194 return self._repo.wwrite(
2195 return self._repo.wwrite(
2195 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2196 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2196 )
2197 )
2197
2198
2198 def markcopied(self, src):
2199 def markcopied(self, src):
2199 """marks this file a copy of `src`"""
2200 """marks this file a copy of `src`"""
2200 self._repo.dirstate.copy(src, self._path)
2201 self._repo.dirstate.copy(src, self._path)
2201
2202
2202 def clearunknown(self):
2203 def clearunknown(self):
2203 """Removes conflicting items in the working directory so that
2204 """Removes conflicting items in the working directory so that
2204 ``write()`` can be called successfully.
2205 ``write()`` can be called successfully.
2205 """
2206 """
2206 wvfs = self._repo.wvfs
2207 wvfs = self._repo.wvfs
2207 f = self._path
2208 f = self._path
2208 wvfs.audit(f)
2209 wvfs.audit(f)
2209 if self._repo.ui.configbool(
2210 if self._repo.ui.configbool(
2210 b'experimental', b'merge.checkpathconflicts'
2211 b'experimental', b'merge.checkpathconflicts'
2211 ):
2212 ):
2212 # remove files under the directory as they should already be
2213 # remove files under the directory as they should already be
2213 # warned and backed up
2214 # warned and backed up
2214 if wvfs.isdir(f) and not wvfs.islink(f):
2215 if wvfs.isdir(f) and not wvfs.islink(f):
2215 wvfs.rmtree(f, forcibly=True)
2216 wvfs.rmtree(f, forcibly=True)
2216 for p in reversed(list(pathutil.finddirs(f))):
2217 for p in reversed(list(pathutil.finddirs(f))):
2217 if wvfs.isfileorlink(p):
2218 if wvfs.isfileorlink(p):
2218 wvfs.unlink(p)
2219 wvfs.unlink(p)
2219 break
2220 break
2220 else:
2221 else:
2221 # don't remove files if path conflicts are not processed
2222 # don't remove files if path conflicts are not processed
2222 if wvfs.isdir(f) and not wvfs.islink(f):
2223 if wvfs.isdir(f) and not wvfs.islink(f):
2223 wvfs.removedirs(f)
2224 wvfs.removedirs(f)
2224
2225
2225 def setflags(self, l, x):
2226 def setflags(self, l, x):
2226 self._repo.wvfs.setflags(self._path, l, x)
2227 self._repo.wvfs.setflags(self._path, l, x)
2227
2228
2228
2229
2229 class overlayworkingctx(committablectx):
2230 class overlayworkingctx(committablectx):
2230 """Wraps another mutable context with a write-back cache that can be
2231 """Wraps another mutable context with a write-back cache that can be
2231 converted into a commit context.
2232 converted into a commit context.
2232
2233
2233 self._cache[path] maps to a dict with keys: {
2234 self._cache[path] maps to a dict with keys: {
2234 'exists': bool?
2235 'exists': bool?
2235 'date': date?
2236 'date': date?
2236 'data': str?
2237 'data': str?
2237 'flags': str?
2238 'flags': str?
2238 'copied': str? (path or None)
2239 'copied': str? (path or None)
2239 }
2240 }
2240 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2241 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2241 is `False`, the file was deleted.
2242 is `False`, the file was deleted.
2242 """
2243 """
2243
2244
2244 def __init__(self, repo):
2245 def __init__(self, repo):
2245 super(overlayworkingctx, self).__init__(repo)
2246 super(overlayworkingctx, self).__init__(repo)
2246 self.clean()
2247 self.clean()
2247
2248
2248 def setbase(self, wrappedctx):
2249 def setbase(self, wrappedctx):
2249 self._wrappedctx = wrappedctx
2250 self._wrappedctx = wrappedctx
2250 self._parents = [wrappedctx]
2251 self._parents = [wrappedctx]
2251 # Drop old manifest cache as it is now out of date.
2252 # Drop old manifest cache as it is now out of date.
2252 # This is necessary when, e.g., rebasing several nodes with one
2253 # This is necessary when, e.g., rebasing several nodes with one
2253 # ``overlayworkingctx`` (e.g. with --collapse).
2254 # ``overlayworkingctx`` (e.g. with --collapse).
2254 util.clearcachedproperty(self, b'_manifest')
2255 util.clearcachedproperty(self, b'_manifest')
2255
2256
2256 def setparents(self, p1node, p2node=None):
2257 def setparents(self, p1node, p2node=None):
2257 if p2node is None:
2258 if p2node is None:
2258 p2node = self._repo.nodeconstants.nullid
2259 p2node = self._repo.nodeconstants.nullid
2259 assert p1node == self._wrappedctx.node()
2260 assert p1node == self._wrappedctx.node()
2260 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2261 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2261
2262
2262 def data(self, path):
2263 def data(self, path):
2263 if self.isdirty(path):
2264 if self.isdirty(path):
2264 if self._cache[path][b'exists']:
2265 if self._cache[path][b'exists']:
2265 if self._cache[path][b'data'] is not None:
2266 if self._cache[path][b'data'] is not None:
2266 return self._cache[path][b'data']
2267 return self._cache[path][b'data']
2267 else:
2268 else:
2268 # Must fallback here, too, because we only set flags.
2269 # Must fallback here, too, because we only set flags.
2269 return self._wrappedctx[path].data()
2270 return self._wrappedctx[path].data()
2270 else:
2271 else:
2271 raise error.ProgrammingError(
2272 raise error.ProgrammingError(
2272 b"No such file or directory: %s" % path
2273 b"No such file or directory: %s" % path
2273 )
2274 )
2274 else:
2275 else:
2275 return self._wrappedctx[path].data()
2276 return self._wrappedctx[path].data()
2276
2277
2277 @propertycache
2278 @propertycache
2278 def _manifest(self):
2279 def _manifest(self):
2279 parents = self.parents()
2280 parents = self.parents()
2280 man = parents[0].manifest().copy()
2281 man = parents[0].manifest().copy()
2281
2282
2282 flag = self._flagfunc
2283 flag = self._flagfunc
2283 for path in self.added():
2284 for path in self.added():
2284 man[path] = self._repo.nodeconstants.addednodeid
2285 man[path] = self._repo.nodeconstants.addednodeid
2285 man.setflag(path, flag(path))
2286 man.setflag(path, flag(path))
2286 for path in self.modified():
2287 for path in self.modified():
2287 man[path] = self._repo.nodeconstants.modifiednodeid
2288 man[path] = self._repo.nodeconstants.modifiednodeid
2288 man.setflag(path, flag(path))
2289 man.setflag(path, flag(path))
2289 for path in self.removed():
2290 for path in self.removed():
2290 del man[path]
2291 del man[path]
2291 return man
2292 return man
2292
2293
2293 @propertycache
2294 @propertycache
2294 def _flagfunc(self):
2295 def _flagfunc(self):
2295 def f(path):
2296 def f(path):
2296 return self._cache[path][b'flags']
2297 return self._cache[path][b'flags']
2297
2298
2298 return f
2299 return f
2299
2300
2300 def files(self):
2301 def files(self):
2301 return sorted(self.added() + self.modified() + self.removed())
2302 return sorted(self.added() + self.modified() + self.removed())
2302
2303
2303 def modified(self):
2304 def modified(self):
2304 return [
2305 return [
2305 f
2306 f
2306 for f in self._cache.keys()
2307 for f in self._cache.keys()
2307 if self._cache[f][b'exists'] and self._existsinparent(f)
2308 if self._cache[f][b'exists'] and self._existsinparent(f)
2308 ]
2309 ]
2309
2310
2310 def added(self):
2311 def added(self):
2311 return [
2312 return [
2312 f
2313 f
2313 for f in self._cache.keys()
2314 for f in self._cache.keys()
2314 if self._cache[f][b'exists'] and not self._existsinparent(f)
2315 if self._cache[f][b'exists'] and not self._existsinparent(f)
2315 ]
2316 ]
2316
2317
2317 def removed(self):
2318 def removed(self):
2318 return [
2319 return [
2319 f
2320 f
2320 for f in self._cache.keys()
2321 for f in self._cache.keys()
2321 if not self._cache[f][b'exists'] and self._existsinparent(f)
2322 if not self._cache[f][b'exists'] and self._existsinparent(f)
2322 ]
2323 ]
2323
2324
2324 def p1copies(self):
2325 def p1copies(self):
2325 copies = {}
2326 copies = {}
2326 narrowmatch = self._repo.narrowmatch()
2327 narrowmatch = self._repo.narrowmatch()
2327 for f in self._cache.keys():
2328 for f in self._cache.keys():
2328 if not narrowmatch(f):
2329 if not narrowmatch(f):
2329 continue
2330 continue
2330 copies.pop(f, None) # delete if it exists
2331 copies.pop(f, None) # delete if it exists
2331 source = self._cache[f][b'copied']
2332 source = self._cache[f][b'copied']
2332 if source:
2333 if source:
2333 copies[f] = source
2334 copies[f] = source
2334 return copies
2335 return copies
2335
2336
2336 def p2copies(self):
2337 def p2copies(self):
2337 copies = {}
2338 copies = {}
2338 narrowmatch = self._repo.narrowmatch()
2339 narrowmatch = self._repo.narrowmatch()
2339 for f in self._cache.keys():
2340 for f in self._cache.keys():
2340 if not narrowmatch(f):
2341 if not narrowmatch(f):
2341 continue
2342 continue
2342 copies.pop(f, None) # delete if it exists
2343 copies.pop(f, None) # delete if it exists
2343 source = self._cache[f][b'copied']
2344 source = self._cache[f][b'copied']
2344 if source:
2345 if source:
2345 copies[f] = source
2346 copies[f] = source
2346 return copies
2347 return copies
2347
2348
2348 def isinmemory(self):
2349 def isinmemory(self):
2349 return True
2350 return True
2350
2351
2351 def filedate(self, path):
2352 def filedate(self, path):
2352 if self.isdirty(path):
2353 if self.isdirty(path):
2353 return self._cache[path][b'date']
2354 return self._cache[path][b'date']
2354 else:
2355 else:
2355 return self._wrappedctx[path].date()
2356 return self._wrappedctx[path].date()
2356
2357
2357 def markcopied(self, path, origin):
2358 def markcopied(self, path, origin):
2358 self._markdirty(
2359 self._markdirty(
2359 path,
2360 path,
2360 exists=True,
2361 exists=True,
2361 date=self.filedate(path),
2362 date=self.filedate(path),
2362 flags=self.flags(path),
2363 flags=self.flags(path),
2363 copied=origin,
2364 copied=origin,
2364 )
2365 )
2365
2366
2366 def copydata(self, path):
2367 def copydata(self, path):
2367 if self.isdirty(path):
2368 if self.isdirty(path):
2368 return self._cache[path][b'copied']
2369 return self._cache[path][b'copied']
2369 else:
2370 else:
2370 return None
2371 return None
2371
2372
2372 def flags(self, path):
2373 def flags(self, path):
2373 if self.isdirty(path):
2374 if self.isdirty(path):
2374 if self._cache[path][b'exists']:
2375 if self._cache[path][b'exists']:
2375 return self._cache[path][b'flags']
2376 return self._cache[path][b'flags']
2376 else:
2377 else:
2377 raise error.ProgrammingError(
2378 raise error.ProgrammingError(
2378 b"No such file or directory: %s" % path
2379 b"No such file or directory: %s" % path
2379 )
2380 )
2380 else:
2381 else:
2381 return self._wrappedctx[path].flags()
2382 return self._wrappedctx[path].flags()
2382
2383
2383 def __contains__(self, key):
2384 def __contains__(self, key):
2384 if key in self._cache:
2385 if key in self._cache:
2385 return self._cache[key][b'exists']
2386 return self._cache[key][b'exists']
2386 return key in self.p1()
2387 return key in self.p1()
2387
2388
2388 def _existsinparent(self, path):
2389 def _existsinparent(self, path):
2389 try:
2390 try:
2390 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2391 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2391 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2392 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2392 # with an ``exists()`` function.
2393 # with an ``exists()`` function.
2393 self._wrappedctx[path]
2394 self._wrappedctx[path]
2394 return True
2395 return True
2395 except error.ManifestLookupError:
2396 except error.ManifestLookupError:
2396 return False
2397 return False
2397
2398
2398 def _auditconflicts(self, path):
2399 def _auditconflicts(self, path):
2399 """Replicates conflict checks done by wvfs.write().
2400 """Replicates conflict checks done by wvfs.write().
2400
2401
2401 Since we never write to the filesystem and never call `applyupdates` in
2402 Since we never write to the filesystem and never call `applyupdates` in
2402 IMM, we'll never check that a path is actually writable -- e.g., because
2403 IMM, we'll never check that a path is actually writable -- e.g., because
2403 it adds `a/foo`, but `a` is actually a file in the other commit.
2404 it adds `a/foo`, but `a` is actually a file in the other commit.
2404 """
2405 """
2405
2406
2406 def fail(path, component):
2407 def fail(path, component):
2407 # p1() is the base and we're receiving "writes" for p2()'s
2408 # p1() is the base and we're receiving "writes" for p2()'s
2408 # files.
2409 # files.
2409 if b'l' in self.p1()[component].flags():
2410 if b'l' in self.p1()[component].flags():
2410 raise error.Abort(
2411 raise error.Abort(
2411 b"error: %s conflicts with symlink %s "
2412 b"error: %s conflicts with symlink %s "
2412 b"in %d." % (path, component, self.p1().rev())
2413 b"in %d." % (path, component, self.p1().rev())
2413 )
2414 )
2414 else:
2415 else:
2415 raise error.Abort(
2416 raise error.Abort(
2416 b"error: '%s' conflicts with file '%s' in "
2417 b"error: '%s' conflicts with file '%s' in "
2417 b"%d." % (path, component, self.p1().rev())
2418 b"%d." % (path, component, self.p1().rev())
2418 )
2419 )
2419
2420
2420 # Test that each new directory to be created to write this path from p2
2421 # Test that each new directory to be created to write this path from p2
2421 # is not a file in p1.
2422 # is not a file in p1.
2422 components = path.split(b'/')
2423 components = path.split(b'/')
2423 for i in range(len(components)):
2424 for i in range(len(components)):
2424 component = b"/".join(components[0:i])
2425 component = b"/".join(components[0:i])
2425 if component in self:
2426 if component in self:
2426 fail(path, component)
2427 fail(path, component)
2427
2428
2428 # Test the other direction -- that this path from p2 isn't a directory
2429 # Test the other direction -- that this path from p2 isn't a directory
2429 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2430 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2430 match = self.match([path], default=b'path')
2431 match = self.match([path], default=b'path')
2431 mfiles = list(self.p1().manifest().walk(match))
2432 mfiles = list(self.p1().manifest().walk(match))
2432 if len(mfiles) > 0:
2433 if len(mfiles) > 0:
2433 if len(mfiles) == 1 and mfiles[0] == path:
2434 if len(mfiles) == 1 and mfiles[0] == path:
2434 return
2435 return
2435 # omit the files which are deleted in current IMM wctx
2436 # omit the files which are deleted in current IMM wctx
2436 mfiles = [m for m in mfiles if m in self]
2437 mfiles = [m for m in mfiles if m in self]
2437 if not mfiles:
2438 if not mfiles:
2438 return
2439 return
2439 raise error.Abort(
2440 raise error.Abort(
2440 b"error: file '%s' cannot be written because "
2441 b"error: file '%s' cannot be written because "
2441 b" '%s/' is a directory in %s (containing %d "
2442 b" '%s/' is a directory in %s (containing %d "
2442 b"entries: %s)"
2443 b"entries: %s)"
2443 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2444 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2444 )
2445 )
2445
2446
2446 def write(self, path, data, flags=b'', **kwargs):
2447 def write(self, path, data, flags=b'', **kwargs):
2447 if data is None:
2448 if data is None:
2448 raise error.ProgrammingError(b"data must be non-None")
2449 raise error.ProgrammingError(b"data must be non-None")
2449 self._auditconflicts(path)
2450 self._auditconflicts(path)
2450 self._markdirty(
2451 self._markdirty(
2451 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2452 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2452 )
2453 )
2453
2454
2454 def setflags(self, path, l, x):
2455 def setflags(self, path, l, x):
2455 flag = b''
2456 flag = b''
2456 if l:
2457 if l:
2457 flag = b'l'
2458 flag = b'l'
2458 elif x:
2459 elif x:
2459 flag = b'x'
2460 flag = b'x'
2460 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2461 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2461
2462
2462 def remove(self, path):
2463 def remove(self, path):
2463 self._markdirty(path, exists=False)
2464 self._markdirty(path, exists=False)
2464
2465
2465 def exists(self, path):
2466 def exists(self, path):
2466 """exists behaves like `lexists`, but needs to follow symlinks and
2467 """exists behaves like `lexists`, but needs to follow symlinks and
2467 return False if they are broken.
2468 return False if they are broken.
2468 """
2469 """
2469 if self.isdirty(path):
2470 if self.isdirty(path):
2470 # If this path exists and is a symlink, "follow" it by calling
2471 # If this path exists and is a symlink, "follow" it by calling
2471 # exists on the destination path.
2472 # exists on the destination path.
2472 if (
2473 if (
2473 self._cache[path][b'exists']
2474 self._cache[path][b'exists']
2474 and b'l' in self._cache[path][b'flags']
2475 and b'l' in self._cache[path][b'flags']
2475 ):
2476 ):
2476 return self.exists(self._cache[path][b'data'].strip())
2477 return self.exists(self._cache[path][b'data'].strip())
2477 else:
2478 else:
2478 return self._cache[path][b'exists']
2479 return self._cache[path][b'exists']
2479
2480
2480 return self._existsinparent(path)
2481 return self._existsinparent(path)
2481
2482
2482 def lexists(self, path):
2483 def lexists(self, path):
2483 """lexists returns True if the path exists"""
2484 """lexists returns True if the path exists"""
2484 if self.isdirty(path):
2485 if self.isdirty(path):
2485 return self._cache[path][b'exists']
2486 return self._cache[path][b'exists']
2486
2487
2487 return self._existsinparent(path)
2488 return self._existsinparent(path)
2488
2489
2489 def size(self, path):
2490 def size(self, path):
2490 if self.isdirty(path):
2491 if self.isdirty(path):
2491 if self._cache[path][b'exists']:
2492 if self._cache[path][b'exists']:
2492 return len(self._cache[path][b'data'])
2493 return len(self._cache[path][b'data'])
2493 else:
2494 else:
2494 raise error.ProgrammingError(
2495 raise error.ProgrammingError(
2495 b"No such file or directory: %s" % path
2496 b"No such file or directory: %s" % path
2496 )
2497 )
2497 return self._wrappedctx[path].size()
2498 return self._wrappedctx[path].size()
2498
2499
2499 def tomemctx(
2500 def tomemctx(
2500 self,
2501 self,
2501 text,
2502 text,
2502 branch=None,
2503 branch=None,
2503 extra=None,
2504 extra=None,
2504 date=None,
2505 date=None,
2505 parents=None,
2506 parents=None,
2506 user=None,
2507 user=None,
2507 editor=None,
2508 editor=None,
2508 ):
2509 ):
2509 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2510 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2510 committed.
2511 committed.
2511
2512
2512 ``text`` is the commit message.
2513 ``text`` is the commit message.
2513 ``parents`` (optional) are rev numbers.
2514 ``parents`` (optional) are rev numbers.
2514 """
2515 """
2515 # Default parents to the wrapped context if not passed.
2516 # Default parents to the wrapped context if not passed.
2516 if parents is None:
2517 if parents is None:
2517 parents = self.parents()
2518 parents = self.parents()
2518 if len(parents) == 1:
2519 if len(parents) == 1:
2519 parents = (parents[0], None)
2520 parents = (parents[0], None)
2520
2521
2521 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2522 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2522 if parents[1] is None:
2523 if parents[1] is None:
2523 parents = (self._repo[parents[0]], None)
2524 parents = (self._repo[parents[0]], None)
2524 else:
2525 else:
2525 parents = (self._repo[parents[0]], self._repo[parents[1]])
2526 parents = (self._repo[parents[0]], self._repo[parents[1]])
2526
2527
2527 files = self.files()
2528 files = self.files()
2528
2529
2529 def getfile(repo, memctx, path):
2530 def getfile(repo, memctx, path):
2530 if self._cache[path][b'exists']:
2531 if self._cache[path][b'exists']:
2531 return memfilectx(
2532 return memfilectx(
2532 repo,
2533 repo,
2533 memctx,
2534 memctx,
2534 path,
2535 path,
2535 self._cache[path][b'data'],
2536 self._cache[path][b'data'],
2536 b'l' in self._cache[path][b'flags'],
2537 b'l' in self._cache[path][b'flags'],
2537 b'x' in self._cache[path][b'flags'],
2538 b'x' in self._cache[path][b'flags'],
2538 self._cache[path][b'copied'],
2539 self._cache[path][b'copied'],
2539 )
2540 )
2540 else:
2541 else:
2541 # Returning None, but including the path in `files`, is
2542 # Returning None, but including the path in `files`, is
2542 # necessary for memctx to register a deletion.
2543 # necessary for memctx to register a deletion.
2543 return None
2544 return None
2544
2545
2545 if branch is None:
2546 if branch is None:
2546 branch = self._wrappedctx.branch()
2547 branch = self._wrappedctx.branch()
2547
2548
2548 return memctx(
2549 return memctx(
2549 self._repo,
2550 self._repo,
2550 parents,
2551 parents,
2551 text,
2552 text,
2552 files,
2553 files,
2553 getfile,
2554 getfile,
2554 date=date,
2555 date=date,
2555 extra=extra,
2556 extra=extra,
2556 user=user,
2557 user=user,
2557 branch=branch,
2558 branch=branch,
2558 editor=editor,
2559 editor=editor,
2559 )
2560 )
2560
2561
2561 def tomemctx_for_amend(self, precursor):
2562 def tomemctx_for_amend(self, precursor):
2562 extra = precursor.extra().copy()
2563 extra = precursor.extra().copy()
2563 extra[b'amend_source'] = precursor.hex()
2564 extra[b'amend_source'] = precursor.hex()
2564 return self.tomemctx(
2565 return self.tomemctx(
2565 text=precursor.description(),
2566 text=precursor.description(),
2566 branch=precursor.branch(),
2567 branch=precursor.branch(),
2567 extra=extra,
2568 extra=extra,
2568 date=precursor.date(),
2569 date=precursor.date(),
2569 user=precursor.user(),
2570 user=precursor.user(),
2570 )
2571 )
2571
2572
2572 def isdirty(self, path):
2573 def isdirty(self, path):
2573 return path in self._cache
2574 return path in self._cache
2574
2575
2575 def clean(self):
2576 def clean(self):
2576 self._mergestate = None
2577 self._mergestate = None
2577 self._cache = {}
2578 self._cache = {}
2578
2579
2579 def _compact(self):
2580 def _compact(self):
2580 """Removes keys from the cache that are actually clean, by comparing
2581 """Removes keys from the cache that are actually clean, by comparing
2581 them with the underlying context.
2582 them with the underlying context.
2582
2583
2583 This can occur during the merge process, e.g. by passing --tool :local
2584 This can occur during the merge process, e.g. by passing --tool :local
2584 to resolve a conflict.
2585 to resolve a conflict.
2585 """
2586 """
2586 keys = []
2587 keys = []
2587 # This won't be perfect, but can help performance significantly when
2588 # This won't be perfect, but can help performance significantly when
2588 # using things like remotefilelog.
2589 # using things like remotefilelog.
2589 scmutil.prefetchfiles(
2590 scmutil.prefetchfiles(
2590 self.repo(),
2591 self.repo(),
2591 [
2592 [
2592 (
2593 (
2593 self.p1().rev(),
2594 self.p1().rev(),
2594 scmutil.matchfiles(self.repo(), self._cache.keys()),
2595 scmutil.matchfiles(self.repo(), self._cache.keys()),
2595 )
2596 )
2596 ],
2597 ],
2597 )
2598 )
2598
2599
2599 for path in self._cache.keys():
2600 for path in self._cache.keys():
2600 cache = self._cache[path]
2601 cache = self._cache[path]
2601 try:
2602 try:
2602 underlying = self._wrappedctx[path]
2603 underlying = self._wrappedctx[path]
2603 if (
2604 if (
2604 underlying.data() == cache[b'data']
2605 underlying.data() == cache[b'data']
2605 and underlying.flags() == cache[b'flags']
2606 and underlying.flags() == cache[b'flags']
2606 ):
2607 ):
2607 keys.append(path)
2608 keys.append(path)
2608 except error.ManifestLookupError:
2609 except error.ManifestLookupError:
2609 # Path not in the underlying manifest (created).
2610 # Path not in the underlying manifest (created).
2610 continue
2611 continue
2611
2612
2612 for path in keys:
2613 for path in keys:
2613 del self._cache[path]
2614 del self._cache[path]
2614 return keys
2615 return keys
2615
2616
2616 def _markdirty(
2617 def _markdirty(
2617 self, path, exists, data=None, date=None, flags=b'', copied=None
2618 self, path, exists, data=None, date=None, flags=b'', copied=None
2618 ):
2619 ):
2619 # data not provided, let's see if we already have some; if not, let's
2620 # data not provided, let's see if we already have some; if not, let's
2620 # grab it from our underlying context, so that we always have data if
2621 # grab it from our underlying context, so that we always have data if
2621 # the file is marked as existing.
2622 # the file is marked as existing.
2622 if exists and data is None:
2623 if exists and data is None:
2623 oldentry = self._cache.get(path) or {}
2624 oldentry = self._cache.get(path) or {}
2624 data = oldentry.get(b'data')
2625 data = oldentry.get(b'data')
2625 if data is None:
2626 if data is None:
2626 data = self._wrappedctx[path].data()
2627 data = self._wrappedctx[path].data()
2627
2628
2628 self._cache[path] = {
2629 self._cache[path] = {
2629 b'exists': exists,
2630 b'exists': exists,
2630 b'data': data,
2631 b'data': data,
2631 b'date': date,
2632 b'date': date,
2632 b'flags': flags,
2633 b'flags': flags,
2633 b'copied': copied,
2634 b'copied': copied,
2634 }
2635 }
2635 util.clearcachedproperty(self, b'_manifest')
2636 util.clearcachedproperty(self, b'_manifest')
2636
2637
2637 def filectx(self, path, filelog=None):
2638 def filectx(self, path, filelog=None):
2638 return overlayworkingfilectx(
2639 return overlayworkingfilectx(
2639 self._repo, path, parent=self, filelog=filelog
2640 self._repo, path, parent=self, filelog=filelog
2640 )
2641 )
2641
2642
2642 def mergestate(self, clean=False):
2643 def mergestate(self, clean=False):
2643 if clean or self._mergestate is None:
2644 if clean or self._mergestate is None:
2644 self._mergestate = mergestatemod.memmergestate(self._repo)
2645 self._mergestate = mergestatemod.memmergestate(self._repo)
2645 return self._mergestate
2646 return self._mergestate
2646
2647
2647
2648
2648 class overlayworkingfilectx(committablefilectx):
2649 class overlayworkingfilectx(committablefilectx):
2649 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2650 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2650 cache, which can be flushed through later by calling ``flush()``."""
2651 cache, which can be flushed through later by calling ``flush()``."""
2651
2652
2652 def __init__(self, repo, path, filelog=None, parent=None):
2653 def __init__(self, repo, path, filelog=None, parent=None):
2653 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2654 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2654 self._repo = repo
2655 self._repo = repo
2655 self._parent = parent
2656 self._parent = parent
2656 self._path = path
2657 self._path = path
2657
2658
2658 def cmp(self, fctx):
2659 def cmp(self, fctx):
2659 return self.data() != fctx.data()
2660 return self.data() != fctx.data()
2660
2661
2661 def changectx(self):
2662 def changectx(self):
2662 return self._parent
2663 return self._parent
2663
2664
2664 def data(self):
2665 def data(self):
2665 return self._parent.data(self._path)
2666 return self._parent.data(self._path)
2666
2667
2667 def date(self):
2668 def date(self):
2668 return self._parent.filedate(self._path)
2669 return self._parent.filedate(self._path)
2669
2670
2670 def exists(self):
2671 def exists(self):
2671 return self.lexists()
2672 return self.lexists()
2672
2673
2673 def lexists(self):
2674 def lexists(self):
2674 return self._parent.exists(self._path)
2675 return self._parent.exists(self._path)
2675
2676
2676 def copysource(self):
2677 def copysource(self):
2677 return self._parent.copydata(self._path)
2678 return self._parent.copydata(self._path)
2678
2679
2679 def size(self):
2680 def size(self):
2680 return self._parent.size(self._path)
2681 return self._parent.size(self._path)
2681
2682
2682 def markcopied(self, origin):
2683 def markcopied(self, origin):
2683 self._parent.markcopied(self._path, origin)
2684 self._parent.markcopied(self._path, origin)
2684
2685
2685 def audit(self):
2686 def audit(self):
2686 pass
2687 pass
2687
2688
2688 def flags(self):
2689 def flags(self):
2689 return self._parent.flags(self._path)
2690 return self._parent.flags(self._path)
2690
2691
2691 def setflags(self, islink, isexec):
2692 def setflags(self, islink, isexec):
2692 return self._parent.setflags(self._path, islink, isexec)
2693 return self._parent.setflags(self._path, islink, isexec)
2693
2694
2694 def write(self, data, flags, backgroundclose=False, **kwargs):
2695 def write(self, data, flags, backgroundclose=False, **kwargs):
2695 return self._parent.write(self._path, data, flags, **kwargs)
2696 return self._parent.write(self._path, data, flags, **kwargs)
2696
2697
2697 def remove(self, ignoremissing=False):
2698 def remove(self, ignoremissing=False):
2698 return self._parent.remove(self._path)
2699 return self._parent.remove(self._path)
2699
2700
2700 def clearunknown(self):
2701 def clearunknown(self):
2701 pass
2702 pass
2702
2703
2703
2704
2704 class workingcommitctx(workingctx):
2705 class workingcommitctx(workingctx):
2705 """A workingcommitctx object makes access to data related to
2706 """A workingcommitctx object makes access to data related to
2706 the revision being committed convenient.
2707 the revision being committed convenient.
2707
2708
2708 This hides changes in the working directory, if they aren't
2709 This hides changes in the working directory, if they aren't
2709 committed in this context.
2710 committed in this context.
2710 """
2711 """
2711
2712
2712 def __init__(
2713 def __init__(
2713 self, repo, changes, text=b"", user=None, date=None, extra=None
2714 self, repo, changes, text=b"", user=None, date=None, extra=None
2714 ):
2715 ):
2715 super(workingcommitctx, self).__init__(
2716 super(workingcommitctx, self).__init__(
2716 repo, text, user, date, extra, changes
2717 repo, text, user, date, extra, changes
2717 )
2718 )
2718
2719
2719 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2720 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2720 """Return matched files only in ``self._status``
2721 """Return matched files only in ``self._status``
2721
2722
2722 Uncommitted files appear "clean" via this context, even if
2723 Uncommitted files appear "clean" via this context, even if
2723 they aren't actually so in the working directory.
2724 they aren't actually so in the working directory.
2724 """
2725 """
2725 if clean:
2726 if clean:
2726 clean = [f for f in self._manifest if f not in self._changedset]
2727 clean = [f for f in self._manifest if f not in self._changedset]
2727 else:
2728 else:
2728 clean = []
2729 clean = []
2729 return scmutil.status(
2730 return scmutil.status(
2730 [f for f in self._status.modified if match(f)],
2731 [f for f in self._status.modified if match(f)],
2731 [f for f in self._status.added if match(f)],
2732 [f for f in self._status.added if match(f)],
2732 [f for f in self._status.removed if match(f)],
2733 [f for f in self._status.removed if match(f)],
2733 [],
2734 [],
2734 [],
2735 [],
2735 [],
2736 [],
2736 clean,
2737 clean,
2737 )
2738 )
2738
2739
2739 @propertycache
2740 @propertycache
2740 def _changedset(self):
2741 def _changedset(self):
2741 """Return the set of files changed in this context"""
2742 """Return the set of files changed in this context"""
2742 changed = set(self._status.modified)
2743 changed = set(self._status.modified)
2743 changed.update(self._status.added)
2744 changed.update(self._status.added)
2744 changed.update(self._status.removed)
2745 changed.update(self._status.removed)
2745 return changed
2746 return changed
2746
2747
2747
2748
2748 def makecachingfilectxfn(func):
2749 def makecachingfilectxfn(func):
2749 """Create a filectxfn that caches based on the path.
2750 """Create a filectxfn that caches based on the path.
2750
2751
2751 We can't use util.cachefunc because it uses all arguments as the cache
2752 We can't use util.cachefunc because it uses all arguments as the cache
2752 key and this creates a cycle since the arguments include the repo and
2753 key and this creates a cycle since the arguments include the repo and
2753 memctx.
2754 memctx.
2754 """
2755 """
2755 cache = {}
2756 cache = {}
2756
2757
2757 def getfilectx(repo, memctx, path):
2758 def getfilectx(repo, memctx, path):
2758 if path not in cache:
2759 if path not in cache:
2759 cache[path] = func(repo, memctx, path)
2760 cache[path] = func(repo, memctx, path)
2760 return cache[path]
2761 return cache[path]
2761
2762
2762 return getfilectx
2763 return getfilectx
2763
2764
2764
2765
2765 def memfilefromctx(ctx):
2766 def memfilefromctx(ctx):
2766 """Given a context return a memfilectx for ctx[path]
2767 """Given a context return a memfilectx for ctx[path]
2767
2768
2768 This is a convenience method for building a memctx based on another
2769 This is a convenience method for building a memctx based on another
2769 context.
2770 context.
2770 """
2771 """
2771
2772
2772 def getfilectx(repo, memctx, path):
2773 def getfilectx(repo, memctx, path):
2773 fctx = ctx[path]
2774 fctx = ctx[path]
2774 copysource = fctx.copysource()
2775 copysource = fctx.copysource()
2775 return memfilectx(
2776 return memfilectx(
2776 repo,
2777 repo,
2777 memctx,
2778 memctx,
2778 path,
2779 path,
2779 fctx.data(),
2780 fctx.data(),
2780 islink=fctx.islink(),
2781 islink=fctx.islink(),
2781 isexec=fctx.isexec(),
2782 isexec=fctx.isexec(),
2782 copysource=copysource,
2783 copysource=copysource,
2783 )
2784 )
2784
2785
2785 return getfilectx
2786 return getfilectx
2786
2787
2787
2788
2788 def memfilefrompatch(patchstore):
2789 def memfilefrompatch(patchstore):
2789 """Given a patch (e.g. patchstore object) return a memfilectx
2790 """Given a patch (e.g. patchstore object) return a memfilectx
2790
2791
2791 This is a convenience method for building a memctx based on a patchstore.
2792 This is a convenience method for building a memctx based on a patchstore.
2792 """
2793 """
2793
2794
2794 def getfilectx(repo, memctx, path):
2795 def getfilectx(repo, memctx, path):
2795 data, mode, copysource = patchstore.getfile(path)
2796 data, mode, copysource = patchstore.getfile(path)
2796 if data is None:
2797 if data is None:
2797 return None
2798 return None
2798 islink, isexec = mode
2799 islink, isexec = mode
2799 return memfilectx(
2800 return memfilectx(
2800 repo,
2801 repo,
2801 memctx,
2802 memctx,
2802 path,
2803 path,
2803 data,
2804 data,
2804 islink=islink,
2805 islink=islink,
2805 isexec=isexec,
2806 isexec=isexec,
2806 copysource=copysource,
2807 copysource=copysource,
2807 )
2808 )
2808
2809
2809 return getfilectx
2810 return getfilectx
2810
2811
2811
2812
2812 class memctx(committablectx):
2813 class memctx(committablectx):
2813 """Use memctx to perform in-memory commits via localrepo.commitctx().
2814 """Use memctx to perform in-memory commits via localrepo.commitctx().
2814
2815
2815 Revision information is supplied at initialization time while
2816 Revision information is supplied at initialization time while
2816 related files data and is made available through a callback
2817 related files data and is made available through a callback
2817 mechanism. 'repo' is the current localrepo, 'parents' is a
2818 mechanism. 'repo' is the current localrepo, 'parents' is a
2818 sequence of two parent revisions identifiers (pass None for every
2819 sequence of two parent revisions identifiers (pass None for every
2819 missing parent), 'text' is the commit message and 'files' lists
2820 missing parent), 'text' is the commit message and 'files' lists
2820 names of files touched by the revision (normalized and relative to
2821 names of files touched by the revision (normalized and relative to
2821 repository root).
2822 repository root).
2822
2823
2823 filectxfn(repo, memctx, path) is a callable receiving the
2824 filectxfn(repo, memctx, path) is a callable receiving the
2824 repository, the current memctx object and the normalized path of
2825 repository, the current memctx object and the normalized path of
2825 requested file, relative to repository root. It is fired by the
2826 requested file, relative to repository root. It is fired by the
2826 commit function for every file in 'files', but calls order is
2827 commit function for every file in 'files', but calls order is
2827 undefined. If the file is available in the revision being
2828 undefined. If the file is available in the revision being
2828 committed (updated or added), filectxfn returns a memfilectx
2829 committed (updated or added), filectxfn returns a memfilectx
2829 object. If the file was removed, filectxfn return None for recent
2830 object. If the file was removed, filectxfn return None for recent
2830 Mercurial. Moved files are represented by marking the source file
2831 Mercurial. Moved files are represented by marking the source file
2831 removed and the new file added with copy information (see
2832 removed and the new file added with copy information (see
2832 memfilectx).
2833 memfilectx).
2833
2834
2834 user receives the committer name and defaults to current
2835 user receives the committer name and defaults to current
2835 repository username, date is the commit date in any format
2836 repository username, date is the commit date in any format
2836 supported by dateutil.parsedate() and defaults to current date, extra
2837 supported by dateutil.parsedate() and defaults to current date, extra
2837 is a dictionary of metadata or is left empty.
2838 is a dictionary of metadata or is left empty.
2838 """
2839 """
2839
2840
2840 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2841 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2841 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2842 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2842 # this field to determine what to do in filectxfn.
2843 # this field to determine what to do in filectxfn.
2843 _returnnoneformissingfiles = True
2844 _returnnoneformissingfiles = True
2844
2845
2845 def __init__(
2846 def __init__(
2846 self,
2847 self,
2847 repo,
2848 repo,
2848 parents,
2849 parents,
2849 text,
2850 text,
2850 files,
2851 files,
2851 filectxfn,
2852 filectxfn,
2852 user=None,
2853 user=None,
2853 date=None,
2854 date=None,
2854 extra=None,
2855 extra=None,
2855 branch=None,
2856 branch=None,
2856 editor=None,
2857 editor=None,
2857 ):
2858 ):
2858 super(memctx, self).__init__(
2859 super(memctx, self).__init__(
2859 repo, text, user, date, extra, branch=branch
2860 repo, text, user, date, extra, branch=branch
2860 )
2861 )
2861 self._rev = None
2862 self._rev = None
2862 self._node = None
2863 self._node = None
2863 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2864 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2864 p1, p2 = parents
2865 p1, p2 = parents
2865 self._parents = [self._repo[p] for p in (p1, p2)]
2866 self._parents = [self._repo[p] for p in (p1, p2)]
2866 files = sorted(set(files))
2867 files = sorted(set(files))
2867 self._files = files
2868 self._files = files
2868 self.substate = {}
2869 self.substate = {}
2869
2870
2870 if isinstance(filectxfn, patch.filestore):
2871 if isinstance(filectxfn, patch.filestore):
2871 filectxfn = memfilefrompatch(filectxfn)
2872 filectxfn = memfilefrompatch(filectxfn)
2872 elif not callable(filectxfn):
2873 elif not callable(filectxfn):
2873 # if store is not callable, wrap it in a function
2874 # if store is not callable, wrap it in a function
2874 filectxfn = memfilefromctx(filectxfn)
2875 filectxfn = memfilefromctx(filectxfn)
2875
2876
2876 # memoizing increases performance for e.g. vcs convert scenarios.
2877 # memoizing increases performance for e.g. vcs convert scenarios.
2877 self._filectxfn = makecachingfilectxfn(filectxfn)
2878 self._filectxfn = makecachingfilectxfn(filectxfn)
2878
2879
2879 if editor:
2880 if editor:
2880 self._text = editor(self._repo, self, [])
2881 self._text = editor(self._repo, self, [])
2881 self._repo.savecommitmessage(self._text)
2882 self._repo.savecommitmessage(self._text)
2882
2883
2883 def filectx(self, path, filelog=None):
2884 def filectx(self, path, filelog=None):
2884 """get a file context from the working directory
2885 """get a file context from the working directory
2885
2886
2886 Returns None if file doesn't exist and should be removed."""
2887 Returns None if file doesn't exist and should be removed."""
2887 return self._filectxfn(self._repo, self, path)
2888 return self._filectxfn(self._repo, self, path)
2888
2889
2889 def commit(self):
2890 def commit(self):
2890 """commit context to the repo"""
2891 """commit context to the repo"""
2891 return self._repo.commitctx(self)
2892 return self._repo.commitctx(self)
2892
2893
2893 @propertycache
2894 @propertycache
2894 def _manifest(self):
2895 def _manifest(self):
2895 """generate a manifest based on the return values of filectxfn"""
2896 """generate a manifest based on the return values of filectxfn"""
2896
2897
2897 # keep this simple for now; just worry about p1
2898 # keep this simple for now; just worry about p1
2898 pctx = self._parents[0]
2899 pctx = self._parents[0]
2899 man = pctx.manifest().copy()
2900 man = pctx.manifest().copy()
2900
2901
2901 for f in self._status.modified:
2902 for f in self._status.modified:
2902 man[f] = self._repo.nodeconstants.modifiednodeid
2903 man[f] = self._repo.nodeconstants.modifiednodeid
2903
2904
2904 for f in self._status.added:
2905 for f in self._status.added:
2905 man[f] = self._repo.nodeconstants.addednodeid
2906 man[f] = self._repo.nodeconstants.addednodeid
2906
2907
2907 for f in self._status.removed:
2908 for f in self._status.removed:
2908 if f in man:
2909 if f in man:
2909 del man[f]
2910 del man[f]
2910
2911
2911 return man
2912 return man
2912
2913
2913 @propertycache
2914 @propertycache
2914 def _status(self):
2915 def _status(self):
2915 """Calculate exact status from ``files`` specified at construction"""
2916 """Calculate exact status from ``files`` specified at construction"""
2916 man1 = self.p1().manifest()
2917 man1 = self.p1().manifest()
2917 p2 = self._parents[1]
2918 p2 = self._parents[1]
2918 # "1 < len(self._parents)" can't be used for checking
2919 # "1 < len(self._parents)" can't be used for checking
2919 # existence of the 2nd parent, because "memctx._parents" is
2920 # existence of the 2nd parent, because "memctx._parents" is
2920 # explicitly initialized by the list, of which length is 2.
2921 # explicitly initialized by the list, of which length is 2.
2921 if p2.rev() != nullrev:
2922 if p2.rev() != nullrev:
2922 man2 = p2.manifest()
2923 man2 = p2.manifest()
2923 managing = lambda f: f in man1 or f in man2
2924 managing = lambda f: f in man1 or f in man2
2924 else:
2925 else:
2925 managing = lambda f: f in man1
2926 managing = lambda f: f in man1
2926
2927
2927 modified, added, removed = [], [], []
2928 modified, added, removed = [], [], []
2928 for f in self._files:
2929 for f in self._files:
2929 if not managing(f):
2930 if not managing(f):
2930 added.append(f)
2931 added.append(f)
2931 elif self[f]:
2932 elif self[f]:
2932 modified.append(f)
2933 modified.append(f)
2933 else:
2934 else:
2934 removed.append(f)
2935 removed.append(f)
2935
2936
2936 return scmutil.status(modified, added, removed, [], [], [], [])
2937 return scmutil.status(modified, added, removed, [], [], [], [])
2937
2938
2938 def parents(self):
2939 def parents(self):
2939 if self._parents[1].rev() == nullrev:
2940 if self._parents[1].rev() == nullrev:
2940 return [self._parents[0]]
2941 return [self._parents[0]]
2941 return self._parents
2942 return self._parents
2942
2943
2943
2944
2944 class memfilectx(committablefilectx):
2945 class memfilectx(committablefilectx):
2945 """memfilectx represents an in-memory file to commit.
2946 """memfilectx represents an in-memory file to commit.
2946
2947
2947 See memctx and committablefilectx for more details.
2948 See memctx and committablefilectx for more details.
2948 """
2949 """
2949
2950
2950 def __init__(
2951 def __init__(
2951 self,
2952 self,
2952 repo,
2953 repo,
2953 changectx,
2954 changectx,
2954 path,
2955 path,
2955 data,
2956 data,
2956 islink=False,
2957 islink=False,
2957 isexec=False,
2958 isexec=False,
2958 copysource=None,
2959 copysource=None,
2959 ):
2960 ):
2960 """
2961 """
2961 path is the normalized file path relative to repository root.
2962 path is the normalized file path relative to repository root.
2962 data is the file content as a string.
2963 data is the file content as a string.
2963 islink is True if the file is a symbolic link.
2964 islink is True if the file is a symbolic link.
2964 isexec is True if the file is executable.
2965 isexec is True if the file is executable.
2965 copied is the source file path if current file was copied in the
2966 copied is the source file path if current file was copied in the
2966 revision being committed, or None."""
2967 revision being committed, or None."""
2967 super(memfilectx, self).__init__(repo, path, None, changectx)
2968 super(memfilectx, self).__init__(repo, path, None, changectx)
2968 self._data = data
2969 self._data = data
2969 if islink:
2970 if islink:
2970 self._flags = b'l'
2971 self._flags = b'l'
2971 elif isexec:
2972 elif isexec:
2972 self._flags = b'x'
2973 self._flags = b'x'
2973 else:
2974 else:
2974 self._flags = b''
2975 self._flags = b''
2975 self._copysource = copysource
2976 self._copysource = copysource
2976
2977
2977 def copysource(self):
2978 def copysource(self):
2978 return self._copysource
2979 return self._copysource
2979
2980
2980 def cmp(self, fctx):
2981 def cmp(self, fctx):
2981 return self.data() != fctx.data()
2982 return self.data() != fctx.data()
2982
2983
2983 def data(self):
2984 def data(self):
2984 return self._data
2985 return self._data
2985
2986
2986 def remove(self, ignoremissing=False):
2987 def remove(self, ignoremissing=False):
2987 """wraps unlink for a repo's working directory"""
2988 """wraps unlink for a repo's working directory"""
2988 # need to figure out what to do here
2989 # need to figure out what to do here
2989 del self._changectx[self._path]
2990 del self._changectx[self._path]
2990
2991
2991 def write(self, data, flags, **kwargs):
2992 def write(self, data, flags, **kwargs):
2992 """wraps repo.wwrite"""
2993 """wraps repo.wwrite"""
2993 self._data = data
2994 self._data = data
2994
2995
2995
2996
2996 class metadataonlyctx(committablectx):
2997 class metadataonlyctx(committablectx):
2997 """Like memctx but it's reusing the manifest of different commit.
2998 """Like memctx but it's reusing the manifest of different commit.
2998 Intended to be used by lightweight operations that are creating
2999 Intended to be used by lightweight operations that are creating
2999 metadata-only changes.
3000 metadata-only changes.
3000
3001
3001 Revision information is supplied at initialization time. 'repo' is the
3002 Revision information is supplied at initialization time. 'repo' is the
3002 current localrepo, 'ctx' is original revision which manifest we're reuisng
3003 current localrepo, 'ctx' is original revision which manifest we're reuisng
3003 'parents' is a sequence of two parent revisions identifiers (pass None for
3004 'parents' is a sequence of two parent revisions identifiers (pass None for
3004 every missing parent), 'text' is the commit.
3005 every missing parent), 'text' is the commit.
3005
3006
3006 user receives the committer name and defaults to current repository
3007 user receives the committer name and defaults to current repository
3007 username, date is the commit date in any format supported by
3008 username, date is the commit date in any format supported by
3008 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3009 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3009 metadata or is left empty.
3010 metadata or is left empty.
3010 """
3011 """
3011
3012
3012 def __init__(
3013 def __init__(
3013 self,
3014 self,
3014 repo,
3015 repo,
3015 originalctx,
3016 originalctx,
3016 parents=None,
3017 parents=None,
3017 text=None,
3018 text=None,
3018 user=None,
3019 user=None,
3019 date=None,
3020 date=None,
3020 extra=None,
3021 extra=None,
3021 editor=None,
3022 editor=None,
3022 ):
3023 ):
3023 if text is None:
3024 if text is None:
3024 text = originalctx.description()
3025 text = originalctx.description()
3025 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3026 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3026 self._rev = None
3027 self._rev = None
3027 self._node = None
3028 self._node = None
3028 self._originalctx = originalctx
3029 self._originalctx = originalctx
3029 self._manifestnode = originalctx.manifestnode()
3030 self._manifestnode = originalctx.manifestnode()
3030 if parents is None:
3031 if parents is None:
3031 parents = originalctx.parents()
3032 parents = originalctx.parents()
3032 else:
3033 else:
3033 parents = [repo[p] for p in parents if p is not None]
3034 parents = [repo[p] for p in parents if p is not None]
3034 parents = parents[:]
3035 parents = parents[:]
3035 while len(parents) < 2:
3036 while len(parents) < 2:
3036 parents.append(repo[nullrev])
3037 parents.append(repo[nullrev])
3037 p1, p2 = self._parents = parents
3038 p1, p2 = self._parents = parents
3038
3039
3039 # sanity check to ensure that the reused manifest parents are
3040 # sanity check to ensure that the reused manifest parents are
3040 # manifests of our commit parents
3041 # manifests of our commit parents
3041 mp1, mp2 = self.manifestctx().parents
3042 mp1, mp2 = self.manifestctx().parents
3042 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3043 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3043 raise RuntimeError(
3044 raise RuntimeError(
3044 r"can't reuse the manifest: its p1 "
3045 r"can't reuse the manifest: its p1 "
3045 r"doesn't match the new ctx p1"
3046 r"doesn't match the new ctx p1"
3046 )
3047 )
3047 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3048 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3048 raise RuntimeError(
3049 raise RuntimeError(
3049 r"can't reuse the manifest: "
3050 r"can't reuse the manifest: "
3050 r"its p2 doesn't match the new ctx p2"
3051 r"its p2 doesn't match the new ctx p2"
3051 )
3052 )
3052
3053
3053 self._files = originalctx.files()
3054 self._files = originalctx.files()
3054 self.substate = {}
3055 self.substate = {}
3055
3056
3056 if editor:
3057 if editor:
3057 self._text = editor(self._repo, self, [])
3058 self._text = editor(self._repo, self, [])
3058 self._repo.savecommitmessage(self._text)
3059 self._repo.savecommitmessage(self._text)
3059
3060
3060 def manifestnode(self):
3061 def manifestnode(self):
3061 return self._manifestnode
3062 return self._manifestnode
3062
3063
3063 @property
3064 @property
3064 def _manifestctx(self):
3065 def _manifestctx(self):
3065 return self._repo.manifestlog[self._manifestnode]
3066 return self._repo.manifestlog[self._manifestnode]
3066
3067
3067 def filectx(self, path, filelog=None):
3068 def filectx(self, path, filelog=None):
3068 return self._originalctx.filectx(path, filelog=filelog)
3069 return self._originalctx.filectx(path, filelog=filelog)
3069
3070
3070 def commit(self):
3071 def commit(self):
3071 """commit context to the repo"""
3072 """commit context to the repo"""
3072 return self._repo.commitctx(self)
3073 return self._repo.commitctx(self)
3073
3074
3074 @property
3075 @property
3075 def _manifest(self):
3076 def _manifest(self):
3076 return self._originalctx.manifest()
3077 return self._originalctx.manifest()
3077
3078
3078 @propertycache
3079 @propertycache
3079 def _status(self):
3080 def _status(self):
3080 """Calculate exact status from ``files`` specified in the ``origctx``
3081 """Calculate exact status from ``files`` specified in the ``origctx``
3081 and parents manifests.
3082 and parents manifests.
3082 """
3083 """
3083 man1 = self.p1().manifest()
3084 man1 = self.p1().manifest()
3084 p2 = self._parents[1]
3085 p2 = self._parents[1]
3085 # "1 < len(self._parents)" can't be used for checking
3086 # "1 < len(self._parents)" can't be used for checking
3086 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3087 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3087 # explicitly initialized by the list, of which length is 2.
3088 # explicitly initialized by the list, of which length is 2.
3088 if p2.rev() != nullrev:
3089 if p2.rev() != nullrev:
3089 man2 = p2.manifest()
3090 man2 = p2.manifest()
3090 managing = lambda f: f in man1 or f in man2
3091 managing = lambda f: f in man1 or f in man2
3091 else:
3092 else:
3092 managing = lambda f: f in man1
3093 managing = lambda f: f in man1
3093
3094
3094 modified, added, removed = [], [], []
3095 modified, added, removed = [], [], []
3095 for f in self._files:
3096 for f in self._files:
3096 if not managing(f):
3097 if not managing(f):
3097 added.append(f)
3098 added.append(f)
3098 elif f in self:
3099 elif f in self:
3099 modified.append(f)
3100 modified.append(f)
3100 else:
3101 else:
3101 removed.append(f)
3102 removed.append(f)
3102
3103
3103 return scmutil.status(modified, added, removed, [], [], [], [])
3104 return scmutil.status(modified, added, removed, [], [], [], [])
3104
3105
3105
3106
3106 class arbitraryfilectx:
3107 class arbitraryfilectx:
3107 """Allows you to use filectx-like functions on a file in an arbitrary
3108 """Allows you to use filectx-like functions on a file in an arbitrary
3108 location on disk, possibly not in the working directory.
3109 location on disk, possibly not in the working directory.
3109 """
3110 """
3110
3111
3111 def __init__(self, path, repo=None):
3112 def __init__(self, path, repo=None):
3112 # Repo is optional because contrib/simplemerge uses this class.
3113 # Repo is optional because contrib/simplemerge uses this class.
3113 self._repo = repo
3114 self._repo = repo
3114 self._path = path
3115 self._path = path
3115
3116
3116 def cmp(self, fctx):
3117 def cmp(self, fctx):
3117 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3118 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3118 # path if either side is a symlink.
3119 # path if either side is a symlink.
3119 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3120 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3120 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3121 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3121 # Add a fast-path for merge if both sides are disk-backed.
3122 # Add a fast-path for merge if both sides are disk-backed.
3122 # Note that filecmp uses the opposite return values (True if same)
3123 # Note that filecmp uses the opposite return values (True if same)
3123 # from our cmp functions (True if different).
3124 # from our cmp functions (True if different).
3124 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3125 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3125 return self.data() != fctx.data()
3126 return self.data() != fctx.data()
3126
3127
3127 def path(self):
3128 def path(self):
3128 return self._path
3129 return self._path
3129
3130
3130 def flags(self):
3131 def flags(self):
3131 return b''
3132 return b''
3132
3133
3133 def data(self):
3134 def data(self):
3134 return util.readfile(self._path)
3135 return util.readfile(self._path)
3135
3136
3136 def decodeddata(self):
3137 def decodeddata(self):
3137 return util.readfile(self._path)
3138 return util.readfile(self._path)
3138
3139
3139 def remove(self):
3140 def remove(self):
3140 util.unlink(self._path)
3141 util.unlink(self._path)
3141
3142
3142 def write(self, data, flags, **kwargs):
3143 def write(self, data, flags, **kwargs):
3143 assert not flags
3144 assert not flags
3144 util.writefile(self._path, data)
3145 util.writefile(self._path, data)
General Comments 0
You need to be logged in to leave comments. Login now