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