##// END OF EJS Templates
status: simplify the post status fixup phases...
marmoute -
r51025:9e1debbb default
parent child Browse files
Show More
@@ -1,3155 +1,3144 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 poststatus = self._repo.postdsstatus()
1858 poststatus = self._repo.postdsstatus()
1858 if fixup or poststatus or self._repo.dirstate._dirty:
1859 if fixup:
1860 if dirstate.is_changing_parents:
1861 normal = lambda f, pfd: dirstate.update_file(
1862 f,
1863 p1_tracked=True,
1864 wc_tracked=True,
1865 )
1866 else:
1867 normal = dirstate.set_clean
1868 for f, pdf in fixup:
1869 normal(f, pdf)
1870 if poststatus or self._repo.dirstate._dirty:
1859 try:
1871 try:
1860 oldid = self._repo.dirstate.identity()
1861
1862 # updating the dirstate is optional
1872 # updating the dirstate is optional
1863 # so we don't wait on the lock
1873 # so we don't wait on the lock
1864 # wlock can invalidate the dirstate, so cache normal _after_
1874 # wlock can invalidate the dirstate, so cache normal _after_
1865 # taking the lock
1875 # taking the lock
1876 pre_dirty = dirstate._dirty
1866 with self._repo.wlock(False):
1877 with self._repo.wlock(False):
1867 dirstate = self._repo.dirstate
1878 assert self._repo.dirstate is dirstate
1868 if dirstate.identity() == oldid:
1879 post_dirty = dirstate._dirty
1869 if fixup:
1880 if post_dirty:
1870 if dirstate.is_changing_parents:
1871 normal = lambda f, pfd: dirstate.update_file(
1872 f, p1_tracked=True, wc_tracked=True
1873 )
1874 else:
1875 normal = dirstate.set_clean
1876 for f, pdf in fixup:
1877 normal(f, pdf)
1878 # write changes out explicitly, because nesting
1879 # wlock at runtime may prevent 'wlock.release()'
1880 # after this block from doing so for subsequent
1881 # changing files
1882 #
1883 # (This is outside of the (if fixup) block because the
1884 # status operation itself might have updated some cache
1885 # information before.)
1886 tr = self._repo.currenttransaction()
1881 tr = self._repo.currenttransaction()
1887 self._repo.dirstate.write(tr)
1882 dirstate.write(tr)
1888
1883 elif pre_dirty:
1889 if poststatus:
1884 # the wlock grabbing detected that dirtate changes
1890 for ps in poststatus:
1885 # needed to be dropped
1891 ps(self, status)
1886 m = b'skip updating dirstate: identity mismatch\n'
1892 else:
1887 self._repo.ui.debug(m)
1893 # in this case, writing changes out breaks
1888 if poststatus:
1894 # consistency, because .hg/dirstate was
1889 for ps in poststatus:
1895 # already changed simultaneously after last
1890 ps(self, status)
1896 # caching (see also issue5584 for detail)
1897 self._repo.ui.debug(
1898 b'skip updating dirstate: identity mismatch\n'
1899 )
1900 # throw away anything we have.
1901 dirstate.invalidate()
1902 except error.LockError:
1891 except error.LockError:
1903 pass
1892 pass
1904 finally:
1893 finally:
1905 # 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.
1906 self._repo.clearpostdsstatus()
1895 self._repo.clearpostdsstatus()
1907
1896
1908 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1897 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1909 '''Gets the status from the dirstate -- internal use only.'''
1898 '''Gets the status from the dirstate -- internal use only.'''
1910 subrepos = []
1899 subrepos = []
1911 if b'.hgsub' in self:
1900 if b'.hgsub' in self:
1912 subrepos = sorted(self.substate)
1901 subrepos = sorted(self.substate)
1913 cmp, s, mtime_boundary = self._repo.dirstate.status(
1902 cmp, s, mtime_boundary = self._repo.dirstate.status(
1914 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1903 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1915 )
1904 )
1916
1905
1917 # check for any possibly clean files
1906 # check for any possibly clean files
1918 fixup = []
1907 fixup = []
1919 if cmp:
1908 if cmp:
1920 modified2, deleted2, clean_set, fixup = self._checklookup(
1909 modified2, deleted2, clean_set, fixup = self._checklookup(
1921 cmp, mtime_boundary
1910 cmp, mtime_boundary
1922 )
1911 )
1923 s.modified.extend(modified2)
1912 s.modified.extend(modified2)
1924 s.deleted.extend(deleted2)
1913 s.deleted.extend(deleted2)
1925
1914
1926 if clean_set and clean:
1915 if clean_set and clean:
1927 s.clean.extend(clean_set)
1916 s.clean.extend(clean_set)
1928 if fixup and clean:
1917 if fixup and clean:
1929 s.clean.extend((f for f, _ in fixup))
1918 s.clean.extend((f for f, _ in fixup))
1930
1919
1931 self._poststatusfixup(s, fixup)
1920 self._poststatusfixup(s, fixup)
1932
1921
1933 if match.always():
1922 if match.always():
1934 # cache for performance
1923 # cache for performance
1935 if s.unknown or s.ignored or s.clean:
1924 if s.unknown or s.ignored or s.clean:
1936 # "_status" is cached with list*=False in the normal route
1925 # "_status" is cached with list*=False in the normal route
1937 self._status = scmutil.status(
1926 self._status = scmutil.status(
1938 s.modified, s.added, s.removed, s.deleted, [], [], []
1927 s.modified, s.added, s.removed, s.deleted, [], [], []
1939 )
1928 )
1940 else:
1929 else:
1941 self._status = s
1930 self._status = s
1942
1931
1943 return s
1932 return s
1944
1933
1945 @propertycache
1934 @propertycache
1946 def _copies(self):
1935 def _copies(self):
1947 p1copies = {}
1936 p1copies = {}
1948 p2copies = {}
1937 p2copies = {}
1949 parents = self._repo.dirstate.parents()
1938 parents = self._repo.dirstate.parents()
1950 p1manifest = self._repo[parents[0]].manifest()
1939 p1manifest = self._repo[parents[0]].manifest()
1951 p2manifest = self._repo[parents[1]].manifest()
1940 p2manifest = self._repo[parents[1]].manifest()
1952 changedset = set(self.added()) | set(self.modified())
1941 changedset = set(self.added()) | set(self.modified())
1953 narrowmatch = self._repo.narrowmatch()
1942 narrowmatch = self._repo.narrowmatch()
1954 for dst, src in self._repo.dirstate.copies().items():
1943 for dst, src in self._repo.dirstate.copies().items():
1955 if dst not in changedset or not narrowmatch(dst):
1944 if dst not in changedset or not narrowmatch(dst):
1956 continue
1945 continue
1957 if src in p1manifest:
1946 if src in p1manifest:
1958 p1copies[dst] = src
1947 p1copies[dst] = src
1959 elif src in p2manifest:
1948 elif src in p2manifest:
1960 p2copies[dst] = src
1949 p2copies[dst] = src
1961 return p1copies, p2copies
1950 return p1copies, p2copies
1962
1951
1963 @propertycache
1952 @propertycache
1964 def _manifest(self):
1953 def _manifest(self):
1965 """generate a manifest corresponding to the values in self._status
1954 """generate a manifest corresponding to the values in self._status
1966
1955
1967 This reuse the file nodeid from parent, but we use special node
1956 This reuse the file nodeid from parent, but we use special node
1968 identifiers for added and modified files. This is used by manifests
1957 identifiers for added and modified files. This is used by manifests
1969 merge to see that files are different and by update logic to avoid
1958 merge to see that files are different and by update logic to avoid
1970 deleting newly added files.
1959 deleting newly added files.
1971 """
1960 """
1972 return self._buildstatusmanifest(self._status)
1961 return self._buildstatusmanifest(self._status)
1973
1962
1974 def _buildstatusmanifest(self, status):
1963 def _buildstatusmanifest(self, status):
1975 """Builds a manifest that includes the given status results."""
1964 """Builds a manifest that includes the given status results."""
1976 parents = self.parents()
1965 parents = self.parents()
1977
1966
1978 man = parents[0].manifest().copy()
1967 man = parents[0].manifest().copy()
1979
1968
1980 ff = self._flagfunc
1969 ff = self._flagfunc
1981 for i, l in (
1970 for i, l in (
1982 (self._repo.nodeconstants.addednodeid, status.added),
1971 (self._repo.nodeconstants.addednodeid, status.added),
1983 (self._repo.nodeconstants.modifiednodeid, status.modified),
1972 (self._repo.nodeconstants.modifiednodeid, status.modified),
1984 ):
1973 ):
1985 for f in l:
1974 for f in l:
1986 man[f] = i
1975 man[f] = i
1987 try:
1976 try:
1988 man.setflag(f, ff(f))
1977 man.setflag(f, ff(f))
1989 except OSError:
1978 except OSError:
1990 pass
1979 pass
1991
1980
1992 for f in status.deleted + status.removed:
1981 for f in status.deleted + status.removed:
1993 if f in man:
1982 if f in man:
1994 del man[f]
1983 del man[f]
1995
1984
1996 return man
1985 return man
1997
1986
1998 def _buildstatus(
1987 def _buildstatus(
1999 self, other, s, match, listignored, listclean, listunknown
1988 self, other, s, match, listignored, listclean, listunknown
2000 ):
1989 ):
2001 """build a status with respect to another context
1990 """build a status with respect to another context
2002
1991
2003 This includes logic for maintaining the fast path of status when
1992 This includes logic for maintaining the fast path of status when
2004 comparing the working directory against its parent, which is to skip
1993 comparing the working directory against its parent, which is to skip
2005 building a new manifest if self (working directory) is not comparing
1994 building a new manifest if self (working directory) is not comparing
2006 against its parent (repo['.']).
1995 against its parent (repo['.']).
2007 """
1996 """
2008 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1997 s = self._dirstatestatus(match, listignored, listclean, listunknown)
2009 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1998 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
2010 # might have accidentally ended up with the entire contents of the file
1999 # might have accidentally ended up with the entire contents of the file
2011 # they are supposed to be linking to.
2000 # they are supposed to be linking to.
2012 s.modified[:] = self._filtersuspectsymlink(s.modified)
2001 s.modified[:] = self._filtersuspectsymlink(s.modified)
2013 if other != self._repo[b'.']:
2002 if other != self._repo[b'.']:
2014 s = super(workingctx, self)._buildstatus(
2003 s = super(workingctx, self)._buildstatus(
2015 other, s, match, listignored, listclean, listunknown
2004 other, s, match, listignored, listclean, listunknown
2016 )
2005 )
2017 return s
2006 return s
2018
2007
2019 def _matchstatus(self, other, match):
2008 def _matchstatus(self, other, match):
2020 """override the match method with a filter for directory patterns
2009 """override the match method with a filter for directory patterns
2021
2010
2022 We use inheritance to customize the match.bad method only in cases of
2011 We use inheritance to customize the match.bad method only in cases of
2023 workingctx since it belongs only to the working directory when
2012 workingctx since it belongs only to the working directory when
2024 comparing against the parent changeset.
2013 comparing against the parent changeset.
2025
2014
2026 If we aren't comparing against the working directory's parent, then we
2015 If we aren't comparing against the working directory's parent, then we
2027 just use the default match object sent to us.
2016 just use the default match object sent to us.
2028 """
2017 """
2029 if other != self._repo[b'.']:
2018 if other != self._repo[b'.']:
2030
2019
2031 def bad(f, msg):
2020 def bad(f, msg):
2032 # 'f' may be a directory pattern from 'match.files()',
2021 # 'f' may be a directory pattern from 'match.files()',
2033 # so 'f not in ctx1' is not enough
2022 # so 'f not in ctx1' is not enough
2034 if f not in other and not other.hasdir(f):
2023 if f not in other and not other.hasdir(f):
2035 self._repo.ui.warn(
2024 self._repo.ui.warn(
2036 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2025 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2037 )
2026 )
2038
2027
2039 match.bad = bad
2028 match.bad = bad
2040 return match
2029 return match
2041
2030
2042 def walk(self, match):
2031 def walk(self, match):
2043 '''Generates matching file names.'''
2032 '''Generates matching file names.'''
2044 return sorted(
2033 return sorted(
2045 self._repo.dirstate.walk(
2034 self._repo.dirstate.walk(
2046 self._repo.narrowmatch(match),
2035 self._repo.narrowmatch(match),
2047 subrepos=sorted(self.substate),
2036 subrepos=sorted(self.substate),
2048 unknown=True,
2037 unknown=True,
2049 ignored=False,
2038 ignored=False,
2050 )
2039 )
2051 )
2040 )
2052
2041
2053 def matches(self, match):
2042 def matches(self, match):
2054 match = self._repo.narrowmatch(match)
2043 match = self._repo.narrowmatch(match)
2055 ds = self._repo.dirstate
2044 ds = self._repo.dirstate
2056 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2045 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2057
2046
2058 def markcommitted(self, node):
2047 def markcommitted(self, node):
2059 with self._repo.dirstate.changing_parents(self._repo):
2048 with self._repo.dirstate.changing_parents(self._repo):
2060 for f in self.modified() + self.added():
2049 for f in self.modified() + self.added():
2061 self._repo.dirstate.update_file(
2050 self._repo.dirstate.update_file(
2062 f, p1_tracked=True, wc_tracked=True
2051 f, p1_tracked=True, wc_tracked=True
2063 )
2052 )
2064 for f in self.removed():
2053 for f in self.removed():
2065 self._repo.dirstate.update_file(
2054 self._repo.dirstate.update_file(
2066 f, p1_tracked=False, wc_tracked=False
2055 f, p1_tracked=False, wc_tracked=False
2067 )
2056 )
2068 self._repo.dirstate.setparents(node)
2057 self._repo.dirstate.setparents(node)
2069 self._repo._quick_access_changeid_invalidate()
2058 self._repo._quick_access_changeid_invalidate()
2070
2059
2071 sparse.aftercommit(self._repo, node)
2060 sparse.aftercommit(self._repo, node)
2072
2061
2073 # write changes out explicitly, because nesting wlock at
2062 # write changes out explicitly, because nesting wlock at
2074 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2063 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2075 # from immediately doing so for subsequent changing files
2064 # from immediately doing so for subsequent changing files
2076 self._repo.dirstate.write(self._repo.currenttransaction())
2065 self._repo.dirstate.write(self._repo.currenttransaction())
2077
2066
2078 def mergestate(self, clean=False):
2067 def mergestate(self, clean=False):
2079 if clean:
2068 if clean:
2080 return mergestatemod.mergestate.clean(self._repo)
2069 return mergestatemod.mergestate.clean(self._repo)
2081 return mergestatemod.mergestate.read(self._repo)
2070 return mergestatemod.mergestate.read(self._repo)
2082
2071
2083
2072
2084 class committablefilectx(basefilectx):
2073 class committablefilectx(basefilectx):
2085 """A committablefilectx provides common functionality for a file context
2074 """A committablefilectx provides common functionality for a file context
2086 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2075 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2087
2076
2088 def __init__(self, repo, path, filelog=None, ctx=None):
2077 def __init__(self, repo, path, filelog=None, ctx=None):
2089 self._repo = repo
2078 self._repo = repo
2090 self._path = path
2079 self._path = path
2091 self._changeid = None
2080 self._changeid = None
2092 self._filerev = self._filenode = None
2081 self._filerev = self._filenode = None
2093
2082
2094 if filelog is not None:
2083 if filelog is not None:
2095 self._filelog = filelog
2084 self._filelog = filelog
2096 if ctx:
2085 if ctx:
2097 self._changectx = ctx
2086 self._changectx = ctx
2098
2087
2099 def __nonzero__(self):
2088 def __nonzero__(self):
2100 return True
2089 return True
2101
2090
2102 __bool__ = __nonzero__
2091 __bool__ = __nonzero__
2103
2092
2104 def linkrev(self):
2093 def linkrev(self):
2105 # linked to self._changectx no matter if file is modified or not
2094 # linked to self._changectx no matter if file is modified or not
2106 return self.rev()
2095 return self.rev()
2107
2096
2108 def renamed(self):
2097 def renamed(self):
2109 path = self.copysource()
2098 path = self.copysource()
2110 if not path:
2099 if not path:
2111 return None
2100 return None
2112 return (
2101 return (
2113 path,
2102 path,
2114 self._changectx._parents[0]._manifest.get(
2103 self._changectx._parents[0]._manifest.get(
2115 path, self._repo.nodeconstants.nullid
2104 path, self._repo.nodeconstants.nullid
2116 ),
2105 ),
2117 )
2106 )
2118
2107
2119 def parents(self):
2108 def parents(self):
2120 '''return parent filectxs, following copies if necessary'''
2109 '''return parent filectxs, following copies if necessary'''
2121
2110
2122 def filenode(ctx, path):
2111 def filenode(ctx, path):
2123 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2112 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2124
2113
2125 path = self._path
2114 path = self._path
2126 fl = self._filelog
2115 fl = self._filelog
2127 pcl = self._changectx._parents
2116 pcl = self._changectx._parents
2128 renamed = self.renamed()
2117 renamed = self.renamed()
2129
2118
2130 if renamed:
2119 if renamed:
2131 pl = [renamed + (None,)]
2120 pl = [renamed + (None,)]
2132 else:
2121 else:
2133 pl = [(path, filenode(pcl[0], path), fl)]
2122 pl = [(path, filenode(pcl[0], path), fl)]
2134
2123
2135 for pc in pcl[1:]:
2124 for pc in pcl[1:]:
2136 pl.append((path, filenode(pc, path), fl))
2125 pl.append((path, filenode(pc, path), fl))
2137
2126
2138 return [
2127 return [
2139 self._parentfilectx(p, fileid=n, filelog=l)
2128 self._parentfilectx(p, fileid=n, filelog=l)
2140 for p, n, l in pl
2129 for p, n, l in pl
2141 if n != self._repo.nodeconstants.nullid
2130 if n != self._repo.nodeconstants.nullid
2142 ]
2131 ]
2143
2132
2144 def children(self):
2133 def children(self):
2145 return []
2134 return []
2146
2135
2147
2136
2148 class workingfilectx(committablefilectx):
2137 class workingfilectx(committablefilectx):
2149 """A workingfilectx object makes access to data related to a particular
2138 """A workingfilectx object makes access to data related to a particular
2150 file in the working directory convenient."""
2139 file in the working directory convenient."""
2151
2140
2152 def __init__(self, repo, path, filelog=None, workingctx=None):
2141 def __init__(self, repo, path, filelog=None, workingctx=None):
2153 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2142 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2154
2143
2155 @propertycache
2144 @propertycache
2156 def _changectx(self):
2145 def _changectx(self):
2157 return workingctx(self._repo)
2146 return workingctx(self._repo)
2158
2147
2159 def data(self):
2148 def data(self):
2160 return self._repo.wread(self._path)
2149 return self._repo.wread(self._path)
2161
2150
2162 def copysource(self):
2151 def copysource(self):
2163 return self._repo.dirstate.copied(self._path)
2152 return self._repo.dirstate.copied(self._path)
2164
2153
2165 def size(self):
2154 def size(self):
2166 return self._repo.wvfs.lstat(self._path).st_size
2155 return self._repo.wvfs.lstat(self._path).st_size
2167
2156
2168 def lstat(self):
2157 def lstat(self):
2169 return self._repo.wvfs.lstat(self._path)
2158 return self._repo.wvfs.lstat(self._path)
2170
2159
2171 def date(self):
2160 def date(self):
2172 t, tz = self._changectx.date()
2161 t, tz = self._changectx.date()
2173 try:
2162 try:
2174 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2163 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2175 except FileNotFoundError:
2164 except FileNotFoundError:
2176 return (t, tz)
2165 return (t, tz)
2177
2166
2178 def exists(self):
2167 def exists(self):
2179 return self._repo.wvfs.exists(self._path)
2168 return self._repo.wvfs.exists(self._path)
2180
2169
2181 def lexists(self):
2170 def lexists(self):
2182 return self._repo.wvfs.lexists(self._path)
2171 return self._repo.wvfs.lexists(self._path)
2183
2172
2184 def audit(self):
2173 def audit(self):
2185 return self._repo.wvfs.audit(self._path)
2174 return self._repo.wvfs.audit(self._path)
2186
2175
2187 def cmp(self, fctx):
2176 def cmp(self, fctx):
2188 """compare with other file context
2177 """compare with other file context
2189
2178
2190 returns True if different than fctx.
2179 returns True if different than fctx.
2191 """
2180 """
2192 # fctx should be a filectx (not a workingfilectx)
2181 # fctx should be a filectx (not a workingfilectx)
2193 # invert comparison to reuse the same code path
2182 # invert comparison to reuse the same code path
2194 return fctx.cmp(self)
2183 return fctx.cmp(self)
2195
2184
2196 def remove(self, ignoremissing=False):
2185 def remove(self, ignoremissing=False):
2197 """wraps unlink for a repo's working directory"""
2186 """wraps unlink for a repo's working directory"""
2198 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2187 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2199 self._repo.wvfs.unlinkpath(
2188 self._repo.wvfs.unlinkpath(
2200 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2189 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2201 )
2190 )
2202
2191
2203 def write(self, data, flags, backgroundclose=False, **kwargs):
2192 def write(self, data, flags, backgroundclose=False, **kwargs):
2204 """wraps repo.wwrite"""
2193 """wraps repo.wwrite"""
2205 return self._repo.wwrite(
2194 return self._repo.wwrite(
2206 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2195 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2207 )
2196 )
2208
2197
2209 def markcopied(self, src):
2198 def markcopied(self, src):
2210 """marks this file a copy of `src`"""
2199 """marks this file a copy of `src`"""
2211 self._repo.dirstate.copy(src, self._path)
2200 self._repo.dirstate.copy(src, self._path)
2212
2201
2213 def clearunknown(self):
2202 def clearunknown(self):
2214 """Removes conflicting items in the working directory so that
2203 """Removes conflicting items in the working directory so that
2215 ``write()`` can be called successfully.
2204 ``write()`` can be called successfully.
2216 """
2205 """
2217 wvfs = self._repo.wvfs
2206 wvfs = self._repo.wvfs
2218 f = self._path
2207 f = self._path
2219 wvfs.audit(f)
2208 wvfs.audit(f)
2220 if self._repo.ui.configbool(
2209 if self._repo.ui.configbool(
2221 b'experimental', b'merge.checkpathconflicts'
2210 b'experimental', b'merge.checkpathconflicts'
2222 ):
2211 ):
2223 # remove files under the directory as they should already be
2212 # remove files under the directory as they should already be
2224 # warned and backed up
2213 # warned and backed up
2225 if wvfs.isdir(f) and not wvfs.islink(f):
2214 if wvfs.isdir(f) and not wvfs.islink(f):
2226 wvfs.rmtree(f, forcibly=True)
2215 wvfs.rmtree(f, forcibly=True)
2227 for p in reversed(list(pathutil.finddirs(f))):
2216 for p in reversed(list(pathutil.finddirs(f))):
2228 if wvfs.isfileorlink(p):
2217 if wvfs.isfileorlink(p):
2229 wvfs.unlink(p)
2218 wvfs.unlink(p)
2230 break
2219 break
2231 else:
2220 else:
2232 # don't remove files if path conflicts are not processed
2221 # don't remove files if path conflicts are not processed
2233 if wvfs.isdir(f) and not wvfs.islink(f):
2222 if wvfs.isdir(f) and not wvfs.islink(f):
2234 wvfs.removedirs(f)
2223 wvfs.removedirs(f)
2235
2224
2236 def setflags(self, l, x):
2225 def setflags(self, l, x):
2237 self._repo.wvfs.setflags(self._path, l, x)
2226 self._repo.wvfs.setflags(self._path, l, x)
2238
2227
2239
2228
2240 class overlayworkingctx(committablectx):
2229 class overlayworkingctx(committablectx):
2241 """Wraps another mutable context with a write-back cache that can be
2230 """Wraps another mutable context with a write-back cache that can be
2242 converted into a commit context.
2231 converted into a commit context.
2243
2232
2244 self._cache[path] maps to a dict with keys: {
2233 self._cache[path] maps to a dict with keys: {
2245 'exists': bool?
2234 'exists': bool?
2246 'date': date?
2235 'date': date?
2247 'data': str?
2236 'data': str?
2248 'flags': str?
2237 'flags': str?
2249 'copied': str? (path or None)
2238 'copied': str? (path or None)
2250 }
2239 }
2251 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2240 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2252 is `False`, the file was deleted.
2241 is `False`, the file was deleted.
2253 """
2242 """
2254
2243
2255 def __init__(self, repo):
2244 def __init__(self, repo):
2256 super(overlayworkingctx, self).__init__(repo)
2245 super(overlayworkingctx, self).__init__(repo)
2257 self.clean()
2246 self.clean()
2258
2247
2259 def setbase(self, wrappedctx):
2248 def setbase(self, wrappedctx):
2260 self._wrappedctx = wrappedctx
2249 self._wrappedctx = wrappedctx
2261 self._parents = [wrappedctx]
2250 self._parents = [wrappedctx]
2262 # Drop old manifest cache as it is now out of date.
2251 # Drop old manifest cache as it is now out of date.
2263 # This is necessary when, e.g., rebasing several nodes with one
2252 # This is necessary when, e.g., rebasing several nodes with one
2264 # ``overlayworkingctx`` (e.g. with --collapse).
2253 # ``overlayworkingctx`` (e.g. with --collapse).
2265 util.clearcachedproperty(self, b'_manifest')
2254 util.clearcachedproperty(self, b'_manifest')
2266
2255
2267 def setparents(self, p1node, p2node=None):
2256 def setparents(self, p1node, p2node=None):
2268 if p2node is None:
2257 if p2node is None:
2269 p2node = self._repo.nodeconstants.nullid
2258 p2node = self._repo.nodeconstants.nullid
2270 assert p1node == self._wrappedctx.node()
2259 assert p1node == self._wrappedctx.node()
2271 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2260 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2272
2261
2273 def data(self, path):
2262 def data(self, path):
2274 if self.isdirty(path):
2263 if self.isdirty(path):
2275 if self._cache[path][b'exists']:
2264 if self._cache[path][b'exists']:
2276 if self._cache[path][b'data'] is not None:
2265 if self._cache[path][b'data'] is not None:
2277 return self._cache[path][b'data']
2266 return self._cache[path][b'data']
2278 else:
2267 else:
2279 # Must fallback here, too, because we only set flags.
2268 # Must fallback here, too, because we only set flags.
2280 return self._wrappedctx[path].data()
2269 return self._wrappedctx[path].data()
2281 else:
2270 else:
2282 raise error.ProgrammingError(
2271 raise error.ProgrammingError(
2283 b"No such file or directory: %s" % path
2272 b"No such file or directory: %s" % path
2284 )
2273 )
2285 else:
2274 else:
2286 return self._wrappedctx[path].data()
2275 return self._wrappedctx[path].data()
2287
2276
2288 @propertycache
2277 @propertycache
2289 def _manifest(self):
2278 def _manifest(self):
2290 parents = self.parents()
2279 parents = self.parents()
2291 man = parents[0].manifest().copy()
2280 man = parents[0].manifest().copy()
2292
2281
2293 flag = self._flagfunc
2282 flag = self._flagfunc
2294 for path in self.added():
2283 for path in self.added():
2295 man[path] = self._repo.nodeconstants.addednodeid
2284 man[path] = self._repo.nodeconstants.addednodeid
2296 man.setflag(path, flag(path))
2285 man.setflag(path, flag(path))
2297 for path in self.modified():
2286 for path in self.modified():
2298 man[path] = self._repo.nodeconstants.modifiednodeid
2287 man[path] = self._repo.nodeconstants.modifiednodeid
2299 man.setflag(path, flag(path))
2288 man.setflag(path, flag(path))
2300 for path in self.removed():
2289 for path in self.removed():
2301 del man[path]
2290 del man[path]
2302 return man
2291 return man
2303
2292
2304 @propertycache
2293 @propertycache
2305 def _flagfunc(self):
2294 def _flagfunc(self):
2306 def f(path):
2295 def f(path):
2307 return self._cache[path][b'flags']
2296 return self._cache[path][b'flags']
2308
2297
2309 return f
2298 return f
2310
2299
2311 def files(self):
2300 def files(self):
2312 return sorted(self.added() + self.modified() + self.removed())
2301 return sorted(self.added() + self.modified() + self.removed())
2313
2302
2314 def modified(self):
2303 def modified(self):
2315 return [
2304 return [
2316 f
2305 f
2317 for f in self._cache.keys()
2306 for f in self._cache.keys()
2318 if self._cache[f][b'exists'] and self._existsinparent(f)
2307 if self._cache[f][b'exists'] and self._existsinparent(f)
2319 ]
2308 ]
2320
2309
2321 def added(self):
2310 def added(self):
2322 return [
2311 return [
2323 f
2312 f
2324 for f in self._cache.keys()
2313 for f in self._cache.keys()
2325 if self._cache[f][b'exists'] and not self._existsinparent(f)
2314 if self._cache[f][b'exists'] and not self._existsinparent(f)
2326 ]
2315 ]
2327
2316
2328 def removed(self):
2317 def removed(self):
2329 return [
2318 return [
2330 f
2319 f
2331 for f in self._cache.keys()
2320 for f in self._cache.keys()
2332 if not self._cache[f][b'exists'] and self._existsinparent(f)
2321 if not self._cache[f][b'exists'] and self._existsinparent(f)
2333 ]
2322 ]
2334
2323
2335 def p1copies(self):
2324 def p1copies(self):
2336 copies = {}
2325 copies = {}
2337 narrowmatch = self._repo.narrowmatch()
2326 narrowmatch = self._repo.narrowmatch()
2338 for f in self._cache.keys():
2327 for f in self._cache.keys():
2339 if not narrowmatch(f):
2328 if not narrowmatch(f):
2340 continue
2329 continue
2341 copies.pop(f, None) # delete if it exists
2330 copies.pop(f, None) # delete if it exists
2342 source = self._cache[f][b'copied']
2331 source = self._cache[f][b'copied']
2343 if source:
2332 if source:
2344 copies[f] = source
2333 copies[f] = source
2345 return copies
2334 return copies
2346
2335
2347 def p2copies(self):
2336 def p2copies(self):
2348 copies = {}
2337 copies = {}
2349 narrowmatch = self._repo.narrowmatch()
2338 narrowmatch = self._repo.narrowmatch()
2350 for f in self._cache.keys():
2339 for f in self._cache.keys():
2351 if not narrowmatch(f):
2340 if not narrowmatch(f):
2352 continue
2341 continue
2353 copies.pop(f, None) # delete if it exists
2342 copies.pop(f, None) # delete if it exists
2354 source = self._cache[f][b'copied']
2343 source = self._cache[f][b'copied']
2355 if source:
2344 if source:
2356 copies[f] = source
2345 copies[f] = source
2357 return copies
2346 return copies
2358
2347
2359 def isinmemory(self):
2348 def isinmemory(self):
2360 return True
2349 return True
2361
2350
2362 def filedate(self, path):
2351 def filedate(self, path):
2363 if self.isdirty(path):
2352 if self.isdirty(path):
2364 return self._cache[path][b'date']
2353 return self._cache[path][b'date']
2365 else:
2354 else:
2366 return self._wrappedctx[path].date()
2355 return self._wrappedctx[path].date()
2367
2356
2368 def markcopied(self, path, origin):
2357 def markcopied(self, path, origin):
2369 self._markdirty(
2358 self._markdirty(
2370 path,
2359 path,
2371 exists=True,
2360 exists=True,
2372 date=self.filedate(path),
2361 date=self.filedate(path),
2373 flags=self.flags(path),
2362 flags=self.flags(path),
2374 copied=origin,
2363 copied=origin,
2375 )
2364 )
2376
2365
2377 def copydata(self, path):
2366 def copydata(self, path):
2378 if self.isdirty(path):
2367 if self.isdirty(path):
2379 return self._cache[path][b'copied']
2368 return self._cache[path][b'copied']
2380 else:
2369 else:
2381 return None
2370 return None
2382
2371
2383 def flags(self, path):
2372 def flags(self, path):
2384 if self.isdirty(path):
2373 if self.isdirty(path):
2385 if self._cache[path][b'exists']:
2374 if self._cache[path][b'exists']:
2386 return self._cache[path][b'flags']
2375 return self._cache[path][b'flags']
2387 else:
2376 else:
2388 raise error.ProgrammingError(
2377 raise error.ProgrammingError(
2389 b"No such file or directory: %s" % path
2378 b"No such file or directory: %s" % path
2390 )
2379 )
2391 else:
2380 else:
2392 return self._wrappedctx[path].flags()
2381 return self._wrappedctx[path].flags()
2393
2382
2394 def __contains__(self, key):
2383 def __contains__(self, key):
2395 if key in self._cache:
2384 if key in self._cache:
2396 return self._cache[key][b'exists']
2385 return self._cache[key][b'exists']
2397 return key in self.p1()
2386 return key in self.p1()
2398
2387
2399 def _existsinparent(self, path):
2388 def _existsinparent(self, path):
2400 try:
2389 try:
2401 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2390 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2402 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2391 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2403 # with an ``exists()`` function.
2392 # with an ``exists()`` function.
2404 self._wrappedctx[path]
2393 self._wrappedctx[path]
2405 return True
2394 return True
2406 except error.ManifestLookupError:
2395 except error.ManifestLookupError:
2407 return False
2396 return False
2408
2397
2409 def _auditconflicts(self, path):
2398 def _auditconflicts(self, path):
2410 """Replicates conflict checks done by wvfs.write().
2399 """Replicates conflict checks done by wvfs.write().
2411
2400
2412 Since we never write to the filesystem and never call `applyupdates` in
2401 Since we never write to the filesystem and never call `applyupdates` in
2413 IMM, we'll never check that a path is actually writable -- e.g., because
2402 IMM, we'll never check that a path is actually writable -- e.g., because
2414 it adds `a/foo`, but `a` is actually a file in the other commit.
2403 it adds `a/foo`, but `a` is actually a file in the other commit.
2415 """
2404 """
2416
2405
2417 def fail(path, component):
2406 def fail(path, component):
2418 # p1() is the base and we're receiving "writes" for p2()'s
2407 # p1() is the base and we're receiving "writes" for p2()'s
2419 # files.
2408 # files.
2420 if b'l' in self.p1()[component].flags():
2409 if b'l' in self.p1()[component].flags():
2421 raise error.Abort(
2410 raise error.Abort(
2422 b"error: %s conflicts with symlink %s "
2411 b"error: %s conflicts with symlink %s "
2423 b"in %d." % (path, component, self.p1().rev())
2412 b"in %d." % (path, component, self.p1().rev())
2424 )
2413 )
2425 else:
2414 else:
2426 raise error.Abort(
2415 raise error.Abort(
2427 b"error: '%s' conflicts with file '%s' in "
2416 b"error: '%s' conflicts with file '%s' in "
2428 b"%d." % (path, component, self.p1().rev())
2417 b"%d." % (path, component, self.p1().rev())
2429 )
2418 )
2430
2419
2431 # Test that each new directory to be created to write this path from p2
2420 # Test that each new directory to be created to write this path from p2
2432 # is not a file in p1.
2421 # is not a file in p1.
2433 components = path.split(b'/')
2422 components = path.split(b'/')
2434 for i in range(len(components)):
2423 for i in range(len(components)):
2435 component = b"/".join(components[0:i])
2424 component = b"/".join(components[0:i])
2436 if component in self:
2425 if component in self:
2437 fail(path, component)
2426 fail(path, component)
2438
2427
2439 # Test the other direction -- that this path from p2 isn't a directory
2428 # Test the other direction -- that this path from p2 isn't a directory
2440 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2429 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2441 match = self.match([path], default=b'path')
2430 match = self.match([path], default=b'path')
2442 mfiles = list(self.p1().manifest().walk(match))
2431 mfiles = list(self.p1().manifest().walk(match))
2443 if len(mfiles) > 0:
2432 if len(mfiles) > 0:
2444 if len(mfiles) == 1 and mfiles[0] == path:
2433 if len(mfiles) == 1 and mfiles[0] == path:
2445 return
2434 return
2446 # omit the files which are deleted in current IMM wctx
2435 # omit the files which are deleted in current IMM wctx
2447 mfiles = [m for m in mfiles if m in self]
2436 mfiles = [m for m in mfiles if m in self]
2448 if not mfiles:
2437 if not mfiles:
2449 return
2438 return
2450 raise error.Abort(
2439 raise error.Abort(
2451 b"error: file '%s' cannot be written because "
2440 b"error: file '%s' cannot be written because "
2452 b" '%s/' is a directory in %s (containing %d "
2441 b" '%s/' is a directory in %s (containing %d "
2453 b"entries: %s)"
2442 b"entries: %s)"
2454 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2443 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2455 )
2444 )
2456
2445
2457 def write(self, path, data, flags=b'', **kwargs):
2446 def write(self, path, data, flags=b'', **kwargs):
2458 if data is None:
2447 if data is None:
2459 raise error.ProgrammingError(b"data must be non-None")
2448 raise error.ProgrammingError(b"data must be non-None")
2460 self._auditconflicts(path)
2449 self._auditconflicts(path)
2461 self._markdirty(
2450 self._markdirty(
2462 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2451 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2463 )
2452 )
2464
2453
2465 def setflags(self, path, l, x):
2454 def setflags(self, path, l, x):
2466 flag = b''
2455 flag = b''
2467 if l:
2456 if l:
2468 flag = b'l'
2457 flag = b'l'
2469 elif x:
2458 elif x:
2470 flag = b'x'
2459 flag = b'x'
2471 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2460 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2472
2461
2473 def remove(self, path):
2462 def remove(self, path):
2474 self._markdirty(path, exists=False)
2463 self._markdirty(path, exists=False)
2475
2464
2476 def exists(self, path):
2465 def exists(self, path):
2477 """exists behaves like `lexists`, but needs to follow symlinks and
2466 """exists behaves like `lexists`, but needs to follow symlinks and
2478 return False if they are broken.
2467 return False if they are broken.
2479 """
2468 """
2480 if self.isdirty(path):
2469 if self.isdirty(path):
2481 # If this path exists and is a symlink, "follow" it by calling
2470 # If this path exists and is a symlink, "follow" it by calling
2482 # exists on the destination path.
2471 # exists on the destination path.
2483 if (
2472 if (
2484 self._cache[path][b'exists']
2473 self._cache[path][b'exists']
2485 and b'l' in self._cache[path][b'flags']
2474 and b'l' in self._cache[path][b'flags']
2486 ):
2475 ):
2487 return self.exists(self._cache[path][b'data'].strip())
2476 return self.exists(self._cache[path][b'data'].strip())
2488 else:
2477 else:
2489 return self._cache[path][b'exists']
2478 return self._cache[path][b'exists']
2490
2479
2491 return self._existsinparent(path)
2480 return self._existsinparent(path)
2492
2481
2493 def lexists(self, path):
2482 def lexists(self, path):
2494 """lexists returns True if the path exists"""
2483 """lexists returns True if the path exists"""
2495 if self.isdirty(path):
2484 if self.isdirty(path):
2496 return self._cache[path][b'exists']
2485 return self._cache[path][b'exists']
2497
2486
2498 return self._existsinparent(path)
2487 return self._existsinparent(path)
2499
2488
2500 def size(self, path):
2489 def size(self, path):
2501 if self.isdirty(path):
2490 if self.isdirty(path):
2502 if self._cache[path][b'exists']:
2491 if self._cache[path][b'exists']:
2503 return len(self._cache[path][b'data'])
2492 return len(self._cache[path][b'data'])
2504 else:
2493 else:
2505 raise error.ProgrammingError(
2494 raise error.ProgrammingError(
2506 b"No such file or directory: %s" % path
2495 b"No such file or directory: %s" % path
2507 )
2496 )
2508 return self._wrappedctx[path].size()
2497 return self._wrappedctx[path].size()
2509
2498
2510 def tomemctx(
2499 def tomemctx(
2511 self,
2500 self,
2512 text,
2501 text,
2513 branch=None,
2502 branch=None,
2514 extra=None,
2503 extra=None,
2515 date=None,
2504 date=None,
2516 parents=None,
2505 parents=None,
2517 user=None,
2506 user=None,
2518 editor=None,
2507 editor=None,
2519 ):
2508 ):
2520 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2509 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2521 committed.
2510 committed.
2522
2511
2523 ``text`` is the commit message.
2512 ``text`` is the commit message.
2524 ``parents`` (optional) are rev numbers.
2513 ``parents`` (optional) are rev numbers.
2525 """
2514 """
2526 # Default parents to the wrapped context if not passed.
2515 # Default parents to the wrapped context if not passed.
2527 if parents is None:
2516 if parents is None:
2528 parents = self.parents()
2517 parents = self.parents()
2529 if len(parents) == 1:
2518 if len(parents) == 1:
2530 parents = (parents[0], None)
2519 parents = (parents[0], None)
2531
2520
2532 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2521 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2533 if parents[1] is None:
2522 if parents[1] is None:
2534 parents = (self._repo[parents[0]], None)
2523 parents = (self._repo[parents[0]], None)
2535 else:
2524 else:
2536 parents = (self._repo[parents[0]], self._repo[parents[1]])
2525 parents = (self._repo[parents[0]], self._repo[parents[1]])
2537
2526
2538 files = self.files()
2527 files = self.files()
2539
2528
2540 def getfile(repo, memctx, path):
2529 def getfile(repo, memctx, path):
2541 if self._cache[path][b'exists']:
2530 if self._cache[path][b'exists']:
2542 return memfilectx(
2531 return memfilectx(
2543 repo,
2532 repo,
2544 memctx,
2533 memctx,
2545 path,
2534 path,
2546 self._cache[path][b'data'],
2535 self._cache[path][b'data'],
2547 b'l' in self._cache[path][b'flags'],
2536 b'l' in self._cache[path][b'flags'],
2548 b'x' in self._cache[path][b'flags'],
2537 b'x' in self._cache[path][b'flags'],
2549 self._cache[path][b'copied'],
2538 self._cache[path][b'copied'],
2550 )
2539 )
2551 else:
2540 else:
2552 # Returning None, but including the path in `files`, is
2541 # Returning None, but including the path in `files`, is
2553 # necessary for memctx to register a deletion.
2542 # necessary for memctx to register a deletion.
2554 return None
2543 return None
2555
2544
2556 if branch is None:
2545 if branch is None:
2557 branch = self._wrappedctx.branch()
2546 branch = self._wrappedctx.branch()
2558
2547
2559 return memctx(
2548 return memctx(
2560 self._repo,
2549 self._repo,
2561 parents,
2550 parents,
2562 text,
2551 text,
2563 files,
2552 files,
2564 getfile,
2553 getfile,
2565 date=date,
2554 date=date,
2566 extra=extra,
2555 extra=extra,
2567 user=user,
2556 user=user,
2568 branch=branch,
2557 branch=branch,
2569 editor=editor,
2558 editor=editor,
2570 )
2559 )
2571
2560
2572 def tomemctx_for_amend(self, precursor):
2561 def tomemctx_for_amend(self, precursor):
2573 extra = precursor.extra().copy()
2562 extra = precursor.extra().copy()
2574 extra[b'amend_source'] = precursor.hex()
2563 extra[b'amend_source'] = precursor.hex()
2575 return self.tomemctx(
2564 return self.tomemctx(
2576 text=precursor.description(),
2565 text=precursor.description(),
2577 branch=precursor.branch(),
2566 branch=precursor.branch(),
2578 extra=extra,
2567 extra=extra,
2579 date=precursor.date(),
2568 date=precursor.date(),
2580 user=precursor.user(),
2569 user=precursor.user(),
2581 )
2570 )
2582
2571
2583 def isdirty(self, path):
2572 def isdirty(self, path):
2584 return path in self._cache
2573 return path in self._cache
2585
2574
2586 def clean(self):
2575 def clean(self):
2587 self._mergestate = None
2576 self._mergestate = None
2588 self._cache = {}
2577 self._cache = {}
2589
2578
2590 def _compact(self):
2579 def _compact(self):
2591 """Removes keys from the cache that are actually clean, by comparing
2580 """Removes keys from the cache that are actually clean, by comparing
2592 them with the underlying context.
2581 them with the underlying context.
2593
2582
2594 This can occur during the merge process, e.g. by passing --tool :local
2583 This can occur during the merge process, e.g. by passing --tool :local
2595 to resolve a conflict.
2584 to resolve a conflict.
2596 """
2585 """
2597 keys = []
2586 keys = []
2598 # This won't be perfect, but can help performance significantly when
2587 # This won't be perfect, but can help performance significantly when
2599 # using things like remotefilelog.
2588 # using things like remotefilelog.
2600 scmutil.prefetchfiles(
2589 scmutil.prefetchfiles(
2601 self.repo(),
2590 self.repo(),
2602 [
2591 [
2603 (
2592 (
2604 self.p1().rev(),
2593 self.p1().rev(),
2605 scmutil.matchfiles(self.repo(), self._cache.keys()),
2594 scmutil.matchfiles(self.repo(), self._cache.keys()),
2606 )
2595 )
2607 ],
2596 ],
2608 )
2597 )
2609
2598
2610 for path in self._cache.keys():
2599 for path in self._cache.keys():
2611 cache = self._cache[path]
2600 cache = self._cache[path]
2612 try:
2601 try:
2613 underlying = self._wrappedctx[path]
2602 underlying = self._wrappedctx[path]
2614 if (
2603 if (
2615 underlying.data() == cache[b'data']
2604 underlying.data() == cache[b'data']
2616 and underlying.flags() == cache[b'flags']
2605 and underlying.flags() == cache[b'flags']
2617 ):
2606 ):
2618 keys.append(path)
2607 keys.append(path)
2619 except error.ManifestLookupError:
2608 except error.ManifestLookupError:
2620 # Path not in the underlying manifest (created).
2609 # Path not in the underlying manifest (created).
2621 continue
2610 continue
2622
2611
2623 for path in keys:
2612 for path in keys:
2624 del self._cache[path]
2613 del self._cache[path]
2625 return keys
2614 return keys
2626
2615
2627 def _markdirty(
2616 def _markdirty(
2628 self, path, exists, data=None, date=None, flags=b'', copied=None
2617 self, path, exists, data=None, date=None, flags=b'', copied=None
2629 ):
2618 ):
2630 # data not provided, let's see if we already have some; if not, let's
2619 # data not provided, let's see if we already have some; if not, let's
2631 # grab it from our underlying context, so that we always have data if
2620 # grab it from our underlying context, so that we always have data if
2632 # the file is marked as existing.
2621 # the file is marked as existing.
2633 if exists and data is None:
2622 if exists and data is None:
2634 oldentry = self._cache.get(path) or {}
2623 oldentry = self._cache.get(path) or {}
2635 data = oldentry.get(b'data')
2624 data = oldentry.get(b'data')
2636 if data is None:
2625 if data is None:
2637 data = self._wrappedctx[path].data()
2626 data = self._wrappedctx[path].data()
2638
2627
2639 self._cache[path] = {
2628 self._cache[path] = {
2640 b'exists': exists,
2629 b'exists': exists,
2641 b'data': data,
2630 b'data': data,
2642 b'date': date,
2631 b'date': date,
2643 b'flags': flags,
2632 b'flags': flags,
2644 b'copied': copied,
2633 b'copied': copied,
2645 }
2634 }
2646 util.clearcachedproperty(self, b'_manifest')
2635 util.clearcachedproperty(self, b'_manifest')
2647
2636
2648 def filectx(self, path, filelog=None):
2637 def filectx(self, path, filelog=None):
2649 return overlayworkingfilectx(
2638 return overlayworkingfilectx(
2650 self._repo, path, parent=self, filelog=filelog
2639 self._repo, path, parent=self, filelog=filelog
2651 )
2640 )
2652
2641
2653 def mergestate(self, clean=False):
2642 def mergestate(self, clean=False):
2654 if clean or self._mergestate is None:
2643 if clean or self._mergestate is None:
2655 self._mergestate = mergestatemod.memmergestate(self._repo)
2644 self._mergestate = mergestatemod.memmergestate(self._repo)
2656 return self._mergestate
2645 return self._mergestate
2657
2646
2658
2647
2659 class overlayworkingfilectx(committablefilectx):
2648 class overlayworkingfilectx(committablefilectx):
2660 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2649 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2661 cache, which can be flushed through later by calling ``flush()``."""
2650 cache, which can be flushed through later by calling ``flush()``."""
2662
2651
2663 def __init__(self, repo, path, filelog=None, parent=None):
2652 def __init__(self, repo, path, filelog=None, parent=None):
2664 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2653 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2665 self._repo = repo
2654 self._repo = repo
2666 self._parent = parent
2655 self._parent = parent
2667 self._path = path
2656 self._path = path
2668
2657
2669 def cmp(self, fctx):
2658 def cmp(self, fctx):
2670 return self.data() != fctx.data()
2659 return self.data() != fctx.data()
2671
2660
2672 def changectx(self):
2661 def changectx(self):
2673 return self._parent
2662 return self._parent
2674
2663
2675 def data(self):
2664 def data(self):
2676 return self._parent.data(self._path)
2665 return self._parent.data(self._path)
2677
2666
2678 def date(self):
2667 def date(self):
2679 return self._parent.filedate(self._path)
2668 return self._parent.filedate(self._path)
2680
2669
2681 def exists(self):
2670 def exists(self):
2682 return self.lexists()
2671 return self.lexists()
2683
2672
2684 def lexists(self):
2673 def lexists(self):
2685 return self._parent.exists(self._path)
2674 return self._parent.exists(self._path)
2686
2675
2687 def copysource(self):
2676 def copysource(self):
2688 return self._parent.copydata(self._path)
2677 return self._parent.copydata(self._path)
2689
2678
2690 def size(self):
2679 def size(self):
2691 return self._parent.size(self._path)
2680 return self._parent.size(self._path)
2692
2681
2693 def markcopied(self, origin):
2682 def markcopied(self, origin):
2694 self._parent.markcopied(self._path, origin)
2683 self._parent.markcopied(self._path, origin)
2695
2684
2696 def audit(self):
2685 def audit(self):
2697 pass
2686 pass
2698
2687
2699 def flags(self):
2688 def flags(self):
2700 return self._parent.flags(self._path)
2689 return self._parent.flags(self._path)
2701
2690
2702 def setflags(self, islink, isexec):
2691 def setflags(self, islink, isexec):
2703 return self._parent.setflags(self._path, islink, isexec)
2692 return self._parent.setflags(self._path, islink, isexec)
2704
2693
2705 def write(self, data, flags, backgroundclose=False, **kwargs):
2694 def write(self, data, flags, backgroundclose=False, **kwargs):
2706 return self._parent.write(self._path, data, flags, **kwargs)
2695 return self._parent.write(self._path, data, flags, **kwargs)
2707
2696
2708 def remove(self, ignoremissing=False):
2697 def remove(self, ignoremissing=False):
2709 return self._parent.remove(self._path)
2698 return self._parent.remove(self._path)
2710
2699
2711 def clearunknown(self):
2700 def clearunknown(self):
2712 pass
2701 pass
2713
2702
2714
2703
2715 class workingcommitctx(workingctx):
2704 class workingcommitctx(workingctx):
2716 """A workingcommitctx object makes access to data related to
2705 """A workingcommitctx object makes access to data related to
2717 the revision being committed convenient.
2706 the revision being committed convenient.
2718
2707
2719 This hides changes in the working directory, if they aren't
2708 This hides changes in the working directory, if they aren't
2720 committed in this context.
2709 committed in this context.
2721 """
2710 """
2722
2711
2723 def __init__(
2712 def __init__(
2724 self, repo, changes, text=b"", user=None, date=None, extra=None
2713 self, repo, changes, text=b"", user=None, date=None, extra=None
2725 ):
2714 ):
2726 super(workingcommitctx, self).__init__(
2715 super(workingcommitctx, self).__init__(
2727 repo, text, user, date, extra, changes
2716 repo, text, user, date, extra, changes
2728 )
2717 )
2729
2718
2730 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2719 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2731 """Return matched files only in ``self._status``
2720 """Return matched files only in ``self._status``
2732
2721
2733 Uncommitted files appear "clean" via this context, even if
2722 Uncommitted files appear "clean" via this context, even if
2734 they aren't actually so in the working directory.
2723 they aren't actually so in the working directory.
2735 """
2724 """
2736 if clean:
2725 if clean:
2737 clean = [f for f in self._manifest if f not in self._changedset]
2726 clean = [f for f in self._manifest if f not in self._changedset]
2738 else:
2727 else:
2739 clean = []
2728 clean = []
2740 return scmutil.status(
2729 return scmutil.status(
2741 [f for f in self._status.modified if match(f)],
2730 [f for f in self._status.modified if match(f)],
2742 [f for f in self._status.added if match(f)],
2731 [f for f in self._status.added if match(f)],
2743 [f for f in self._status.removed if match(f)],
2732 [f for f in self._status.removed if match(f)],
2744 [],
2733 [],
2745 [],
2734 [],
2746 [],
2735 [],
2747 clean,
2736 clean,
2748 )
2737 )
2749
2738
2750 @propertycache
2739 @propertycache
2751 def _changedset(self):
2740 def _changedset(self):
2752 """Return the set of files changed in this context"""
2741 """Return the set of files changed in this context"""
2753 changed = set(self._status.modified)
2742 changed = set(self._status.modified)
2754 changed.update(self._status.added)
2743 changed.update(self._status.added)
2755 changed.update(self._status.removed)
2744 changed.update(self._status.removed)
2756 return changed
2745 return changed
2757
2746
2758
2747
2759 def makecachingfilectxfn(func):
2748 def makecachingfilectxfn(func):
2760 """Create a filectxfn that caches based on the path.
2749 """Create a filectxfn that caches based on the path.
2761
2750
2762 We can't use util.cachefunc because it uses all arguments as the cache
2751 We can't use util.cachefunc because it uses all arguments as the cache
2763 key and this creates a cycle since the arguments include the repo and
2752 key and this creates a cycle since the arguments include the repo and
2764 memctx.
2753 memctx.
2765 """
2754 """
2766 cache = {}
2755 cache = {}
2767
2756
2768 def getfilectx(repo, memctx, path):
2757 def getfilectx(repo, memctx, path):
2769 if path not in cache:
2758 if path not in cache:
2770 cache[path] = func(repo, memctx, path)
2759 cache[path] = func(repo, memctx, path)
2771 return cache[path]
2760 return cache[path]
2772
2761
2773 return getfilectx
2762 return getfilectx
2774
2763
2775
2764
2776 def memfilefromctx(ctx):
2765 def memfilefromctx(ctx):
2777 """Given a context return a memfilectx for ctx[path]
2766 """Given a context return a memfilectx for ctx[path]
2778
2767
2779 This is a convenience method for building a memctx based on another
2768 This is a convenience method for building a memctx based on another
2780 context.
2769 context.
2781 """
2770 """
2782
2771
2783 def getfilectx(repo, memctx, path):
2772 def getfilectx(repo, memctx, path):
2784 fctx = ctx[path]
2773 fctx = ctx[path]
2785 copysource = fctx.copysource()
2774 copysource = fctx.copysource()
2786 return memfilectx(
2775 return memfilectx(
2787 repo,
2776 repo,
2788 memctx,
2777 memctx,
2789 path,
2778 path,
2790 fctx.data(),
2779 fctx.data(),
2791 islink=fctx.islink(),
2780 islink=fctx.islink(),
2792 isexec=fctx.isexec(),
2781 isexec=fctx.isexec(),
2793 copysource=copysource,
2782 copysource=copysource,
2794 )
2783 )
2795
2784
2796 return getfilectx
2785 return getfilectx
2797
2786
2798
2787
2799 def memfilefrompatch(patchstore):
2788 def memfilefrompatch(patchstore):
2800 """Given a patch (e.g. patchstore object) return a memfilectx
2789 """Given a patch (e.g. patchstore object) return a memfilectx
2801
2790
2802 This is a convenience method for building a memctx based on a patchstore.
2791 This is a convenience method for building a memctx based on a patchstore.
2803 """
2792 """
2804
2793
2805 def getfilectx(repo, memctx, path):
2794 def getfilectx(repo, memctx, path):
2806 data, mode, copysource = patchstore.getfile(path)
2795 data, mode, copysource = patchstore.getfile(path)
2807 if data is None:
2796 if data is None:
2808 return None
2797 return None
2809 islink, isexec = mode
2798 islink, isexec = mode
2810 return memfilectx(
2799 return memfilectx(
2811 repo,
2800 repo,
2812 memctx,
2801 memctx,
2813 path,
2802 path,
2814 data,
2803 data,
2815 islink=islink,
2804 islink=islink,
2816 isexec=isexec,
2805 isexec=isexec,
2817 copysource=copysource,
2806 copysource=copysource,
2818 )
2807 )
2819
2808
2820 return getfilectx
2809 return getfilectx
2821
2810
2822
2811
2823 class memctx(committablectx):
2812 class memctx(committablectx):
2824 """Use memctx to perform in-memory commits via localrepo.commitctx().
2813 """Use memctx to perform in-memory commits via localrepo.commitctx().
2825
2814
2826 Revision information is supplied at initialization time while
2815 Revision information is supplied at initialization time while
2827 related files data and is made available through a callback
2816 related files data and is made available through a callback
2828 mechanism. 'repo' is the current localrepo, 'parents' is a
2817 mechanism. 'repo' is the current localrepo, 'parents' is a
2829 sequence of two parent revisions identifiers (pass None for every
2818 sequence of two parent revisions identifiers (pass None for every
2830 missing parent), 'text' is the commit message and 'files' lists
2819 missing parent), 'text' is the commit message and 'files' lists
2831 names of files touched by the revision (normalized and relative to
2820 names of files touched by the revision (normalized and relative to
2832 repository root).
2821 repository root).
2833
2822
2834 filectxfn(repo, memctx, path) is a callable receiving the
2823 filectxfn(repo, memctx, path) is a callable receiving the
2835 repository, the current memctx object and the normalized path of
2824 repository, the current memctx object and the normalized path of
2836 requested file, relative to repository root. It is fired by the
2825 requested file, relative to repository root. It is fired by the
2837 commit function for every file in 'files', but calls order is
2826 commit function for every file in 'files', but calls order is
2838 undefined. If the file is available in the revision being
2827 undefined. If the file is available in the revision being
2839 committed (updated or added), filectxfn returns a memfilectx
2828 committed (updated or added), filectxfn returns a memfilectx
2840 object. If the file was removed, filectxfn return None for recent
2829 object. If the file was removed, filectxfn return None for recent
2841 Mercurial. Moved files are represented by marking the source file
2830 Mercurial. Moved files are represented by marking the source file
2842 removed and the new file added with copy information (see
2831 removed and the new file added with copy information (see
2843 memfilectx).
2832 memfilectx).
2844
2833
2845 user receives the committer name and defaults to current
2834 user receives the committer name and defaults to current
2846 repository username, date is the commit date in any format
2835 repository username, date is the commit date in any format
2847 supported by dateutil.parsedate() and defaults to current date, extra
2836 supported by dateutil.parsedate() and defaults to current date, extra
2848 is a dictionary of metadata or is left empty.
2837 is a dictionary of metadata or is left empty.
2849 """
2838 """
2850
2839
2851 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2840 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2852 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2841 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2853 # this field to determine what to do in filectxfn.
2842 # this field to determine what to do in filectxfn.
2854 _returnnoneformissingfiles = True
2843 _returnnoneformissingfiles = True
2855
2844
2856 def __init__(
2845 def __init__(
2857 self,
2846 self,
2858 repo,
2847 repo,
2859 parents,
2848 parents,
2860 text,
2849 text,
2861 files,
2850 files,
2862 filectxfn,
2851 filectxfn,
2863 user=None,
2852 user=None,
2864 date=None,
2853 date=None,
2865 extra=None,
2854 extra=None,
2866 branch=None,
2855 branch=None,
2867 editor=None,
2856 editor=None,
2868 ):
2857 ):
2869 super(memctx, self).__init__(
2858 super(memctx, self).__init__(
2870 repo, text, user, date, extra, branch=branch
2859 repo, text, user, date, extra, branch=branch
2871 )
2860 )
2872 self._rev = None
2861 self._rev = None
2873 self._node = None
2862 self._node = None
2874 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2863 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2875 p1, p2 = parents
2864 p1, p2 = parents
2876 self._parents = [self._repo[p] for p in (p1, p2)]
2865 self._parents = [self._repo[p] for p in (p1, p2)]
2877 files = sorted(set(files))
2866 files = sorted(set(files))
2878 self._files = files
2867 self._files = files
2879 self.substate = {}
2868 self.substate = {}
2880
2869
2881 if isinstance(filectxfn, patch.filestore):
2870 if isinstance(filectxfn, patch.filestore):
2882 filectxfn = memfilefrompatch(filectxfn)
2871 filectxfn = memfilefrompatch(filectxfn)
2883 elif not callable(filectxfn):
2872 elif not callable(filectxfn):
2884 # if store is not callable, wrap it in a function
2873 # if store is not callable, wrap it in a function
2885 filectxfn = memfilefromctx(filectxfn)
2874 filectxfn = memfilefromctx(filectxfn)
2886
2875
2887 # memoizing increases performance for e.g. vcs convert scenarios.
2876 # memoizing increases performance for e.g. vcs convert scenarios.
2888 self._filectxfn = makecachingfilectxfn(filectxfn)
2877 self._filectxfn = makecachingfilectxfn(filectxfn)
2889
2878
2890 if editor:
2879 if editor:
2891 self._text = editor(self._repo, self, [])
2880 self._text = editor(self._repo, self, [])
2892 self._repo.savecommitmessage(self._text)
2881 self._repo.savecommitmessage(self._text)
2893
2882
2894 def filectx(self, path, filelog=None):
2883 def filectx(self, path, filelog=None):
2895 """get a file context from the working directory
2884 """get a file context from the working directory
2896
2885
2897 Returns None if file doesn't exist and should be removed."""
2886 Returns None if file doesn't exist and should be removed."""
2898 return self._filectxfn(self._repo, self, path)
2887 return self._filectxfn(self._repo, self, path)
2899
2888
2900 def commit(self):
2889 def commit(self):
2901 """commit context to the repo"""
2890 """commit context to the repo"""
2902 return self._repo.commitctx(self)
2891 return self._repo.commitctx(self)
2903
2892
2904 @propertycache
2893 @propertycache
2905 def _manifest(self):
2894 def _manifest(self):
2906 """generate a manifest based on the return values of filectxfn"""
2895 """generate a manifest based on the return values of filectxfn"""
2907
2896
2908 # keep this simple for now; just worry about p1
2897 # keep this simple for now; just worry about p1
2909 pctx = self._parents[0]
2898 pctx = self._parents[0]
2910 man = pctx.manifest().copy()
2899 man = pctx.manifest().copy()
2911
2900
2912 for f in self._status.modified:
2901 for f in self._status.modified:
2913 man[f] = self._repo.nodeconstants.modifiednodeid
2902 man[f] = self._repo.nodeconstants.modifiednodeid
2914
2903
2915 for f in self._status.added:
2904 for f in self._status.added:
2916 man[f] = self._repo.nodeconstants.addednodeid
2905 man[f] = self._repo.nodeconstants.addednodeid
2917
2906
2918 for f in self._status.removed:
2907 for f in self._status.removed:
2919 if f in man:
2908 if f in man:
2920 del man[f]
2909 del man[f]
2921
2910
2922 return man
2911 return man
2923
2912
2924 @propertycache
2913 @propertycache
2925 def _status(self):
2914 def _status(self):
2926 """Calculate exact status from ``files`` specified at construction"""
2915 """Calculate exact status from ``files`` specified at construction"""
2927 man1 = self.p1().manifest()
2916 man1 = self.p1().manifest()
2928 p2 = self._parents[1]
2917 p2 = self._parents[1]
2929 # "1 < len(self._parents)" can't be used for checking
2918 # "1 < len(self._parents)" can't be used for checking
2930 # existence of the 2nd parent, because "memctx._parents" is
2919 # existence of the 2nd parent, because "memctx._parents" is
2931 # explicitly initialized by the list, of which length is 2.
2920 # explicitly initialized by the list, of which length is 2.
2932 if p2.rev() != nullrev:
2921 if p2.rev() != nullrev:
2933 man2 = p2.manifest()
2922 man2 = p2.manifest()
2934 managing = lambda f: f in man1 or f in man2
2923 managing = lambda f: f in man1 or f in man2
2935 else:
2924 else:
2936 managing = lambda f: f in man1
2925 managing = lambda f: f in man1
2937
2926
2938 modified, added, removed = [], [], []
2927 modified, added, removed = [], [], []
2939 for f in self._files:
2928 for f in self._files:
2940 if not managing(f):
2929 if not managing(f):
2941 added.append(f)
2930 added.append(f)
2942 elif self[f]:
2931 elif self[f]:
2943 modified.append(f)
2932 modified.append(f)
2944 else:
2933 else:
2945 removed.append(f)
2934 removed.append(f)
2946
2935
2947 return scmutil.status(modified, added, removed, [], [], [], [])
2936 return scmutil.status(modified, added, removed, [], [], [], [])
2948
2937
2949 def parents(self):
2938 def parents(self):
2950 if self._parents[1].rev() == nullrev:
2939 if self._parents[1].rev() == nullrev:
2951 return [self._parents[0]]
2940 return [self._parents[0]]
2952 return self._parents
2941 return self._parents
2953
2942
2954
2943
2955 class memfilectx(committablefilectx):
2944 class memfilectx(committablefilectx):
2956 """memfilectx represents an in-memory file to commit.
2945 """memfilectx represents an in-memory file to commit.
2957
2946
2958 See memctx and committablefilectx for more details.
2947 See memctx and committablefilectx for more details.
2959 """
2948 """
2960
2949
2961 def __init__(
2950 def __init__(
2962 self,
2951 self,
2963 repo,
2952 repo,
2964 changectx,
2953 changectx,
2965 path,
2954 path,
2966 data,
2955 data,
2967 islink=False,
2956 islink=False,
2968 isexec=False,
2957 isexec=False,
2969 copysource=None,
2958 copysource=None,
2970 ):
2959 ):
2971 """
2960 """
2972 path is the normalized file path relative to repository root.
2961 path is the normalized file path relative to repository root.
2973 data is the file content as a string.
2962 data is the file content as a string.
2974 islink is True if the file is a symbolic link.
2963 islink is True if the file is a symbolic link.
2975 isexec is True if the file is executable.
2964 isexec is True if the file is executable.
2976 copied is the source file path if current file was copied in the
2965 copied is the source file path if current file was copied in the
2977 revision being committed, or None."""
2966 revision being committed, or None."""
2978 super(memfilectx, self).__init__(repo, path, None, changectx)
2967 super(memfilectx, self).__init__(repo, path, None, changectx)
2979 self._data = data
2968 self._data = data
2980 if islink:
2969 if islink:
2981 self._flags = b'l'
2970 self._flags = b'l'
2982 elif isexec:
2971 elif isexec:
2983 self._flags = b'x'
2972 self._flags = b'x'
2984 else:
2973 else:
2985 self._flags = b''
2974 self._flags = b''
2986 self._copysource = copysource
2975 self._copysource = copysource
2987
2976
2988 def copysource(self):
2977 def copysource(self):
2989 return self._copysource
2978 return self._copysource
2990
2979
2991 def cmp(self, fctx):
2980 def cmp(self, fctx):
2992 return self.data() != fctx.data()
2981 return self.data() != fctx.data()
2993
2982
2994 def data(self):
2983 def data(self):
2995 return self._data
2984 return self._data
2996
2985
2997 def remove(self, ignoremissing=False):
2986 def remove(self, ignoremissing=False):
2998 """wraps unlink for a repo's working directory"""
2987 """wraps unlink for a repo's working directory"""
2999 # need to figure out what to do here
2988 # need to figure out what to do here
3000 del self._changectx[self._path]
2989 del self._changectx[self._path]
3001
2990
3002 def write(self, data, flags, **kwargs):
2991 def write(self, data, flags, **kwargs):
3003 """wraps repo.wwrite"""
2992 """wraps repo.wwrite"""
3004 self._data = data
2993 self._data = data
3005
2994
3006
2995
3007 class metadataonlyctx(committablectx):
2996 class metadataonlyctx(committablectx):
3008 """Like memctx but it's reusing the manifest of different commit.
2997 """Like memctx but it's reusing the manifest of different commit.
3009 Intended to be used by lightweight operations that are creating
2998 Intended to be used by lightweight operations that are creating
3010 metadata-only changes.
2999 metadata-only changes.
3011
3000
3012 Revision information is supplied at initialization time. 'repo' is the
3001 Revision information is supplied at initialization time. 'repo' is the
3013 current localrepo, 'ctx' is original revision which manifest we're reuisng
3002 current localrepo, 'ctx' is original revision which manifest we're reuisng
3014 'parents' is a sequence of two parent revisions identifiers (pass None for
3003 'parents' is a sequence of two parent revisions identifiers (pass None for
3015 every missing parent), 'text' is the commit.
3004 every missing parent), 'text' is the commit.
3016
3005
3017 user receives the committer name and defaults to current repository
3006 user receives the committer name and defaults to current repository
3018 username, date is the commit date in any format supported by
3007 username, date is the commit date in any format supported by
3019 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3008 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3020 metadata or is left empty.
3009 metadata or is left empty.
3021 """
3010 """
3022
3011
3023 def __init__(
3012 def __init__(
3024 self,
3013 self,
3025 repo,
3014 repo,
3026 originalctx,
3015 originalctx,
3027 parents=None,
3016 parents=None,
3028 text=None,
3017 text=None,
3029 user=None,
3018 user=None,
3030 date=None,
3019 date=None,
3031 extra=None,
3020 extra=None,
3032 editor=None,
3021 editor=None,
3033 ):
3022 ):
3034 if text is None:
3023 if text is None:
3035 text = originalctx.description()
3024 text = originalctx.description()
3036 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3025 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3037 self._rev = None
3026 self._rev = None
3038 self._node = None
3027 self._node = None
3039 self._originalctx = originalctx
3028 self._originalctx = originalctx
3040 self._manifestnode = originalctx.manifestnode()
3029 self._manifestnode = originalctx.manifestnode()
3041 if parents is None:
3030 if parents is None:
3042 parents = originalctx.parents()
3031 parents = originalctx.parents()
3043 else:
3032 else:
3044 parents = [repo[p] for p in parents if p is not None]
3033 parents = [repo[p] for p in parents if p is not None]
3045 parents = parents[:]
3034 parents = parents[:]
3046 while len(parents) < 2:
3035 while len(parents) < 2:
3047 parents.append(repo[nullrev])
3036 parents.append(repo[nullrev])
3048 p1, p2 = self._parents = parents
3037 p1, p2 = self._parents = parents
3049
3038
3050 # sanity check to ensure that the reused manifest parents are
3039 # sanity check to ensure that the reused manifest parents are
3051 # manifests of our commit parents
3040 # manifests of our commit parents
3052 mp1, mp2 = self.manifestctx().parents
3041 mp1, mp2 = self.manifestctx().parents
3053 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3042 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3054 raise RuntimeError(
3043 raise RuntimeError(
3055 r"can't reuse the manifest: its p1 "
3044 r"can't reuse the manifest: its p1 "
3056 r"doesn't match the new ctx p1"
3045 r"doesn't match the new ctx p1"
3057 )
3046 )
3058 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3047 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3059 raise RuntimeError(
3048 raise RuntimeError(
3060 r"can't reuse the manifest: "
3049 r"can't reuse the manifest: "
3061 r"its p2 doesn't match the new ctx p2"
3050 r"its p2 doesn't match the new ctx p2"
3062 )
3051 )
3063
3052
3064 self._files = originalctx.files()
3053 self._files = originalctx.files()
3065 self.substate = {}
3054 self.substate = {}
3066
3055
3067 if editor:
3056 if editor:
3068 self._text = editor(self._repo, self, [])
3057 self._text = editor(self._repo, self, [])
3069 self._repo.savecommitmessage(self._text)
3058 self._repo.savecommitmessage(self._text)
3070
3059
3071 def manifestnode(self):
3060 def manifestnode(self):
3072 return self._manifestnode
3061 return self._manifestnode
3073
3062
3074 @property
3063 @property
3075 def _manifestctx(self):
3064 def _manifestctx(self):
3076 return self._repo.manifestlog[self._manifestnode]
3065 return self._repo.manifestlog[self._manifestnode]
3077
3066
3078 def filectx(self, path, filelog=None):
3067 def filectx(self, path, filelog=None):
3079 return self._originalctx.filectx(path, filelog=filelog)
3068 return self._originalctx.filectx(path, filelog=filelog)
3080
3069
3081 def commit(self):
3070 def commit(self):
3082 """commit context to the repo"""
3071 """commit context to the repo"""
3083 return self._repo.commitctx(self)
3072 return self._repo.commitctx(self)
3084
3073
3085 @property
3074 @property
3086 def _manifest(self):
3075 def _manifest(self):
3087 return self._originalctx.manifest()
3076 return self._originalctx.manifest()
3088
3077
3089 @propertycache
3078 @propertycache
3090 def _status(self):
3079 def _status(self):
3091 """Calculate exact status from ``files`` specified in the ``origctx``
3080 """Calculate exact status from ``files`` specified in the ``origctx``
3092 and parents manifests.
3081 and parents manifests.
3093 """
3082 """
3094 man1 = self.p1().manifest()
3083 man1 = self.p1().manifest()
3095 p2 = self._parents[1]
3084 p2 = self._parents[1]
3096 # "1 < len(self._parents)" can't be used for checking
3085 # "1 < len(self._parents)" can't be used for checking
3097 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3086 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3098 # explicitly initialized by the list, of which length is 2.
3087 # explicitly initialized by the list, of which length is 2.
3099 if p2.rev() != nullrev:
3088 if p2.rev() != nullrev:
3100 man2 = p2.manifest()
3089 man2 = p2.manifest()
3101 managing = lambda f: f in man1 or f in man2
3090 managing = lambda f: f in man1 or f in man2
3102 else:
3091 else:
3103 managing = lambda f: f in man1
3092 managing = lambda f: f in man1
3104
3093
3105 modified, added, removed = [], [], []
3094 modified, added, removed = [], [], []
3106 for f in self._files:
3095 for f in self._files:
3107 if not managing(f):
3096 if not managing(f):
3108 added.append(f)
3097 added.append(f)
3109 elif f in self:
3098 elif f in self:
3110 modified.append(f)
3099 modified.append(f)
3111 else:
3100 else:
3112 removed.append(f)
3101 removed.append(f)
3113
3102
3114 return scmutil.status(modified, added, removed, [], [], [], [])
3103 return scmutil.status(modified, added, removed, [], [], [], [])
3115
3104
3116
3105
3117 class arbitraryfilectx:
3106 class arbitraryfilectx:
3118 """Allows you to use filectx-like functions on a file in an arbitrary
3107 """Allows you to use filectx-like functions on a file in an arbitrary
3119 location on disk, possibly not in the working directory.
3108 location on disk, possibly not in the working directory.
3120 """
3109 """
3121
3110
3122 def __init__(self, path, repo=None):
3111 def __init__(self, path, repo=None):
3123 # Repo is optional because contrib/simplemerge uses this class.
3112 # Repo is optional because contrib/simplemerge uses this class.
3124 self._repo = repo
3113 self._repo = repo
3125 self._path = path
3114 self._path = path
3126
3115
3127 def cmp(self, fctx):
3116 def cmp(self, fctx):
3128 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3117 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3129 # path if either side is a symlink.
3118 # path if either side is a symlink.
3130 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3119 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3131 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3120 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3132 # Add a fast-path for merge if both sides are disk-backed.
3121 # Add a fast-path for merge if both sides are disk-backed.
3133 # Note that filecmp uses the opposite return values (True if same)
3122 # Note that filecmp uses the opposite return values (True if same)
3134 # from our cmp functions (True if different).
3123 # from our cmp functions (True if different).
3135 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3124 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3136 return self.data() != fctx.data()
3125 return self.data() != fctx.data()
3137
3126
3138 def path(self):
3127 def path(self):
3139 return self._path
3128 return self._path
3140
3129
3141 def flags(self):
3130 def flags(self):
3142 return b''
3131 return b''
3143
3132
3144 def data(self):
3133 def data(self):
3145 return util.readfile(self._path)
3134 return util.readfile(self._path)
3146
3135
3147 def decodeddata(self):
3136 def decodeddata(self):
3148 return util.readfile(self._path)
3137 return util.readfile(self._path)
3149
3138
3150 def remove(self):
3139 def remove(self):
3151 util.unlink(self._path)
3140 util.unlink(self._path)
3152
3141
3153 def write(self, data, flags, **kwargs):
3142 def write(self, data, flags, **kwargs):
3154 assert not flags
3143 assert not flags
3155 util.writefile(self._path, data)
3144 util.writefile(self._path, data)
General Comments 0
You need to be logged in to leave comments. Login now