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