##// END OF EJS Templates
context: skip path conflicts by default when clearing unknown file (issue5776)...
Matt Harbison -
r37329:656ac240 default
parent child Browse files
Show More
@@ -1,2616 +1,2617 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 . import (
29 from . import (
30 dagop,
30 dagop,
31 encoding,
31 encoding,
32 error,
32 error,
33 fileset,
33 fileset,
34 match as matchmod,
34 match as matchmod,
35 obsolete as obsmod,
35 obsolete as obsmod,
36 obsutil,
36 obsutil,
37 patch,
37 patch,
38 pathutil,
38 pathutil,
39 phases,
39 phases,
40 pycompat,
40 pycompat,
41 repoview,
41 repoview,
42 revlog,
42 revlog,
43 scmutil,
43 scmutil,
44 sparse,
44 sparse,
45 subrepo,
45 subrepo,
46 subrepoutil,
46 subrepoutil,
47 util,
47 util,
48 )
48 )
49 from .utils import (
49 from .utils import (
50 dateutil,
50 dateutil,
51 stringutil,
51 stringutil,
52 )
52 )
53
53
54 propertycache = util.propertycache
54 propertycache = util.propertycache
55
55
56 nonascii = re.compile(br'[^\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 = "%d" % changeid
436 changeid = "%d" % 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 r"<%s %s>" % (type(self).__name__, str(self))
751 return r"<%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 stringutil.binary(self.data())
824 return stringutil.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, skiprevs=None, diffopts=None):
973 def annotate(self, follow=False, skiprevs=None, diffopts=None):
974 """Returns a list of annotateline objects for each line in the file
974 """Returns a list of annotateline objects for each line in the file
975
975
976 - line.fctx is the filectx of the node where that line was last changed
976 - line.fctx is the filectx of the node where that line was last changed
977 - line.lineno is the line number at the first appearance in the managed
977 - line.lineno is the line number at the first appearance in the managed
978 file
978 file
979 - line.text is the data on that line (including newline character)
979 - line.text is the data on that line (including newline character)
980 """
980 """
981 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
981 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
982
982
983 def parents(f):
983 def parents(f):
984 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
984 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
985 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
985 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
986 # from the topmost introrev (= srcrev) down to p.linkrev() if it
986 # from the topmost introrev (= srcrev) down to p.linkrev() if it
987 # isn't an ancestor of the srcrev.
987 # isn't an ancestor of the srcrev.
988 f._changeid
988 f._changeid
989 pl = f.parents()
989 pl = f.parents()
990
990
991 # Don't return renamed parents if we aren't following.
991 # Don't return renamed parents if we aren't following.
992 if not follow:
992 if not follow:
993 pl = [p for p in pl if p.path() == f.path()]
993 pl = [p for p in pl if p.path() == f.path()]
994
994
995 # renamed filectx won't have a filelog yet, so set it
995 # renamed filectx won't have a filelog yet, so set it
996 # from the cache to save time
996 # from the cache to save time
997 for p in pl:
997 for p in pl:
998 if not r'_filelog' in p.__dict__:
998 if not r'_filelog' in p.__dict__:
999 p._filelog = getlog(p.path())
999 p._filelog = getlog(p.path())
1000
1000
1001 return pl
1001 return pl
1002
1002
1003 # use linkrev to find the first changeset where self appeared
1003 # use linkrev to find the first changeset where self appeared
1004 base = self.introfilectx()
1004 base = self.introfilectx()
1005 if getattr(base, '_ancestrycontext', None) is None:
1005 if getattr(base, '_ancestrycontext', None) is None:
1006 cl = self._repo.changelog
1006 cl = self._repo.changelog
1007 if base.rev() is None:
1007 if base.rev() is None:
1008 # wctx is not inclusive, but works because _ancestrycontext
1008 # wctx is not inclusive, but works because _ancestrycontext
1009 # is used to test filelog revisions
1009 # is used to test filelog revisions
1010 ac = cl.ancestors([p.rev() for p in base.parents()],
1010 ac = cl.ancestors([p.rev() for p in base.parents()],
1011 inclusive=True)
1011 inclusive=True)
1012 else:
1012 else:
1013 ac = cl.ancestors([base.rev()], inclusive=True)
1013 ac = cl.ancestors([base.rev()], inclusive=True)
1014 base._ancestrycontext = ac
1014 base._ancestrycontext = ac
1015
1015
1016 return dagop.annotate(base, parents, skiprevs=skiprevs,
1016 return dagop.annotate(base, parents, skiprevs=skiprevs,
1017 diffopts=diffopts)
1017 diffopts=diffopts)
1018
1018
1019 def ancestors(self, followfirst=False):
1019 def ancestors(self, followfirst=False):
1020 visit = {}
1020 visit = {}
1021 c = self
1021 c = self
1022 if followfirst:
1022 if followfirst:
1023 cut = 1
1023 cut = 1
1024 else:
1024 else:
1025 cut = None
1025 cut = None
1026
1026
1027 while True:
1027 while True:
1028 for parent in c.parents()[:cut]:
1028 for parent in c.parents()[:cut]:
1029 visit[(parent.linkrev(), parent.filenode())] = parent
1029 visit[(parent.linkrev(), parent.filenode())] = parent
1030 if not visit:
1030 if not visit:
1031 break
1031 break
1032 c = visit.pop(max(visit))
1032 c = visit.pop(max(visit))
1033 yield c
1033 yield c
1034
1034
1035 def decodeddata(self):
1035 def decodeddata(self):
1036 """Returns `data()` after running repository decoding filters.
1036 """Returns `data()` after running repository decoding filters.
1037
1037
1038 This is often equivalent to how the data would be expressed on disk.
1038 This is often equivalent to how the data would be expressed on disk.
1039 """
1039 """
1040 return self._repo.wwritedata(self.path(), self.data())
1040 return self._repo.wwritedata(self.path(), self.data())
1041
1041
1042 class filectx(basefilectx):
1042 class filectx(basefilectx):
1043 """A filecontext object makes access to data related to a particular
1043 """A filecontext object makes access to data related to a particular
1044 filerevision convenient."""
1044 filerevision convenient."""
1045 def __init__(self, repo, path, changeid=None, fileid=None,
1045 def __init__(self, repo, path, changeid=None, fileid=None,
1046 filelog=None, changectx=None):
1046 filelog=None, changectx=None):
1047 """changeid can be a changeset revision, node, or tag.
1047 """changeid can be a changeset revision, node, or tag.
1048 fileid can be a file revision or node."""
1048 fileid can be a file revision or node."""
1049 self._repo = repo
1049 self._repo = repo
1050 self._path = path
1050 self._path = path
1051
1051
1052 assert (changeid is not None
1052 assert (changeid is not None
1053 or fileid is not None
1053 or fileid is not None
1054 or changectx is not None), \
1054 or changectx is not None), \
1055 ("bad args: changeid=%r, fileid=%r, changectx=%r"
1055 ("bad args: changeid=%r, fileid=%r, changectx=%r"
1056 % (changeid, fileid, changectx))
1056 % (changeid, fileid, changectx))
1057
1057
1058 if filelog is not None:
1058 if filelog is not None:
1059 self._filelog = filelog
1059 self._filelog = filelog
1060
1060
1061 if changeid is not None:
1061 if changeid is not None:
1062 self._changeid = changeid
1062 self._changeid = changeid
1063 if changectx is not None:
1063 if changectx is not None:
1064 self._changectx = changectx
1064 self._changectx = changectx
1065 if fileid is not None:
1065 if fileid is not None:
1066 self._fileid = fileid
1066 self._fileid = fileid
1067
1067
1068 @propertycache
1068 @propertycache
1069 def _changectx(self):
1069 def _changectx(self):
1070 try:
1070 try:
1071 return changectx(self._repo, self._changeid)
1071 return changectx(self._repo, self._changeid)
1072 except error.FilteredRepoLookupError:
1072 except error.FilteredRepoLookupError:
1073 # Linkrev may point to any revision in the repository. When the
1073 # Linkrev may point to any revision in the repository. When the
1074 # repository is filtered this may lead to `filectx` trying to build
1074 # repository is filtered this may lead to `filectx` trying to build
1075 # `changectx` for filtered revision. In such case we fallback to
1075 # `changectx` for filtered revision. In such case we fallback to
1076 # creating `changectx` on the unfiltered version of the reposition.
1076 # creating `changectx` on the unfiltered version of the reposition.
1077 # This fallback should not be an issue because `changectx` from
1077 # This fallback should not be an issue because `changectx` from
1078 # `filectx` are not used in complex operations that care about
1078 # `filectx` are not used in complex operations that care about
1079 # filtering.
1079 # filtering.
1080 #
1080 #
1081 # This fallback is a cheap and dirty fix that prevent several
1081 # This fallback is a cheap and dirty fix that prevent several
1082 # crashes. It does not ensure the behavior is correct. However the
1082 # crashes. It does not ensure the behavior is correct. However the
1083 # behavior was not correct before filtering either and "incorrect
1083 # behavior was not correct before filtering either and "incorrect
1084 # behavior" is seen as better as "crash"
1084 # behavior" is seen as better as "crash"
1085 #
1085 #
1086 # Linkrevs have several serious troubles with filtering that are
1086 # Linkrevs have several serious troubles with filtering that are
1087 # complicated to solve. Proper handling of the issue here should be
1087 # complicated to solve. Proper handling of the issue here should be
1088 # considered when solving linkrev issue are on the table.
1088 # considered when solving linkrev issue are on the table.
1089 return changectx(self._repo.unfiltered(), self._changeid)
1089 return changectx(self._repo.unfiltered(), self._changeid)
1090
1090
1091 def filectx(self, fileid, changeid=None):
1091 def filectx(self, fileid, changeid=None):
1092 '''opens an arbitrary revision of the file without
1092 '''opens an arbitrary revision of the file without
1093 opening a new filelog'''
1093 opening a new filelog'''
1094 return filectx(self._repo, self._path, fileid=fileid,
1094 return filectx(self._repo, self._path, fileid=fileid,
1095 filelog=self._filelog, changeid=changeid)
1095 filelog=self._filelog, changeid=changeid)
1096
1096
1097 def rawdata(self):
1097 def rawdata(self):
1098 return self._filelog.revision(self._filenode, raw=True)
1098 return self._filelog.revision(self._filenode, raw=True)
1099
1099
1100 def rawflags(self):
1100 def rawflags(self):
1101 """low-level revlog flags"""
1101 """low-level revlog flags"""
1102 return self._filelog.flags(self._filerev)
1102 return self._filelog.flags(self._filerev)
1103
1103
1104 def data(self):
1104 def data(self):
1105 try:
1105 try:
1106 return self._filelog.read(self._filenode)
1106 return self._filelog.read(self._filenode)
1107 except error.CensoredNodeError:
1107 except error.CensoredNodeError:
1108 if self._repo.ui.config("censor", "policy") == "ignore":
1108 if self._repo.ui.config("censor", "policy") == "ignore":
1109 return ""
1109 return ""
1110 raise error.Abort(_("censored node: %s") % short(self._filenode),
1110 raise error.Abort(_("censored node: %s") % short(self._filenode),
1111 hint=_("set censor.policy to ignore errors"))
1111 hint=_("set censor.policy to ignore errors"))
1112
1112
1113 def size(self):
1113 def size(self):
1114 return self._filelog.size(self._filerev)
1114 return self._filelog.size(self._filerev)
1115
1115
1116 @propertycache
1116 @propertycache
1117 def _copied(self):
1117 def _copied(self):
1118 """check if file was actually renamed in this changeset revision
1118 """check if file was actually renamed in this changeset revision
1119
1119
1120 If rename logged in file revision, we report copy for changeset only
1120 If rename logged in file revision, we report copy for changeset only
1121 if file revisions linkrev points back to the changeset in question
1121 if file revisions linkrev points back to the changeset in question
1122 or both changeset parents contain different file revisions.
1122 or both changeset parents contain different file revisions.
1123 """
1123 """
1124
1124
1125 renamed = self._filelog.renamed(self._filenode)
1125 renamed = self._filelog.renamed(self._filenode)
1126 if not renamed:
1126 if not renamed:
1127 return renamed
1127 return renamed
1128
1128
1129 if self.rev() == self.linkrev():
1129 if self.rev() == self.linkrev():
1130 return renamed
1130 return renamed
1131
1131
1132 name = self.path()
1132 name = self.path()
1133 fnode = self._filenode
1133 fnode = self._filenode
1134 for p in self._changectx.parents():
1134 for p in self._changectx.parents():
1135 try:
1135 try:
1136 if fnode == p.filenode(name):
1136 if fnode == p.filenode(name):
1137 return None
1137 return None
1138 except error.LookupError:
1138 except error.LookupError:
1139 pass
1139 pass
1140 return renamed
1140 return renamed
1141
1141
1142 def children(self):
1142 def children(self):
1143 # hard for renames
1143 # hard for renames
1144 c = self._filelog.children(self._filenode)
1144 c = self._filelog.children(self._filenode)
1145 return [filectx(self._repo, self._path, fileid=x,
1145 return [filectx(self._repo, self._path, fileid=x,
1146 filelog=self._filelog) for x in c]
1146 filelog=self._filelog) for x in c]
1147
1147
1148 class committablectx(basectx):
1148 class committablectx(basectx):
1149 """A committablectx object provides common functionality for a context that
1149 """A committablectx object provides common functionality for a context that
1150 wants the ability to commit, e.g. workingctx or memctx."""
1150 wants the ability to commit, e.g. workingctx or memctx."""
1151 def __init__(self, repo, text="", user=None, date=None, extra=None,
1151 def __init__(self, repo, text="", user=None, date=None, extra=None,
1152 changes=None):
1152 changes=None):
1153 self._repo = repo
1153 self._repo = repo
1154 self._rev = None
1154 self._rev = None
1155 self._node = None
1155 self._node = None
1156 self._text = text
1156 self._text = text
1157 if date:
1157 if date:
1158 self._date = dateutil.parsedate(date)
1158 self._date = dateutil.parsedate(date)
1159 if user:
1159 if user:
1160 self._user = user
1160 self._user = user
1161 if changes:
1161 if changes:
1162 self._status = changes
1162 self._status = changes
1163
1163
1164 self._extra = {}
1164 self._extra = {}
1165 if extra:
1165 if extra:
1166 self._extra = extra.copy()
1166 self._extra = extra.copy()
1167 if 'branch' not in self._extra:
1167 if 'branch' not in self._extra:
1168 try:
1168 try:
1169 branch = encoding.fromlocal(self._repo.dirstate.branch())
1169 branch = encoding.fromlocal(self._repo.dirstate.branch())
1170 except UnicodeDecodeError:
1170 except UnicodeDecodeError:
1171 raise error.Abort(_('branch name not in UTF-8!'))
1171 raise error.Abort(_('branch name not in UTF-8!'))
1172 self._extra['branch'] = branch
1172 self._extra['branch'] = branch
1173 if self._extra['branch'] == '':
1173 if self._extra['branch'] == '':
1174 self._extra['branch'] = 'default'
1174 self._extra['branch'] = 'default'
1175
1175
1176 def __bytes__(self):
1176 def __bytes__(self):
1177 return bytes(self._parents[0]) + "+"
1177 return bytes(self._parents[0]) + "+"
1178
1178
1179 __str__ = encoding.strmethod(__bytes__)
1179 __str__ = encoding.strmethod(__bytes__)
1180
1180
1181 def __nonzero__(self):
1181 def __nonzero__(self):
1182 return True
1182 return True
1183
1183
1184 __bool__ = __nonzero__
1184 __bool__ = __nonzero__
1185
1185
1186 def _buildflagfunc(self):
1186 def _buildflagfunc(self):
1187 # Create a fallback function for getting file flags when the
1187 # Create a fallback function for getting file flags when the
1188 # filesystem doesn't support them
1188 # filesystem doesn't support them
1189
1189
1190 copiesget = self._repo.dirstate.copies().get
1190 copiesget = self._repo.dirstate.copies().get
1191 parents = self.parents()
1191 parents = self.parents()
1192 if len(parents) < 2:
1192 if len(parents) < 2:
1193 # when we have one parent, it's easy: copy from parent
1193 # when we have one parent, it's easy: copy from parent
1194 man = parents[0].manifest()
1194 man = parents[0].manifest()
1195 def func(f):
1195 def func(f):
1196 f = copiesget(f, f)
1196 f = copiesget(f, f)
1197 return man.flags(f)
1197 return man.flags(f)
1198 else:
1198 else:
1199 # merges are tricky: we try to reconstruct the unstored
1199 # merges are tricky: we try to reconstruct the unstored
1200 # result from the merge (issue1802)
1200 # result from the merge (issue1802)
1201 p1, p2 = parents
1201 p1, p2 = parents
1202 pa = p1.ancestor(p2)
1202 pa = p1.ancestor(p2)
1203 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1203 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1204
1204
1205 def func(f):
1205 def func(f):
1206 f = copiesget(f, f) # may be wrong for merges with copies
1206 f = copiesget(f, f) # may be wrong for merges with copies
1207 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1207 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1208 if fl1 == fl2:
1208 if fl1 == fl2:
1209 return fl1
1209 return fl1
1210 if fl1 == fla:
1210 if fl1 == fla:
1211 return fl2
1211 return fl2
1212 if fl2 == fla:
1212 if fl2 == fla:
1213 return fl1
1213 return fl1
1214 return '' # punt for conflicts
1214 return '' # punt for conflicts
1215
1215
1216 return func
1216 return func
1217
1217
1218 @propertycache
1218 @propertycache
1219 def _flagfunc(self):
1219 def _flagfunc(self):
1220 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1220 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1221
1221
1222 @propertycache
1222 @propertycache
1223 def _status(self):
1223 def _status(self):
1224 return self._repo.status()
1224 return self._repo.status()
1225
1225
1226 @propertycache
1226 @propertycache
1227 def _user(self):
1227 def _user(self):
1228 return self._repo.ui.username()
1228 return self._repo.ui.username()
1229
1229
1230 @propertycache
1230 @propertycache
1231 def _date(self):
1231 def _date(self):
1232 ui = self._repo.ui
1232 ui = self._repo.ui
1233 date = ui.configdate('devel', 'default-date')
1233 date = ui.configdate('devel', 'default-date')
1234 if date is None:
1234 if date is None:
1235 date = dateutil.makedate()
1235 date = dateutil.makedate()
1236 return date
1236 return date
1237
1237
1238 def subrev(self, subpath):
1238 def subrev(self, subpath):
1239 return None
1239 return None
1240
1240
1241 def manifestnode(self):
1241 def manifestnode(self):
1242 return None
1242 return None
1243 def user(self):
1243 def user(self):
1244 return self._user or self._repo.ui.username()
1244 return self._user or self._repo.ui.username()
1245 def date(self):
1245 def date(self):
1246 return self._date
1246 return self._date
1247 def description(self):
1247 def description(self):
1248 return self._text
1248 return self._text
1249 def files(self):
1249 def files(self):
1250 return sorted(self._status.modified + self._status.added +
1250 return sorted(self._status.modified + self._status.added +
1251 self._status.removed)
1251 self._status.removed)
1252
1252
1253 def modified(self):
1253 def modified(self):
1254 return self._status.modified
1254 return self._status.modified
1255 def added(self):
1255 def added(self):
1256 return self._status.added
1256 return self._status.added
1257 def removed(self):
1257 def removed(self):
1258 return self._status.removed
1258 return self._status.removed
1259 def deleted(self):
1259 def deleted(self):
1260 return self._status.deleted
1260 return self._status.deleted
1261 def branch(self):
1261 def branch(self):
1262 return encoding.tolocal(self._extra['branch'])
1262 return encoding.tolocal(self._extra['branch'])
1263 def closesbranch(self):
1263 def closesbranch(self):
1264 return 'close' in self._extra
1264 return 'close' in self._extra
1265 def extra(self):
1265 def extra(self):
1266 return self._extra
1266 return self._extra
1267
1267
1268 def isinmemory(self):
1268 def isinmemory(self):
1269 return False
1269 return False
1270
1270
1271 def tags(self):
1271 def tags(self):
1272 return []
1272 return []
1273
1273
1274 def bookmarks(self):
1274 def bookmarks(self):
1275 b = []
1275 b = []
1276 for p in self.parents():
1276 for p in self.parents():
1277 b.extend(p.bookmarks())
1277 b.extend(p.bookmarks())
1278 return b
1278 return b
1279
1279
1280 def phase(self):
1280 def phase(self):
1281 phase = phases.draft # default phase to draft
1281 phase = phases.draft # default phase to draft
1282 for p in self.parents():
1282 for p in self.parents():
1283 phase = max(phase, p.phase())
1283 phase = max(phase, p.phase())
1284 return phase
1284 return phase
1285
1285
1286 def hidden(self):
1286 def hidden(self):
1287 return False
1287 return False
1288
1288
1289 def children(self):
1289 def children(self):
1290 return []
1290 return []
1291
1291
1292 def flags(self, path):
1292 def flags(self, path):
1293 if r'_manifest' in self.__dict__:
1293 if r'_manifest' in self.__dict__:
1294 try:
1294 try:
1295 return self._manifest.flags(path)
1295 return self._manifest.flags(path)
1296 except KeyError:
1296 except KeyError:
1297 return ''
1297 return ''
1298
1298
1299 try:
1299 try:
1300 return self._flagfunc(path)
1300 return self._flagfunc(path)
1301 except OSError:
1301 except OSError:
1302 return ''
1302 return ''
1303
1303
1304 def ancestor(self, c2):
1304 def ancestor(self, c2):
1305 """return the "best" ancestor context of self and c2"""
1305 """return the "best" ancestor context of self and c2"""
1306 return self._parents[0].ancestor(c2) # punt on two parents for now
1306 return self._parents[0].ancestor(c2) # punt on two parents for now
1307
1307
1308 def walk(self, match):
1308 def walk(self, match):
1309 '''Generates matching file names.'''
1309 '''Generates matching file names.'''
1310 return sorted(self._repo.dirstate.walk(match,
1310 return sorted(self._repo.dirstate.walk(match,
1311 subrepos=sorted(self.substate),
1311 subrepos=sorted(self.substate),
1312 unknown=True, ignored=False))
1312 unknown=True, ignored=False))
1313
1313
1314 def matches(self, match):
1314 def matches(self, match):
1315 return sorted(self._repo.dirstate.matches(match))
1315 return sorted(self._repo.dirstate.matches(match))
1316
1316
1317 def ancestors(self):
1317 def ancestors(self):
1318 for p in self._parents:
1318 for p in self._parents:
1319 yield p
1319 yield p
1320 for a in self._repo.changelog.ancestors(
1320 for a in self._repo.changelog.ancestors(
1321 [p.rev() for p in self._parents]):
1321 [p.rev() for p in self._parents]):
1322 yield changectx(self._repo, a)
1322 yield changectx(self._repo, a)
1323
1323
1324 def markcommitted(self, node):
1324 def markcommitted(self, node):
1325 """Perform post-commit cleanup necessary after committing this ctx
1325 """Perform post-commit cleanup necessary after committing this ctx
1326
1326
1327 Specifically, this updates backing stores this working context
1327 Specifically, this updates backing stores this working context
1328 wraps to reflect the fact that the changes reflected by this
1328 wraps to reflect the fact that the changes reflected by this
1329 workingctx have been committed. For example, it marks
1329 workingctx have been committed. For example, it marks
1330 modified and added files as normal in the dirstate.
1330 modified and added files as normal in the dirstate.
1331
1331
1332 """
1332 """
1333
1333
1334 with self._repo.dirstate.parentchange():
1334 with self._repo.dirstate.parentchange():
1335 for f in self.modified() + self.added():
1335 for f in self.modified() + self.added():
1336 self._repo.dirstate.normal(f)
1336 self._repo.dirstate.normal(f)
1337 for f in self.removed():
1337 for f in self.removed():
1338 self._repo.dirstate.drop(f)
1338 self._repo.dirstate.drop(f)
1339 self._repo.dirstate.setparents(node)
1339 self._repo.dirstate.setparents(node)
1340
1340
1341 # write changes out explicitly, because nesting wlock at
1341 # write changes out explicitly, because nesting wlock at
1342 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1342 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1343 # from immediately doing so for subsequent changing files
1343 # from immediately doing so for subsequent changing files
1344 self._repo.dirstate.write(self._repo.currenttransaction())
1344 self._repo.dirstate.write(self._repo.currenttransaction())
1345
1345
1346 def dirty(self, missing=False, merge=True, branch=True):
1346 def dirty(self, missing=False, merge=True, branch=True):
1347 return False
1347 return False
1348
1348
1349 class workingctx(committablectx):
1349 class workingctx(committablectx):
1350 """A workingctx object makes access to data related to
1350 """A workingctx object makes access to data related to
1351 the current working directory convenient.
1351 the current working directory convenient.
1352 date - any valid date string or (unixtime, offset), or None.
1352 date - any valid date string or (unixtime, offset), or None.
1353 user - username string, or None.
1353 user - username string, or None.
1354 extra - a dictionary of extra values, or None.
1354 extra - a dictionary of extra values, or None.
1355 changes - a list of file lists as returned by localrepo.status()
1355 changes - a list of file lists as returned by localrepo.status()
1356 or None to use the repository status.
1356 or None to use the repository status.
1357 """
1357 """
1358 def __init__(self, repo, text="", user=None, date=None, extra=None,
1358 def __init__(self, repo, text="", user=None, date=None, extra=None,
1359 changes=None):
1359 changes=None):
1360 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1360 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1361
1361
1362 def __iter__(self):
1362 def __iter__(self):
1363 d = self._repo.dirstate
1363 d = self._repo.dirstate
1364 for f in d:
1364 for f in d:
1365 if d[f] != 'r':
1365 if d[f] != 'r':
1366 yield f
1366 yield f
1367
1367
1368 def __contains__(self, key):
1368 def __contains__(self, key):
1369 return self._repo.dirstate[key] not in "?r"
1369 return self._repo.dirstate[key] not in "?r"
1370
1370
1371 def hex(self):
1371 def hex(self):
1372 return hex(wdirid)
1372 return hex(wdirid)
1373
1373
1374 @propertycache
1374 @propertycache
1375 def _parents(self):
1375 def _parents(self):
1376 p = self._repo.dirstate.parents()
1376 p = self._repo.dirstate.parents()
1377 if p[1] == nullid:
1377 if p[1] == nullid:
1378 p = p[:-1]
1378 p = p[:-1]
1379 return [changectx(self._repo, x) for x in p]
1379 return [changectx(self._repo, x) for x in p]
1380
1380
1381 def filectx(self, path, filelog=None):
1381 def filectx(self, path, filelog=None):
1382 """get a file context from the working directory"""
1382 """get a file context from the working directory"""
1383 return workingfilectx(self._repo, path, workingctx=self,
1383 return workingfilectx(self._repo, path, workingctx=self,
1384 filelog=filelog)
1384 filelog=filelog)
1385
1385
1386 def dirty(self, missing=False, merge=True, branch=True):
1386 def dirty(self, missing=False, merge=True, branch=True):
1387 "check whether a working directory is modified"
1387 "check whether a working directory is modified"
1388 # check subrepos first
1388 # check subrepos first
1389 for s in sorted(self.substate):
1389 for s in sorted(self.substate):
1390 if self.sub(s).dirty(missing=missing):
1390 if self.sub(s).dirty(missing=missing):
1391 return True
1391 return True
1392 # check current working dir
1392 # check current working dir
1393 return ((merge and self.p2()) or
1393 return ((merge and self.p2()) or
1394 (branch and self.branch() != self.p1().branch()) or
1394 (branch and self.branch() != self.p1().branch()) or
1395 self.modified() or self.added() or self.removed() or
1395 self.modified() or self.added() or self.removed() or
1396 (missing and self.deleted()))
1396 (missing and self.deleted()))
1397
1397
1398 def add(self, list, prefix=""):
1398 def add(self, list, prefix=""):
1399 with self._repo.wlock():
1399 with self._repo.wlock():
1400 ui, ds = self._repo.ui, self._repo.dirstate
1400 ui, ds = self._repo.ui, self._repo.dirstate
1401 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1401 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1402 rejected = []
1402 rejected = []
1403 lstat = self._repo.wvfs.lstat
1403 lstat = self._repo.wvfs.lstat
1404 for f in list:
1404 for f in list:
1405 # ds.pathto() returns an absolute file when this is invoked from
1405 # ds.pathto() returns an absolute file when this is invoked from
1406 # the keyword extension. That gets flagged as non-portable on
1406 # the keyword extension. That gets flagged as non-portable on
1407 # Windows, since it contains the drive letter and colon.
1407 # Windows, since it contains the drive letter and colon.
1408 scmutil.checkportable(ui, os.path.join(prefix, f))
1408 scmutil.checkportable(ui, os.path.join(prefix, f))
1409 try:
1409 try:
1410 st = lstat(f)
1410 st = lstat(f)
1411 except OSError:
1411 except OSError:
1412 ui.warn(_("%s does not exist!\n") % uipath(f))
1412 ui.warn(_("%s does not exist!\n") % uipath(f))
1413 rejected.append(f)
1413 rejected.append(f)
1414 continue
1414 continue
1415 if st.st_size > 10000000:
1415 if st.st_size > 10000000:
1416 ui.warn(_("%s: up to %d MB of RAM may be required "
1416 ui.warn(_("%s: up to %d MB of RAM may be required "
1417 "to manage this file\n"
1417 "to manage this file\n"
1418 "(use 'hg revert %s' to cancel the "
1418 "(use 'hg revert %s' to cancel the "
1419 "pending addition)\n")
1419 "pending addition)\n")
1420 % (f, 3 * st.st_size // 1000000, uipath(f)))
1420 % (f, 3 * st.st_size // 1000000, uipath(f)))
1421 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1421 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1422 ui.warn(_("%s not added: only files and symlinks "
1422 ui.warn(_("%s not added: only files and symlinks "
1423 "supported currently\n") % uipath(f))
1423 "supported currently\n") % uipath(f))
1424 rejected.append(f)
1424 rejected.append(f)
1425 elif ds[f] in 'amn':
1425 elif ds[f] in 'amn':
1426 ui.warn(_("%s already tracked!\n") % uipath(f))
1426 ui.warn(_("%s already tracked!\n") % uipath(f))
1427 elif ds[f] == 'r':
1427 elif ds[f] == 'r':
1428 ds.normallookup(f)
1428 ds.normallookup(f)
1429 else:
1429 else:
1430 ds.add(f)
1430 ds.add(f)
1431 return rejected
1431 return rejected
1432
1432
1433 def forget(self, files, prefix=""):
1433 def forget(self, files, prefix=""):
1434 with self._repo.wlock():
1434 with self._repo.wlock():
1435 ds = self._repo.dirstate
1435 ds = self._repo.dirstate
1436 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1436 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1437 rejected = []
1437 rejected = []
1438 for f in files:
1438 for f in files:
1439 if f not in self._repo.dirstate:
1439 if f not in self._repo.dirstate:
1440 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1440 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1441 rejected.append(f)
1441 rejected.append(f)
1442 elif self._repo.dirstate[f] != 'a':
1442 elif self._repo.dirstate[f] != 'a':
1443 self._repo.dirstate.remove(f)
1443 self._repo.dirstate.remove(f)
1444 else:
1444 else:
1445 self._repo.dirstate.drop(f)
1445 self._repo.dirstate.drop(f)
1446 return rejected
1446 return rejected
1447
1447
1448 def undelete(self, list):
1448 def undelete(self, list):
1449 pctxs = self.parents()
1449 pctxs = self.parents()
1450 with self._repo.wlock():
1450 with self._repo.wlock():
1451 ds = self._repo.dirstate
1451 ds = self._repo.dirstate
1452 for f in list:
1452 for f in list:
1453 if self._repo.dirstate[f] != 'r':
1453 if self._repo.dirstate[f] != 'r':
1454 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1454 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1455 else:
1455 else:
1456 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1456 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1457 t = fctx.data()
1457 t = fctx.data()
1458 self._repo.wwrite(f, t, fctx.flags())
1458 self._repo.wwrite(f, t, fctx.flags())
1459 self._repo.dirstate.normal(f)
1459 self._repo.dirstate.normal(f)
1460
1460
1461 def copy(self, source, dest):
1461 def copy(self, source, dest):
1462 try:
1462 try:
1463 st = self._repo.wvfs.lstat(dest)
1463 st = self._repo.wvfs.lstat(dest)
1464 except OSError as err:
1464 except OSError as err:
1465 if err.errno != errno.ENOENT:
1465 if err.errno != errno.ENOENT:
1466 raise
1466 raise
1467 self._repo.ui.warn(_("%s does not exist!\n")
1467 self._repo.ui.warn(_("%s does not exist!\n")
1468 % self._repo.dirstate.pathto(dest))
1468 % self._repo.dirstate.pathto(dest))
1469 return
1469 return
1470 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1470 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1471 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1471 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1472 "symbolic link\n")
1472 "symbolic link\n")
1473 % self._repo.dirstate.pathto(dest))
1473 % self._repo.dirstate.pathto(dest))
1474 else:
1474 else:
1475 with self._repo.wlock():
1475 with self._repo.wlock():
1476 if self._repo.dirstate[dest] in '?':
1476 if self._repo.dirstate[dest] in '?':
1477 self._repo.dirstate.add(dest)
1477 self._repo.dirstate.add(dest)
1478 elif self._repo.dirstate[dest] in 'r':
1478 elif self._repo.dirstate[dest] in 'r':
1479 self._repo.dirstate.normallookup(dest)
1479 self._repo.dirstate.normallookup(dest)
1480 self._repo.dirstate.copy(source, dest)
1480 self._repo.dirstate.copy(source, dest)
1481
1481
1482 def match(self, pats=None, include=None, exclude=None, default='glob',
1482 def match(self, pats=None, include=None, exclude=None, default='glob',
1483 listsubrepos=False, badfn=None):
1483 listsubrepos=False, badfn=None):
1484 r = self._repo
1484 r = self._repo
1485
1485
1486 # Only a case insensitive filesystem needs magic to translate user input
1486 # Only a case insensitive filesystem needs magic to translate user input
1487 # to actual case in the filesystem.
1487 # to actual case in the filesystem.
1488 icasefs = not util.fscasesensitive(r.root)
1488 icasefs = not util.fscasesensitive(r.root)
1489 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1489 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1490 default, auditor=r.auditor, ctx=self,
1490 default, auditor=r.auditor, ctx=self,
1491 listsubrepos=listsubrepos, badfn=badfn,
1491 listsubrepos=listsubrepos, badfn=badfn,
1492 icasefs=icasefs)
1492 icasefs=icasefs)
1493
1493
1494 def _filtersuspectsymlink(self, files):
1494 def _filtersuspectsymlink(self, files):
1495 if not files or self._repo.dirstate._checklink:
1495 if not files or self._repo.dirstate._checklink:
1496 return files
1496 return files
1497
1497
1498 # Symlink placeholders may get non-symlink-like contents
1498 # Symlink placeholders may get non-symlink-like contents
1499 # via user error or dereferencing by NFS or Samba servers,
1499 # via user error or dereferencing by NFS or Samba servers,
1500 # so we filter out any placeholders that don't look like a
1500 # so we filter out any placeholders that don't look like a
1501 # symlink
1501 # symlink
1502 sane = []
1502 sane = []
1503 for f in files:
1503 for f in files:
1504 if self.flags(f) == 'l':
1504 if self.flags(f) == 'l':
1505 d = self[f].data()
1505 d = self[f].data()
1506 if (d == '' or len(d) >= 1024 or '\n' in d
1506 if (d == '' or len(d) >= 1024 or '\n' in d
1507 or stringutil.binary(d)):
1507 or stringutil.binary(d)):
1508 self._repo.ui.debug('ignoring suspect symlink placeholder'
1508 self._repo.ui.debug('ignoring suspect symlink placeholder'
1509 ' "%s"\n' % f)
1509 ' "%s"\n' % f)
1510 continue
1510 continue
1511 sane.append(f)
1511 sane.append(f)
1512 return sane
1512 return sane
1513
1513
1514 def _checklookup(self, files):
1514 def _checklookup(self, files):
1515 # check for any possibly clean files
1515 # check for any possibly clean files
1516 if not files:
1516 if not files:
1517 return [], [], []
1517 return [], [], []
1518
1518
1519 modified = []
1519 modified = []
1520 deleted = []
1520 deleted = []
1521 fixup = []
1521 fixup = []
1522 pctx = self._parents[0]
1522 pctx = self._parents[0]
1523 # do a full compare of any files that might have changed
1523 # do a full compare of any files that might have changed
1524 for f in sorted(files):
1524 for f in sorted(files):
1525 try:
1525 try:
1526 # This will return True for a file that got replaced by a
1526 # This will return True for a file that got replaced by a
1527 # directory in the interim, but fixing that is pretty hard.
1527 # directory in the interim, but fixing that is pretty hard.
1528 if (f not in pctx or self.flags(f) != pctx.flags(f)
1528 if (f not in pctx or self.flags(f) != pctx.flags(f)
1529 or pctx[f].cmp(self[f])):
1529 or pctx[f].cmp(self[f])):
1530 modified.append(f)
1530 modified.append(f)
1531 else:
1531 else:
1532 fixup.append(f)
1532 fixup.append(f)
1533 except (IOError, OSError):
1533 except (IOError, OSError):
1534 # A file become inaccessible in between? Mark it as deleted,
1534 # A file become inaccessible in between? Mark it as deleted,
1535 # matching dirstate behavior (issue5584).
1535 # matching dirstate behavior (issue5584).
1536 # The dirstate has more complex behavior around whether a
1536 # The dirstate has more complex behavior around whether a
1537 # missing file matches a directory, etc, but we don't need to
1537 # missing file matches a directory, etc, but we don't need to
1538 # bother with that: if f has made it to this point, we're sure
1538 # bother with that: if f has made it to this point, we're sure
1539 # it's in the dirstate.
1539 # it's in the dirstate.
1540 deleted.append(f)
1540 deleted.append(f)
1541
1541
1542 return modified, deleted, fixup
1542 return modified, deleted, fixup
1543
1543
1544 def _poststatusfixup(self, status, fixup):
1544 def _poststatusfixup(self, status, fixup):
1545 """update dirstate for files that are actually clean"""
1545 """update dirstate for files that are actually clean"""
1546 poststatus = self._repo.postdsstatus()
1546 poststatus = self._repo.postdsstatus()
1547 if fixup or poststatus:
1547 if fixup or poststatus:
1548 try:
1548 try:
1549 oldid = self._repo.dirstate.identity()
1549 oldid = self._repo.dirstate.identity()
1550
1550
1551 # updating the dirstate is optional
1551 # updating the dirstate is optional
1552 # so we don't wait on the lock
1552 # so we don't wait on the lock
1553 # wlock can invalidate the dirstate, so cache normal _after_
1553 # wlock can invalidate the dirstate, so cache normal _after_
1554 # taking the lock
1554 # taking the lock
1555 with self._repo.wlock(False):
1555 with self._repo.wlock(False):
1556 if self._repo.dirstate.identity() == oldid:
1556 if self._repo.dirstate.identity() == oldid:
1557 if fixup:
1557 if fixup:
1558 normal = self._repo.dirstate.normal
1558 normal = self._repo.dirstate.normal
1559 for f in fixup:
1559 for f in fixup:
1560 normal(f)
1560 normal(f)
1561 # write changes out explicitly, because nesting
1561 # write changes out explicitly, because nesting
1562 # wlock at runtime may prevent 'wlock.release()'
1562 # wlock at runtime may prevent 'wlock.release()'
1563 # after this block from doing so for subsequent
1563 # after this block from doing so for subsequent
1564 # changing files
1564 # changing files
1565 tr = self._repo.currenttransaction()
1565 tr = self._repo.currenttransaction()
1566 self._repo.dirstate.write(tr)
1566 self._repo.dirstate.write(tr)
1567
1567
1568 if poststatus:
1568 if poststatus:
1569 for ps in poststatus:
1569 for ps in poststatus:
1570 ps(self, status)
1570 ps(self, status)
1571 else:
1571 else:
1572 # in this case, writing changes out breaks
1572 # in this case, writing changes out breaks
1573 # consistency, because .hg/dirstate was
1573 # consistency, because .hg/dirstate was
1574 # already changed simultaneously after last
1574 # already changed simultaneously after last
1575 # caching (see also issue5584 for detail)
1575 # caching (see also issue5584 for detail)
1576 self._repo.ui.debug('skip updating dirstate: '
1576 self._repo.ui.debug('skip updating dirstate: '
1577 'identity mismatch\n')
1577 'identity mismatch\n')
1578 except error.LockError:
1578 except error.LockError:
1579 pass
1579 pass
1580 finally:
1580 finally:
1581 # Even if the wlock couldn't be grabbed, clear out the list.
1581 # Even if the wlock couldn't be grabbed, clear out the list.
1582 self._repo.clearpostdsstatus()
1582 self._repo.clearpostdsstatus()
1583
1583
1584 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1584 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1585 '''Gets the status from the dirstate -- internal use only.'''
1585 '''Gets the status from the dirstate -- internal use only.'''
1586 subrepos = []
1586 subrepos = []
1587 if '.hgsub' in self:
1587 if '.hgsub' in self:
1588 subrepos = sorted(self.substate)
1588 subrepos = sorted(self.substate)
1589 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1589 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1590 clean=clean, unknown=unknown)
1590 clean=clean, unknown=unknown)
1591
1591
1592 # check for any possibly clean files
1592 # check for any possibly clean files
1593 fixup = []
1593 fixup = []
1594 if cmp:
1594 if cmp:
1595 modified2, deleted2, fixup = self._checklookup(cmp)
1595 modified2, deleted2, fixup = self._checklookup(cmp)
1596 s.modified.extend(modified2)
1596 s.modified.extend(modified2)
1597 s.deleted.extend(deleted2)
1597 s.deleted.extend(deleted2)
1598
1598
1599 if fixup and clean:
1599 if fixup and clean:
1600 s.clean.extend(fixup)
1600 s.clean.extend(fixup)
1601
1601
1602 self._poststatusfixup(s, fixup)
1602 self._poststatusfixup(s, fixup)
1603
1603
1604 if match.always():
1604 if match.always():
1605 # cache for performance
1605 # cache for performance
1606 if s.unknown or s.ignored or s.clean:
1606 if s.unknown or s.ignored or s.clean:
1607 # "_status" is cached with list*=False in the normal route
1607 # "_status" is cached with list*=False in the normal route
1608 self._status = scmutil.status(s.modified, s.added, s.removed,
1608 self._status = scmutil.status(s.modified, s.added, s.removed,
1609 s.deleted, [], [], [])
1609 s.deleted, [], [], [])
1610 else:
1610 else:
1611 self._status = s
1611 self._status = s
1612
1612
1613 return s
1613 return s
1614
1614
1615 @propertycache
1615 @propertycache
1616 def _manifest(self):
1616 def _manifest(self):
1617 """generate a manifest corresponding to the values in self._status
1617 """generate a manifest corresponding to the values in self._status
1618
1618
1619 This reuse the file nodeid from parent, but we use special node
1619 This reuse the file nodeid from parent, but we use special node
1620 identifiers for added and modified files. This is used by manifests
1620 identifiers for added and modified files. This is used by manifests
1621 merge to see that files are different and by update logic to avoid
1621 merge to see that files are different and by update logic to avoid
1622 deleting newly added files.
1622 deleting newly added files.
1623 """
1623 """
1624 return self._buildstatusmanifest(self._status)
1624 return self._buildstatusmanifest(self._status)
1625
1625
1626 def _buildstatusmanifest(self, status):
1626 def _buildstatusmanifest(self, status):
1627 """Builds a manifest that includes the given status results."""
1627 """Builds a manifest that includes the given status results."""
1628 parents = self.parents()
1628 parents = self.parents()
1629
1629
1630 man = parents[0].manifest().copy()
1630 man = parents[0].manifest().copy()
1631
1631
1632 ff = self._flagfunc
1632 ff = self._flagfunc
1633 for i, l in ((addednodeid, status.added),
1633 for i, l in ((addednodeid, status.added),
1634 (modifiednodeid, status.modified)):
1634 (modifiednodeid, status.modified)):
1635 for f in l:
1635 for f in l:
1636 man[f] = i
1636 man[f] = i
1637 try:
1637 try:
1638 man.setflag(f, ff(f))
1638 man.setflag(f, ff(f))
1639 except OSError:
1639 except OSError:
1640 pass
1640 pass
1641
1641
1642 for f in status.deleted + status.removed:
1642 for f in status.deleted + status.removed:
1643 if f in man:
1643 if f in man:
1644 del man[f]
1644 del man[f]
1645
1645
1646 return man
1646 return man
1647
1647
1648 def _buildstatus(self, other, s, match, listignored, listclean,
1648 def _buildstatus(self, other, s, match, listignored, listclean,
1649 listunknown):
1649 listunknown):
1650 """build a status with respect to another context
1650 """build a status with respect to another context
1651
1651
1652 This includes logic for maintaining the fast path of status when
1652 This includes logic for maintaining the fast path of status when
1653 comparing the working directory against its parent, which is to skip
1653 comparing the working directory against its parent, which is to skip
1654 building a new manifest if self (working directory) is not comparing
1654 building a new manifest if self (working directory) is not comparing
1655 against its parent (repo['.']).
1655 against its parent (repo['.']).
1656 """
1656 """
1657 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1657 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1658 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1658 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1659 # might have accidentally ended up with the entire contents of the file
1659 # might have accidentally ended up with the entire contents of the file
1660 # they are supposed to be linking to.
1660 # they are supposed to be linking to.
1661 s.modified[:] = self._filtersuspectsymlink(s.modified)
1661 s.modified[:] = self._filtersuspectsymlink(s.modified)
1662 if other != self._repo['.']:
1662 if other != self._repo['.']:
1663 s = super(workingctx, self)._buildstatus(other, s, match,
1663 s = super(workingctx, self)._buildstatus(other, s, match,
1664 listignored, listclean,
1664 listignored, listclean,
1665 listunknown)
1665 listunknown)
1666 return s
1666 return s
1667
1667
1668 def _matchstatus(self, other, match):
1668 def _matchstatus(self, other, match):
1669 """override the match method with a filter for directory patterns
1669 """override the match method with a filter for directory patterns
1670
1670
1671 We use inheritance to customize the match.bad method only in cases of
1671 We use inheritance to customize the match.bad method only in cases of
1672 workingctx since it belongs only to the working directory when
1672 workingctx since it belongs only to the working directory when
1673 comparing against the parent changeset.
1673 comparing against the parent changeset.
1674
1674
1675 If we aren't comparing against the working directory's parent, then we
1675 If we aren't comparing against the working directory's parent, then we
1676 just use the default match object sent to us.
1676 just use the default match object sent to us.
1677 """
1677 """
1678 if other != self._repo['.']:
1678 if other != self._repo['.']:
1679 def bad(f, msg):
1679 def bad(f, msg):
1680 # 'f' may be a directory pattern from 'match.files()',
1680 # 'f' may be a directory pattern from 'match.files()',
1681 # so 'f not in ctx1' is not enough
1681 # so 'f not in ctx1' is not enough
1682 if f not in other and not other.hasdir(f):
1682 if f not in other and not other.hasdir(f):
1683 self._repo.ui.warn('%s: %s\n' %
1683 self._repo.ui.warn('%s: %s\n' %
1684 (self._repo.dirstate.pathto(f), msg))
1684 (self._repo.dirstate.pathto(f), msg))
1685 match.bad = bad
1685 match.bad = bad
1686 return match
1686 return match
1687
1687
1688 def markcommitted(self, node):
1688 def markcommitted(self, node):
1689 super(workingctx, self).markcommitted(node)
1689 super(workingctx, self).markcommitted(node)
1690
1690
1691 sparse.aftercommit(self._repo, node)
1691 sparse.aftercommit(self._repo, node)
1692
1692
1693 class committablefilectx(basefilectx):
1693 class committablefilectx(basefilectx):
1694 """A committablefilectx provides common functionality for a file context
1694 """A committablefilectx provides common functionality for a file context
1695 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1695 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1696 def __init__(self, repo, path, filelog=None, ctx=None):
1696 def __init__(self, repo, path, filelog=None, ctx=None):
1697 self._repo = repo
1697 self._repo = repo
1698 self._path = path
1698 self._path = path
1699 self._changeid = None
1699 self._changeid = None
1700 self._filerev = self._filenode = None
1700 self._filerev = self._filenode = None
1701
1701
1702 if filelog is not None:
1702 if filelog is not None:
1703 self._filelog = filelog
1703 self._filelog = filelog
1704 if ctx:
1704 if ctx:
1705 self._changectx = ctx
1705 self._changectx = ctx
1706
1706
1707 def __nonzero__(self):
1707 def __nonzero__(self):
1708 return True
1708 return True
1709
1709
1710 __bool__ = __nonzero__
1710 __bool__ = __nonzero__
1711
1711
1712 def linkrev(self):
1712 def linkrev(self):
1713 # linked to self._changectx no matter if file is modified or not
1713 # linked to self._changectx no matter if file is modified or not
1714 return self.rev()
1714 return self.rev()
1715
1715
1716 def parents(self):
1716 def parents(self):
1717 '''return parent filectxs, following copies if necessary'''
1717 '''return parent filectxs, following copies if necessary'''
1718 def filenode(ctx, path):
1718 def filenode(ctx, path):
1719 return ctx._manifest.get(path, nullid)
1719 return ctx._manifest.get(path, nullid)
1720
1720
1721 path = self._path
1721 path = self._path
1722 fl = self._filelog
1722 fl = self._filelog
1723 pcl = self._changectx._parents
1723 pcl = self._changectx._parents
1724 renamed = self.renamed()
1724 renamed = self.renamed()
1725
1725
1726 if renamed:
1726 if renamed:
1727 pl = [renamed + (None,)]
1727 pl = [renamed + (None,)]
1728 else:
1728 else:
1729 pl = [(path, filenode(pcl[0], path), fl)]
1729 pl = [(path, filenode(pcl[0], path), fl)]
1730
1730
1731 for pc in pcl[1:]:
1731 for pc in pcl[1:]:
1732 pl.append((path, filenode(pc, path), fl))
1732 pl.append((path, filenode(pc, path), fl))
1733
1733
1734 return [self._parentfilectx(p, fileid=n, filelog=l)
1734 return [self._parentfilectx(p, fileid=n, filelog=l)
1735 for p, n, l in pl if n != nullid]
1735 for p, n, l in pl if n != nullid]
1736
1736
1737 def children(self):
1737 def children(self):
1738 return []
1738 return []
1739
1739
1740 class workingfilectx(committablefilectx):
1740 class workingfilectx(committablefilectx):
1741 """A workingfilectx object makes access to data related to a particular
1741 """A workingfilectx object makes access to data related to a particular
1742 file in the working directory convenient."""
1742 file in the working directory convenient."""
1743 def __init__(self, repo, path, filelog=None, workingctx=None):
1743 def __init__(self, repo, path, filelog=None, workingctx=None):
1744 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1744 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1745
1745
1746 @propertycache
1746 @propertycache
1747 def _changectx(self):
1747 def _changectx(self):
1748 return workingctx(self._repo)
1748 return workingctx(self._repo)
1749
1749
1750 def data(self):
1750 def data(self):
1751 return self._repo.wread(self._path)
1751 return self._repo.wread(self._path)
1752 def renamed(self):
1752 def renamed(self):
1753 rp = self._repo.dirstate.copied(self._path)
1753 rp = self._repo.dirstate.copied(self._path)
1754 if not rp:
1754 if not rp:
1755 return None
1755 return None
1756 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1756 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1757
1757
1758 def size(self):
1758 def size(self):
1759 return self._repo.wvfs.lstat(self._path).st_size
1759 return self._repo.wvfs.lstat(self._path).st_size
1760 def date(self):
1760 def date(self):
1761 t, tz = self._changectx.date()
1761 t, tz = self._changectx.date()
1762 try:
1762 try:
1763 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
1763 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
1764 except OSError as err:
1764 except OSError as err:
1765 if err.errno != errno.ENOENT:
1765 if err.errno != errno.ENOENT:
1766 raise
1766 raise
1767 return (t, tz)
1767 return (t, tz)
1768
1768
1769 def exists(self):
1769 def exists(self):
1770 return self._repo.wvfs.exists(self._path)
1770 return self._repo.wvfs.exists(self._path)
1771
1771
1772 def lexists(self):
1772 def lexists(self):
1773 return self._repo.wvfs.lexists(self._path)
1773 return self._repo.wvfs.lexists(self._path)
1774
1774
1775 def audit(self):
1775 def audit(self):
1776 return self._repo.wvfs.audit(self._path)
1776 return self._repo.wvfs.audit(self._path)
1777
1777
1778 def cmp(self, fctx):
1778 def cmp(self, fctx):
1779 """compare with other file context
1779 """compare with other file context
1780
1780
1781 returns True if different than fctx.
1781 returns True if different than fctx.
1782 """
1782 """
1783 # fctx should be a filectx (not a workingfilectx)
1783 # fctx should be a filectx (not a workingfilectx)
1784 # invert comparison to reuse the same code path
1784 # invert comparison to reuse the same code path
1785 return fctx.cmp(self)
1785 return fctx.cmp(self)
1786
1786
1787 def remove(self, ignoremissing=False):
1787 def remove(self, ignoremissing=False):
1788 """wraps unlink for a repo's working directory"""
1788 """wraps unlink for a repo's working directory"""
1789 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing)
1789 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing)
1790
1790
1791 def write(self, data, flags, backgroundclose=False, **kwargs):
1791 def write(self, data, flags, backgroundclose=False, **kwargs):
1792 """wraps repo.wwrite"""
1792 """wraps repo.wwrite"""
1793 self._repo.wwrite(self._path, data, flags,
1793 self._repo.wwrite(self._path, data, flags,
1794 backgroundclose=backgroundclose,
1794 backgroundclose=backgroundclose,
1795 **kwargs)
1795 **kwargs)
1796
1796
1797 def markcopied(self, src):
1797 def markcopied(self, src):
1798 """marks this file a copy of `src`"""
1798 """marks this file a copy of `src`"""
1799 if self._repo.dirstate[self._path] in "nma":
1799 if self._repo.dirstate[self._path] in "nma":
1800 self._repo.dirstate.copy(src, self._path)
1800 self._repo.dirstate.copy(src, self._path)
1801
1801
1802 def clearunknown(self):
1802 def clearunknown(self):
1803 """Removes conflicting items in the working directory so that
1803 """Removes conflicting items in the working directory so that
1804 ``write()`` can be called successfully.
1804 ``write()`` can be called successfully.
1805 """
1805 """
1806 wvfs = self._repo.wvfs
1806 wvfs = self._repo.wvfs
1807 f = self._path
1807 f = self._path
1808 wvfs.audit(f)
1808 wvfs.audit(f)
1809 if wvfs.isdir(f) and not wvfs.islink(f):
1809 if wvfs.isdir(f) and not wvfs.islink(f):
1810 wvfs.rmtree(f, forcibly=True)
1810 wvfs.rmtree(f, forcibly=True)
1811 for p in reversed(list(util.finddirs(f))):
1811 if self._repo.ui.configbool('experimental', 'merge.checkpathconflicts'):
1812 if wvfs.isfileorlink(p):
1812 for p in reversed(list(util.finddirs(f))):
1813 wvfs.unlink(p)
1813 if wvfs.isfileorlink(p):
1814 break
1814 wvfs.unlink(p)
1815 break
1815
1816
1816 def setflags(self, l, x):
1817 def setflags(self, l, x):
1817 self._repo.wvfs.setflags(self._path, l, x)
1818 self._repo.wvfs.setflags(self._path, l, x)
1818
1819
1819 class overlayworkingctx(committablectx):
1820 class overlayworkingctx(committablectx):
1820 """Wraps another mutable context with a write-back cache that can be
1821 """Wraps another mutable context with a write-back cache that can be
1821 converted into a commit context.
1822 converted into a commit context.
1822
1823
1823 self._cache[path] maps to a dict with keys: {
1824 self._cache[path] maps to a dict with keys: {
1824 'exists': bool?
1825 'exists': bool?
1825 'date': date?
1826 'date': date?
1826 'data': str?
1827 'data': str?
1827 'flags': str?
1828 'flags': str?
1828 'copied': str? (path or None)
1829 'copied': str? (path or None)
1829 }
1830 }
1830 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1831 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1831 is `False`, the file was deleted.
1832 is `False`, the file was deleted.
1832 """
1833 """
1833
1834
1834 def __init__(self, repo):
1835 def __init__(self, repo):
1835 super(overlayworkingctx, self).__init__(repo)
1836 super(overlayworkingctx, self).__init__(repo)
1836 self._repo = repo
1837 self._repo = repo
1837 self.clean()
1838 self.clean()
1838
1839
1839 def setbase(self, wrappedctx):
1840 def setbase(self, wrappedctx):
1840 self._wrappedctx = wrappedctx
1841 self._wrappedctx = wrappedctx
1841 self._parents = [wrappedctx]
1842 self._parents = [wrappedctx]
1842 # Drop old manifest cache as it is now out of date.
1843 # Drop old manifest cache as it is now out of date.
1843 # This is necessary when, e.g., rebasing several nodes with one
1844 # This is necessary when, e.g., rebasing several nodes with one
1844 # ``overlayworkingctx`` (e.g. with --collapse).
1845 # ``overlayworkingctx`` (e.g. with --collapse).
1845 util.clearcachedproperty(self, '_manifest')
1846 util.clearcachedproperty(self, '_manifest')
1846
1847
1847 def data(self, path):
1848 def data(self, path):
1848 if self.isdirty(path):
1849 if self.isdirty(path):
1849 if self._cache[path]['exists']:
1850 if self._cache[path]['exists']:
1850 if self._cache[path]['data']:
1851 if self._cache[path]['data']:
1851 return self._cache[path]['data']
1852 return self._cache[path]['data']
1852 else:
1853 else:
1853 # Must fallback here, too, because we only set flags.
1854 # Must fallback here, too, because we only set flags.
1854 return self._wrappedctx[path].data()
1855 return self._wrappedctx[path].data()
1855 else:
1856 else:
1856 raise error.ProgrammingError("No such file or directory: %s" %
1857 raise error.ProgrammingError("No such file or directory: %s" %
1857 path)
1858 path)
1858 else:
1859 else:
1859 return self._wrappedctx[path].data()
1860 return self._wrappedctx[path].data()
1860
1861
1861 @propertycache
1862 @propertycache
1862 def _manifest(self):
1863 def _manifest(self):
1863 parents = self.parents()
1864 parents = self.parents()
1864 man = parents[0].manifest().copy()
1865 man = parents[0].manifest().copy()
1865
1866
1866 flag = self._flagfunc
1867 flag = self._flagfunc
1867 for path in self.added():
1868 for path in self.added():
1868 man[path] = addednodeid
1869 man[path] = addednodeid
1869 man.setflag(path, flag(path))
1870 man.setflag(path, flag(path))
1870 for path in self.modified():
1871 for path in self.modified():
1871 man[path] = modifiednodeid
1872 man[path] = modifiednodeid
1872 man.setflag(path, flag(path))
1873 man.setflag(path, flag(path))
1873 for path in self.removed():
1874 for path in self.removed():
1874 del man[path]
1875 del man[path]
1875 return man
1876 return man
1876
1877
1877 @propertycache
1878 @propertycache
1878 def _flagfunc(self):
1879 def _flagfunc(self):
1879 def f(path):
1880 def f(path):
1880 return self._cache[path]['flags']
1881 return self._cache[path]['flags']
1881 return f
1882 return f
1882
1883
1883 def files(self):
1884 def files(self):
1884 return sorted(self.added() + self.modified() + self.removed())
1885 return sorted(self.added() + self.modified() + self.removed())
1885
1886
1886 def modified(self):
1887 def modified(self):
1887 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1888 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1888 self._existsinparent(f)]
1889 self._existsinparent(f)]
1889
1890
1890 def added(self):
1891 def added(self):
1891 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1892 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1892 not self._existsinparent(f)]
1893 not self._existsinparent(f)]
1893
1894
1894 def removed(self):
1895 def removed(self):
1895 return [f for f in self._cache.keys() if
1896 return [f for f in self._cache.keys() if
1896 not self._cache[f]['exists'] and self._existsinparent(f)]
1897 not self._cache[f]['exists'] and self._existsinparent(f)]
1897
1898
1898 def isinmemory(self):
1899 def isinmemory(self):
1899 return True
1900 return True
1900
1901
1901 def filedate(self, path):
1902 def filedate(self, path):
1902 if self.isdirty(path):
1903 if self.isdirty(path):
1903 return self._cache[path]['date']
1904 return self._cache[path]['date']
1904 else:
1905 else:
1905 return self._wrappedctx[path].date()
1906 return self._wrappedctx[path].date()
1906
1907
1907 def markcopied(self, path, origin):
1908 def markcopied(self, path, origin):
1908 if self.isdirty(path):
1909 if self.isdirty(path):
1909 self._cache[path]['copied'] = origin
1910 self._cache[path]['copied'] = origin
1910 else:
1911 else:
1911 raise error.ProgrammingError('markcopied() called on clean context')
1912 raise error.ProgrammingError('markcopied() called on clean context')
1912
1913
1913 def copydata(self, path):
1914 def copydata(self, path):
1914 if self.isdirty(path):
1915 if self.isdirty(path):
1915 return self._cache[path]['copied']
1916 return self._cache[path]['copied']
1916 else:
1917 else:
1917 raise error.ProgrammingError('copydata() called on clean context')
1918 raise error.ProgrammingError('copydata() called on clean context')
1918
1919
1919 def flags(self, path):
1920 def flags(self, path):
1920 if self.isdirty(path):
1921 if self.isdirty(path):
1921 if self._cache[path]['exists']:
1922 if self._cache[path]['exists']:
1922 return self._cache[path]['flags']
1923 return self._cache[path]['flags']
1923 else:
1924 else:
1924 raise error.ProgrammingError("No such file or directory: %s" %
1925 raise error.ProgrammingError("No such file or directory: %s" %
1925 self._path)
1926 self._path)
1926 else:
1927 else:
1927 return self._wrappedctx[path].flags()
1928 return self._wrappedctx[path].flags()
1928
1929
1929 def _existsinparent(self, path):
1930 def _existsinparent(self, path):
1930 try:
1931 try:
1931 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
1932 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
1932 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
1933 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
1933 # with an ``exists()`` function.
1934 # with an ``exists()`` function.
1934 self._wrappedctx[path]
1935 self._wrappedctx[path]
1935 return True
1936 return True
1936 except error.ManifestLookupError:
1937 except error.ManifestLookupError:
1937 return False
1938 return False
1938
1939
1939 def _auditconflicts(self, path):
1940 def _auditconflicts(self, path):
1940 """Replicates conflict checks done by wvfs.write().
1941 """Replicates conflict checks done by wvfs.write().
1941
1942
1942 Since we never write to the filesystem and never call `applyupdates` in
1943 Since we never write to the filesystem and never call `applyupdates` in
1943 IMM, we'll never check that a path is actually writable -- e.g., because
1944 IMM, we'll never check that a path is actually writable -- e.g., because
1944 it adds `a/foo`, but `a` is actually a file in the other commit.
1945 it adds `a/foo`, but `a` is actually a file in the other commit.
1945 """
1946 """
1946 def fail(path, component):
1947 def fail(path, component):
1947 # p1() is the base and we're receiving "writes" for p2()'s
1948 # p1() is the base and we're receiving "writes" for p2()'s
1948 # files.
1949 # files.
1949 if 'l' in self.p1()[component].flags():
1950 if 'l' in self.p1()[component].flags():
1950 raise error.Abort("error: %s conflicts with symlink %s "
1951 raise error.Abort("error: %s conflicts with symlink %s "
1951 "in %s." % (path, component,
1952 "in %s." % (path, component,
1952 self.p1().rev()))
1953 self.p1().rev()))
1953 else:
1954 else:
1954 raise error.Abort("error: '%s' conflicts with file '%s' in "
1955 raise error.Abort("error: '%s' conflicts with file '%s' in "
1955 "%s." % (path, component,
1956 "%s." % (path, component,
1956 self.p1().rev()))
1957 self.p1().rev()))
1957
1958
1958 # Test that each new directory to be created to write this path from p2
1959 # Test that each new directory to be created to write this path from p2
1959 # is not a file in p1.
1960 # is not a file in p1.
1960 components = path.split('/')
1961 components = path.split('/')
1961 for i in xrange(len(components)):
1962 for i in xrange(len(components)):
1962 component = "/".join(components[0:i])
1963 component = "/".join(components[0:i])
1963 if component in self.p1():
1964 if component in self.p1():
1964 fail(path, component)
1965 fail(path, component)
1965
1966
1966 # Test the other direction -- that this path from p2 isn't a directory
1967 # Test the other direction -- that this path from p2 isn't a directory
1967 # in p1 (test that p1 doesn't any paths matching `path/*`).
1968 # in p1 (test that p1 doesn't any paths matching `path/*`).
1968 match = matchmod.match('/', '', [path + '/'], default=b'relpath')
1969 match = matchmod.match('/', '', [path + '/'], default=b'relpath')
1969 matches = self.p1().manifest().matches(match)
1970 matches = self.p1().manifest().matches(match)
1970 if len(matches) > 0:
1971 if len(matches) > 0:
1971 if len(matches) == 1 and matches.keys()[0] == path:
1972 if len(matches) == 1 and matches.keys()[0] == path:
1972 return
1973 return
1973 raise error.Abort("error: file '%s' cannot be written because "
1974 raise error.Abort("error: file '%s' cannot be written because "
1974 " '%s/' is a folder in %s (containing %d "
1975 " '%s/' is a folder in %s (containing %d "
1975 "entries: %s)"
1976 "entries: %s)"
1976 % (path, path, self.p1(), len(matches),
1977 % (path, path, self.p1(), len(matches),
1977 ', '.join(matches.keys())))
1978 ', '.join(matches.keys())))
1978
1979
1979 def write(self, path, data, flags='', **kwargs):
1980 def write(self, path, data, flags='', **kwargs):
1980 if data is None:
1981 if data is None:
1981 raise error.ProgrammingError("data must be non-None")
1982 raise error.ProgrammingError("data must be non-None")
1982 self._auditconflicts(path)
1983 self._auditconflicts(path)
1983 self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
1984 self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
1984 flags=flags)
1985 flags=flags)
1985
1986
1986 def setflags(self, path, l, x):
1987 def setflags(self, path, l, x):
1987 self._markdirty(path, exists=True, date=dateutil.makedate(),
1988 self._markdirty(path, exists=True, date=dateutil.makedate(),
1988 flags=(l and 'l' or '') + (x and 'x' or ''))
1989 flags=(l and 'l' or '') + (x and 'x' or ''))
1989
1990
1990 def remove(self, path):
1991 def remove(self, path):
1991 self._markdirty(path, exists=False)
1992 self._markdirty(path, exists=False)
1992
1993
1993 def exists(self, path):
1994 def exists(self, path):
1994 """exists behaves like `lexists`, but needs to follow symlinks and
1995 """exists behaves like `lexists`, but needs to follow symlinks and
1995 return False if they are broken.
1996 return False if they are broken.
1996 """
1997 """
1997 if self.isdirty(path):
1998 if self.isdirty(path):
1998 # If this path exists and is a symlink, "follow" it by calling
1999 # If this path exists and is a symlink, "follow" it by calling
1999 # exists on the destination path.
2000 # exists on the destination path.
2000 if (self._cache[path]['exists'] and
2001 if (self._cache[path]['exists'] and
2001 'l' in self._cache[path]['flags']):
2002 'l' in self._cache[path]['flags']):
2002 return self.exists(self._cache[path]['data'].strip())
2003 return self.exists(self._cache[path]['data'].strip())
2003 else:
2004 else:
2004 return self._cache[path]['exists']
2005 return self._cache[path]['exists']
2005
2006
2006 return self._existsinparent(path)
2007 return self._existsinparent(path)
2007
2008
2008 def lexists(self, path):
2009 def lexists(self, path):
2009 """lexists returns True if the path exists"""
2010 """lexists returns True if the path exists"""
2010 if self.isdirty(path):
2011 if self.isdirty(path):
2011 return self._cache[path]['exists']
2012 return self._cache[path]['exists']
2012
2013
2013 return self._existsinparent(path)
2014 return self._existsinparent(path)
2014
2015
2015 def size(self, path):
2016 def size(self, path):
2016 if self.isdirty(path):
2017 if self.isdirty(path):
2017 if self._cache[path]['exists']:
2018 if self._cache[path]['exists']:
2018 return len(self._cache[path]['data'])
2019 return len(self._cache[path]['data'])
2019 else:
2020 else:
2020 raise error.ProgrammingError("No such file or directory: %s" %
2021 raise error.ProgrammingError("No such file or directory: %s" %
2021 self._path)
2022 self._path)
2022 return self._wrappedctx[path].size()
2023 return self._wrappedctx[path].size()
2023
2024
2024 def tomemctx(self, text, branch=None, extra=None, date=None, parents=None,
2025 def tomemctx(self, text, branch=None, extra=None, date=None, parents=None,
2025 user=None, editor=None):
2026 user=None, editor=None):
2026 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2027 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2027 committed.
2028 committed.
2028
2029
2029 ``text`` is the commit message.
2030 ``text`` is the commit message.
2030 ``parents`` (optional) are rev numbers.
2031 ``parents`` (optional) are rev numbers.
2031 """
2032 """
2032 # Default parents to the wrapped contexts' if not passed.
2033 # Default parents to the wrapped contexts' if not passed.
2033 if parents is None:
2034 if parents is None:
2034 parents = self._wrappedctx.parents()
2035 parents = self._wrappedctx.parents()
2035 if len(parents) == 1:
2036 if len(parents) == 1:
2036 parents = (parents[0], None)
2037 parents = (parents[0], None)
2037
2038
2038 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2039 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2039 if parents[1] is None:
2040 if parents[1] is None:
2040 parents = (self._repo[parents[0]], None)
2041 parents = (self._repo[parents[0]], None)
2041 else:
2042 else:
2042 parents = (self._repo[parents[0]], self._repo[parents[1]])
2043 parents = (self._repo[parents[0]], self._repo[parents[1]])
2043
2044
2044 files = self._cache.keys()
2045 files = self._cache.keys()
2045 def getfile(repo, memctx, path):
2046 def getfile(repo, memctx, path):
2046 if self._cache[path]['exists']:
2047 if self._cache[path]['exists']:
2047 return memfilectx(repo, memctx, path,
2048 return memfilectx(repo, memctx, path,
2048 self._cache[path]['data'],
2049 self._cache[path]['data'],
2049 'l' in self._cache[path]['flags'],
2050 'l' in self._cache[path]['flags'],
2050 'x' in self._cache[path]['flags'],
2051 'x' in self._cache[path]['flags'],
2051 self._cache[path]['copied'])
2052 self._cache[path]['copied'])
2052 else:
2053 else:
2053 # Returning None, but including the path in `files`, is
2054 # Returning None, but including the path in `files`, is
2054 # necessary for memctx to register a deletion.
2055 # necessary for memctx to register a deletion.
2055 return None
2056 return None
2056 return memctx(self._repo, parents, text, files, getfile, date=date,
2057 return memctx(self._repo, parents, text, files, getfile, date=date,
2057 extra=extra, user=user, branch=branch, editor=editor)
2058 extra=extra, user=user, branch=branch, editor=editor)
2058
2059
2059 def isdirty(self, path):
2060 def isdirty(self, path):
2060 return path in self._cache
2061 return path in self._cache
2061
2062
2062 def isempty(self):
2063 def isempty(self):
2063 # We need to discard any keys that are actually clean before the empty
2064 # We need to discard any keys that are actually clean before the empty
2064 # commit check.
2065 # commit check.
2065 self._compact()
2066 self._compact()
2066 return len(self._cache) == 0
2067 return len(self._cache) == 0
2067
2068
2068 def clean(self):
2069 def clean(self):
2069 self._cache = {}
2070 self._cache = {}
2070
2071
2071 def _compact(self):
2072 def _compact(self):
2072 """Removes keys from the cache that are actually clean, by comparing
2073 """Removes keys from the cache that are actually clean, by comparing
2073 them with the underlying context.
2074 them with the underlying context.
2074
2075
2075 This can occur during the merge process, e.g. by passing --tool :local
2076 This can occur during the merge process, e.g. by passing --tool :local
2076 to resolve a conflict.
2077 to resolve a conflict.
2077 """
2078 """
2078 keys = []
2079 keys = []
2079 for path in self._cache.keys():
2080 for path in self._cache.keys():
2080 cache = self._cache[path]
2081 cache = self._cache[path]
2081 try:
2082 try:
2082 underlying = self._wrappedctx[path]
2083 underlying = self._wrappedctx[path]
2083 if (underlying.data() == cache['data'] and
2084 if (underlying.data() == cache['data'] and
2084 underlying.flags() == cache['flags']):
2085 underlying.flags() == cache['flags']):
2085 keys.append(path)
2086 keys.append(path)
2086 except error.ManifestLookupError:
2087 except error.ManifestLookupError:
2087 # Path not in the underlying manifest (created).
2088 # Path not in the underlying manifest (created).
2088 continue
2089 continue
2089
2090
2090 for path in keys:
2091 for path in keys:
2091 del self._cache[path]
2092 del self._cache[path]
2092 return keys
2093 return keys
2093
2094
2094 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2095 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2095 self._cache[path] = {
2096 self._cache[path] = {
2096 'exists': exists,
2097 'exists': exists,
2097 'data': data,
2098 'data': data,
2098 'date': date,
2099 'date': date,
2099 'flags': flags,
2100 'flags': flags,
2100 'copied': None,
2101 'copied': None,
2101 }
2102 }
2102
2103
2103 def filectx(self, path, filelog=None):
2104 def filectx(self, path, filelog=None):
2104 return overlayworkingfilectx(self._repo, path, parent=self,
2105 return overlayworkingfilectx(self._repo, path, parent=self,
2105 filelog=filelog)
2106 filelog=filelog)
2106
2107
2107 class overlayworkingfilectx(committablefilectx):
2108 class overlayworkingfilectx(committablefilectx):
2108 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2109 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2109 cache, which can be flushed through later by calling ``flush()``."""
2110 cache, which can be flushed through later by calling ``flush()``."""
2110
2111
2111 def __init__(self, repo, path, filelog=None, parent=None):
2112 def __init__(self, repo, path, filelog=None, parent=None):
2112 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2113 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2113 parent)
2114 parent)
2114 self._repo = repo
2115 self._repo = repo
2115 self._parent = parent
2116 self._parent = parent
2116 self._path = path
2117 self._path = path
2117
2118
2118 def cmp(self, fctx):
2119 def cmp(self, fctx):
2119 return self.data() != fctx.data()
2120 return self.data() != fctx.data()
2120
2121
2121 def changectx(self):
2122 def changectx(self):
2122 return self._parent
2123 return self._parent
2123
2124
2124 def data(self):
2125 def data(self):
2125 return self._parent.data(self._path)
2126 return self._parent.data(self._path)
2126
2127
2127 def date(self):
2128 def date(self):
2128 return self._parent.filedate(self._path)
2129 return self._parent.filedate(self._path)
2129
2130
2130 def exists(self):
2131 def exists(self):
2131 return self.lexists()
2132 return self.lexists()
2132
2133
2133 def lexists(self):
2134 def lexists(self):
2134 return self._parent.exists(self._path)
2135 return self._parent.exists(self._path)
2135
2136
2136 def renamed(self):
2137 def renamed(self):
2137 path = self._parent.copydata(self._path)
2138 path = self._parent.copydata(self._path)
2138 if not path:
2139 if not path:
2139 return None
2140 return None
2140 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2141 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2141
2142
2142 def size(self):
2143 def size(self):
2143 return self._parent.size(self._path)
2144 return self._parent.size(self._path)
2144
2145
2145 def markcopied(self, origin):
2146 def markcopied(self, origin):
2146 self._parent.markcopied(self._path, origin)
2147 self._parent.markcopied(self._path, origin)
2147
2148
2148 def audit(self):
2149 def audit(self):
2149 pass
2150 pass
2150
2151
2151 def flags(self):
2152 def flags(self):
2152 return self._parent.flags(self._path)
2153 return self._parent.flags(self._path)
2153
2154
2154 def setflags(self, islink, isexec):
2155 def setflags(self, islink, isexec):
2155 return self._parent.setflags(self._path, islink, isexec)
2156 return self._parent.setflags(self._path, islink, isexec)
2156
2157
2157 def write(self, data, flags, backgroundclose=False, **kwargs):
2158 def write(self, data, flags, backgroundclose=False, **kwargs):
2158 return self._parent.write(self._path, data, flags, **kwargs)
2159 return self._parent.write(self._path, data, flags, **kwargs)
2159
2160
2160 def remove(self, ignoremissing=False):
2161 def remove(self, ignoremissing=False):
2161 return self._parent.remove(self._path)
2162 return self._parent.remove(self._path)
2162
2163
2163 def clearunknown(self):
2164 def clearunknown(self):
2164 pass
2165 pass
2165
2166
2166 class workingcommitctx(workingctx):
2167 class workingcommitctx(workingctx):
2167 """A workingcommitctx object makes access to data related to
2168 """A workingcommitctx object makes access to data related to
2168 the revision being committed convenient.
2169 the revision being committed convenient.
2169
2170
2170 This hides changes in the working directory, if they aren't
2171 This hides changes in the working directory, if they aren't
2171 committed in this context.
2172 committed in this context.
2172 """
2173 """
2173 def __init__(self, repo, changes,
2174 def __init__(self, repo, changes,
2174 text="", user=None, date=None, extra=None):
2175 text="", user=None, date=None, extra=None):
2175 super(workingctx, self).__init__(repo, text, user, date, extra,
2176 super(workingctx, self).__init__(repo, text, user, date, extra,
2176 changes)
2177 changes)
2177
2178
2178 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2179 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2179 """Return matched files only in ``self._status``
2180 """Return matched files only in ``self._status``
2180
2181
2181 Uncommitted files appear "clean" via this context, even if
2182 Uncommitted files appear "clean" via this context, even if
2182 they aren't actually so in the working directory.
2183 they aren't actually so in the working directory.
2183 """
2184 """
2184 if clean:
2185 if clean:
2185 clean = [f for f in self._manifest if f not in self._changedset]
2186 clean = [f for f in self._manifest if f not in self._changedset]
2186 else:
2187 else:
2187 clean = []
2188 clean = []
2188 return scmutil.status([f for f in self._status.modified if match(f)],
2189 return scmutil.status([f for f in self._status.modified if match(f)],
2189 [f for f in self._status.added if match(f)],
2190 [f for f in self._status.added if match(f)],
2190 [f for f in self._status.removed if match(f)],
2191 [f for f in self._status.removed if match(f)],
2191 [], [], [], clean)
2192 [], [], [], clean)
2192
2193
2193 @propertycache
2194 @propertycache
2194 def _changedset(self):
2195 def _changedset(self):
2195 """Return the set of files changed in this context
2196 """Return the set of files changed in this context
2196 """
2197 """
2197 changed = set(self._status.modified)
2198 changed = set(self._status.modified)
2198 changed.update(self._status.added)
2199 changed.update(self._status.added)
2199 changed.update(self._status.removed)
2200 changed.update(self._status.removed)
2200 return changed
2201 return changed
2201
2202
2202 def makecachingfilectxfn(func):
2203 def makecachingfilectxfn(func):
2203 """Create a filectxfn that caches based on the path.
2204 """Create a filectxfn that caches based on the path.
2204
2205
2205 We can't use util.cachefunc because it uses all arguments as the cache
2206 We can't use util.cachefunc because it uses all arguments as the cache
2206 key and this creates a cycle since the arguments include the repo and
2207 key and this creates a cycle since the arguments include the repo and
2207 memctx.
2208 memctx.
2208 """
2209 """
2209 cache = {}
2210 cache = {}
2210
2211
2211 def getfilectx(repo, memctx, path):
2212 def getfilectx(repo, memctx, path):
2212 if path not in cache:
2213 if path not in cache:
2213 cache[path] = func(repo, memctx, path)
2214 cache[path] = func(repo, memctx, path)
2214 return cache[path]
2215 return cache[path]
2215
2216
2216 return getfilectx
2217 return getfilectx
2217
2218
2218 def memfilefromctx(ctx):
2219 def memfilefromctx(ctx):
2219 """Given a context return a memfilectx for ctx[path]
2220 """Given a context return a memfilectx for ctx[path]
2220
2221
2221 This is a convenience method for building a memctx based on another
2222 This is a convenience method for building a memctx based on another
2222 context.
2223 context.
2223 """
2224 """
2224 def getfilectx(repo, memctx, path):
2225 def getfilectx(repo, memctx, path):
2225 fctx = ctx[path]
2226 fctx = ctx[path]
2226 # this is weird but apparently we only keep track of one parent
2227 # this is weird but apparently we only keep track of one parent
2227 # (why not only store that instead of a tuple?)
2228 # (why not only store that instead of a tuple?)
2228 copied = fctx.renamed()
2229 copied = fctx.renamed()
2229 if copied:
2230 if copied:
2230 copied = copied[0]
2231 copied = copied[0]
2231 return memfilectx(repo, memctx, path, fctx.data(),
2232 return memfilectx(repo, memctx, path, fctx.data(),
2232 islink=fctx.islink(), isexec=fctx.isexec(),
2233 islink=fctx.islink(), isexec=fctx.isexec(),
2233 copied=copied)
2234 copied=copied)
2234
2235
2235 return getfilectx
2236 return getfilectx
2236
2237
2237 def memfilefrompatch(patchstore):
2238 def memfilefrompatch(patchstore):
2238 """Given a patch (e.g. patchstore object) return a memfilectx
2239 """Given a patch (e.g. patchstore object) return a memfilectx
2239
2240
2240 This is a convenience method for building a memctx based on a patchstore.
2241 This is a convenience method for building a memctx based on a patchstore.
2241 """
2242 """
2242 def getfilectx(repo, memctx, path):
2243 def getfilectx(repo, memctx, path):
2243 data, mode, copied = patchstore.getfile(path)
2244 data, mode, copied = patchstore.getfile(path)
2244 if data is None:
2245 if data is None:
2245 return None
2246 return None
2246 islink, isexec = mode
2247 islink, isexec = mode
2247 return memfilectx(repo, memctx, path, data, islink=islink,
2248 return memfilectx(repo, memctx, path, data, islink=islink,
2248 isexec=isexec, copied=copied)
2249 isexec=isexec, copied=copied)
2249
2250
2250 return getfilectx
2251 return getfilectx
2251
2252
2252 class memctx(committablectx):
2253 class memctx(committablectx):
2253 """Use memctx to perform in-memory commits via localrepo.commitctx().
2254 """Use memctx to perform in-memory commits via localrepo.commitctx().
2254
2255
2255 Revision information is supplied at initialization time while
2256 Revision information is supplied at initialization time while
2256 related files data and is made available through a callback
2257 related files data and is made available through a callback
2257 mechanism. 'repo' is the current localrepo, 'parents' is a
2258 mechanism. 'repo' is the current localrepo, 'parents' is a
2258 sequence of two parent revisions identifiers (pass None for every
2259 sequence of two parent revisions identifiers (pass None for every
2259 missing parent), 'text' is the commit message and 'files' lists
2260 missing parent), 'text' is the commit message and 'files' lists
2260 names of files touched by the revision (normalized and relative to
2261 names of files touched by the revision (normalized and relative to
2261 repository root).
2262 repository root).
2262
2263
2263 filectxfn(repo, memctx, path) is a callable receiving the
2264 filectxfn(repo, memctx, path) is a callable receiving the
2264 repository, the current memctx object and the normalized path of
2265 repository, the current memctx object and the normalized path of
2265 requested file, relative to repository root. It is fired by the
2266 requested file, relative to repository root. It is fired by the
2266 commit function for every file in 'files', but calls order is
2267 commit function for every file in 'files', but calls order is
2267 undefined. If the file is available in the revision being
2268 undefined. If the file is available in the revision being
2268 committed (updated or added), filectxfn returns a memfilectx
2269 committed (updated or added), filectxfn returns a memfilectx
2269 object. If the file was removed, filectxfn return None for recent
2270 object. If the file was removed, filectxfn return None for recent
2270 Mercurial. Moved files are represented by marking the source file
2271 Mercurial. Moved files are represented by marking the source file
2271 removed and the new file added with copy information (see
2272 removed and the new file added with copy information (see
2272 memfilectx).
2273 memfilectx).
2273
2274
2274 user receives the committer name and defaults to current
2275 user receives the committer name and defaults to current
2275 repository username, date is the commit date in any format
2276 repository username, date is the commit date in any format
2276 supported by dateutil.parsedate() and defaults to current date, extra
2277 supported by dateutil.parsedate() and defaults to current date, extra
2277 is a dictionary of metadata or is left empty.
2278 is a dictionary of metadata or is left empty.
2278 """
2279 """
2279
2280
2280 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2281 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2281 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2282 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2282 # this field to determine what to do in filectxfn.
2283 # this field to determine what to do in filectxfn.
2283 _returnnoneformissingfiles = True
2284 _returnnoneformissingfiles = True
2284
2285
2285 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2286 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2286 date=None, extra=None, branch=None, editor=False):
2287 date=None, extra=None, branch=None, editor=False):
2287 super(memctx, self).__init__(repo, text, user, date, extra)
2288 super(memctx, self).__init__(repo, text, user, date, extra)
2288 self._rev = None
2289 self._rev = None
2289 self._node = None
2290 self._node = None
2290 parents = [(p or nullid) for p in parents]
2291 parents = [(p or nullid) for p in parents]
2291 p1, p2 = parents
2292 p1, p2 = parents
2292 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
2293 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
2293 files = sorted(set(files))
2294 files = sorted(set(files))
2294 self._files = files
2295 self._files = files
2295 if branch is not None:
2296 if branch is not None:
2296 self._extra['branch'] = encoding.fromlocal(branch)
2297 self._extra['branch'] = encoding.fromlocal(branch)
2297 self.substate = {}
2298 self.substate = {}
2298
2299
2299 if isinstance(filectxfn, patch.filestore):
2300 if isinstance(filectxfn, patch.filestore):
2300 filectxfn = memfilefrompatch(filectxfn)
2301 filectxfn = memfilefrompatch(filectxfn)
2301 elif not callable(filectxfn):
2302 elif not callable(filectxfn):
2302 # if store is not callable, wrap it in a function
2303 # if store is not callable, wrap it in a function
2303 filectxfn = memfilefromctx(filectxfn)
2304 filectxfn = memfilefromctx(filectxfn)
2304
2305
2305 # memoizing increases performance for e.g. vcs convert scenarios.
2306 # memoizing increases performance for e.g. vcs convert scenarios.
2306 self._filectxfn = makecachingfilectxfn(filectxfn)
2307 self._filectxfn = makecachingfilectxfn(filectxfn)
2307
2308
2308 if editor:
2309 if editor:
2309 self._text = editor(self._repo, self, [])
2310 self._text = editor(self._repo, self, [])
2310 self._repo.savecommitmessage(self._text)
2311 self._repo.savecommitmessage(self._text)
2311
2312
2312 def filectx(self, path, filelog=None):
2313 def filectx(self, path, filelog=None):
2313 """get a file context from the working directory
2314 """get a file context from the working directory
2314
2315
2315 Returns None if file doesn't exist and should be removed."""
2316 Returns None if file doesn't exist and should be removed."""
2316 return self._filectxfn(self._repo, self, path)
2317 return self._filectxfn(self._repo, self, path)
2317
2318
2318 def commit(self):
2319 def commit(self):
2319 """commit context to the repo"""
2320 """commit context to the repo"""
2320 return self._repo.commitctx(self)
2321 return self._repo.commitctx(self)
2321
2322
2322 @propertycache
2323 @propertycache
2323 def _manifest(self):
2324 def _manifest(self):
2324 """generate a manifest based on the return values of filectxfn"""
2325 """generate a manifest based on the return values of filectxfn"""
2325
2326
2326 # keep this simple for now; just worry about p1
2327 # keep this simple for now; just worry about p1
2327 pctx = self._parents[0]
2328 pctx = self._parents[0]
2328 man = pctx.manifest().copy()
2329 man = pctx.manifest().copy()
2329
2330
2330 for f in self._status.modified:
2331 for f in self._status.modified:
2331 p1node = nullid
2332 p1node = nullid
2332 p2node = nullid
2333 p2node = nullid
2333 p = pctx[f].parents() # if file isn't in pctx, check p2?
2334 p = pctx[f].parents() # if file isn't in pctx, check p2?
2334 if len(p) > 0:
2335 if len(p) > 0:
2335 p1node = p[0].filenode()
2336 p1node = p[0].filenode()
2336 if len(p) > 1:
2337 if len(p) > 1:
2337 p2node = p[1].filenode()
2338 p2node = p[1].filenode()
2338 man[f] = revlog.hash(self[f].data(), p1node, p2node)
2339 man[f] = revlog.hash(self[f].data(), p1node, p2node)
2339
2340
2340 for f in self._status.added:
2341 for f in self._status.added:
2341 man[f] = revlog.hash(self[f].data(), nullid, nullid)
2342 man[f] = revlog.hash(self[f].data(), nullid, nullid)
2342
2343
2343 for f in self._status.removed:
2344 for f in self._status.removed:
2344 if f in man:
2345 if f in man:
2345 del man[f]
2346 del man[f]
2346
2347
2347 return man
2348 return man
2348
2349
2349 @propertycache
2350 @propertycache
2350 def _status(self):
2351 def _status(self):
2351 """Calculate exact status from ``files`` specified at construction
2352 """Calculate exact status from ``files`` specified at construction
2352 """
2353 """
2353 man1 = self.p1().manifest()
2354 man1 = self.p1().manifest()
2354 p2 = self._parents[1]
2355 p2 = self._parents[1]
2355 # "1 < len(self._parents)" can't be used for checking
2356 # "1 < len(self._parents)" can't be used for checking
2356 # existence of the 2nd parent, because "memctx._parents" is
2357 # existence of the 2nd parent, because "memctx._parents" is
2357 # explicitly initialized by the list, of which length is 2.
2358 # explicitly initialized by the list, of which length is 2.
2358 if p2.node() != nullid:
2359 if p2.node() != nullid:
2359 man2 = p2.manifest()
2360 man2 = p2.manifest()
2360 managing = lambda f: f in man1 or f in man2
2361 managing = lambda f: f in man1 or f in man2
2361 else:
2362 else:
2362 managing = lambda f: f in man1
2363 managing = lambda f: f in man1
2363
2364
2364 modified, added, removed = [], [], []
2365 modified, added, removed = [], [], []
2365 for f in self._files:
2366 for f in self._files:
2366 if not managing(f):
2367 if not managing(f):
2367 added.append(f)
2368 added.append(f)
2368 elif self[f]:
2369 elif self[f]:
2369 modified.append(f)
2370 modified.append(f)
2370 else:
2371 else:
2371 removed.append(f)
2372 removed.append(f)
2372
2373
2373 return scmutil.status(modified, added, removed, [], [], [], [])
2374 return scmutil.status(modified, added, removed, [], [], [], [])
2374
2375
2375 class memfilectx(committablefilectx):
2376 class memfilectx(committablefilectx):
2376 """memfilectx represents an in-memory file to commit.
2377 """memfilectx represents an in-memory file to commit.
2377
2378
2378 See memctx and committablefilectx for more details.
2379 See memctx and committablefilectx for more details.
2379 """
2380 """
2380 def __init__(self, repo, changectx, path, data, islink=False,
2381 def __init__(self, repo, changectx, path, data, islink=False,
2381 isexec=False, copied=None):
2382 isexec=False, copied=None):
2382 """
2383 """
2383 path is the normalized file path relative to repository root.
2384 path is the normalized file path relative to repository root.
2384 data is the file content as a string.
2385 data is the file content as a string.
2385 islink is True if the file is a symbolic link.
2386 islink is True if the file is a symbolic link.
2386 isexec is True if the file is executable.
2387 isexec is True if the file is executable.
2387 copied is the source file path if current file was copied in the
2388 copied is the source file path if current file was copied in the
2388 revision being committed, or None."""
2389 revision being committed, or None."""
2389 super(memfilectx, self).__init__(repo, path, None, changectx)
2390 super(memfilectx, self).__init__(repo, path, None, changectx)
2390 self._data = data
2391 self._data = data
2391 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
2392 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
2392 self._copied = None
2393 self._copied = None
2393 if copied:
2394 if copied:
2394 self._copied = (copied, nullid)
2395 self._copied = (copied, nullid)
2395
2396
2396 def data(self):
2397 def data(self):
2397 return self._data
2398 return self._data
2398
2399
2399 def remove(self, ignoremissing=False):
2400 def remove(self, ignoremissing=False):
2400 """wraps unlink for a repo's working directory"""
2401 """wraps unlink for a repo's working directory"""
2401 # need to figure out what to do here
2402 # need to figure out what to do here
2402 del self._changectx[self._path]
2403 del self._changectx[self._path]
2403
2404
2404 def write(self, data, flags, **kwargs):
2405 def write(self, data, flags, **kwargs):
2405 """wraps repo.wwrite"""
2406 """wraps repo.wwrite"""
2406 self._data = data
2407 self._data = data
2407
2408
2408 class overlayfilectx(committablefilectx):
2409 class overlayfilectx(committablefilectx):
2409 """Like memfilectx but take an original filectx and optional parameters to
2410 """Like memfilectx but take an original filectx and optional parameters to
2410 override parts of it. This is useful when fctx.data() is expensive (i.e.
2411 override parts of it. This is useful when fctx.data() is expensive (i.e.
2411 flag processor is expensive) and raw data, flags, and filenode could be
2412 flag processor is expensive) and raw data, flags, and filenode could be
2412 reused (ex. rebase or mode-only amend a REVIDX_EXTSTORED file).
2413 reused (ex. rebase or mode-only amend a REVIDX_EXTSTORED file).
2413 """
2414 """
2414
2415
2415 def __init__(self, originalfctx, datafunc=None, path=None, flags=None,
2416 def __init__(self, originalfctx, datafunc=None, path=None, flags=None,
2416 copied=None, ctx=None):
2417 copied=None, ctx=None):
2417 """originalfctx: filecontext to duplicate
2418 """originalfctx: filecontext to duplicate
2418
2419
2419 datafunc: None or a function to override data (file content). It is a
2420 datafunc: None or a function to override data (file content). It is a
2420 function to be lazy. path, flags, copied, ctx: None or overridden value
2421 function to be lazy. path, flags, copied, ctx: None or overridden value
2421
2422
2422 copied could be (path, rev), or False. copied could also be just path,
2423 copied could be (path, rev), or False. copied could also be just path,
2423 and will be converted to (path, nullid). This simplifies some callers.
2424 and will be converted to (path, nullid). This simplifies some callers.
2424 """
2425 """
2425
2426
2426 if path is None:
2427 if path is None:
2427 path = originalfctx.path()
2428 path = originalfctx.path()
2428 if ctx is None:
2429 if ctx is None:
2429 ctx = originalfctx.changectx()
2430 ctx = originalfctx.changectx()
2430 ctxmatch = lambda: True
2431 ctxmatch = lambda: True
2431 else:
2432 else:
2432 ctxmatch = lambda: ctx == originalfctx.changectx()
2433 ctxmatch = lambda: ctx == originalfctx.changectx()
2433
2434
2434 repo = originalfctx.repo()
2435 repo = originalfctx.repo()
2435 flog = originalfctx.filelog()
2436 flog = originalfctx.filelog()
2436 super(overlayfilectx, self).__init__(repo, path, flog, ctx)
2437 super(overlayfilectx, self).__init__(repo, path, flog, ctx)
2437
2438
2438 if copied is None:
2439 if copied is None:
2439 copied = originalfctx.renamed()
2440 copied = originalfctx.renamed()
2440 copiedmatch = lambda: True
2441 copiedmatch = lambda: True
2441 else:
2442 else:
2442 if copied and not isinstance(copied, tuple):
2443 if copied and not isinstance(copied, tuple):
2443 # repo._filecommit will recalculate copyrev so nullid is okay
2444 # repo._filecommit will recalculate copyrev so nullid is okay
2444 copied = (copied, nullid)
2445 copied = (copied, nullid)
2445 copiedmatch = lambda: copied == originalfctx.renamed()
2446 copiedmatch = lambda: copied == originalfctx.renamed()
2446
2447
2447 # When data, copied (could affect data), ctx (could affect filelog
2448 # When data, copied (could affect data), ctx (could affect filelog
2448 # parents) are not overridden, rawdata, rawflags, and filenode may be
2449 # parents) are not overridden, rawdata, rawflags, and filenode may be
2449 # reused (repo._filecommit should double check filelog parents).
2450 # reused (repo._filecommit should double check filelog parents).
2450 #
2451 #
2451 # path, flags are not hashed in filelog (but in manifestlog) so they do
2452 # path, flags are not hashed in filelog (but in manifestlog) so they do
2452 # not affect reusable here.
2453 # not affect reusable here.
2453 #
2454 #
2454 # If ctx or copied is overridden to a same value with originalfctx,
2455 # If ctx or copied is overridden to a same value with originalfctx,
2455 # still consider it's reusable. originalfctx.renamed() may be a bit
2456 # still consider it's reusable. originalfctx.renamed() may be a bit
2456 # expensive so it's not called unless necessary. Assuming datafunc is
2457 # expensive so it's not called unless necessary. Assuming datafunc is
2457 # always expensive, do not call it for this "reusable" test.
2458 # always expensive, do not call it for this "reusable" test.
2458 reusable = datafunc is None and ctxmatch() and copiedmatch()
2459 reusable = datafunc is None and ctxmatch() and copiedmatch()
2459
2460
2460 if datafunc is None:
2461 if datafunc is None:
2461 datafunc = originalfctx.data
2462 datafunc = originalfctx.data
2462 if flags is None:
2463 if flags is None:
2463 flags = originalfctx.flags()
2464 flags = originalfctx.flags()
2464
2465
2465 self._datafunc = datafunc
2466 self._datafunc = datafunc
2466 self._flags = flags
2467 self._flags = flags
2467 self._copied = copied
2468 self._copied = copied
2468
2469
2469 if reusable:
2470 if reusable:
2470 # copy extra fields from originalfctx
2471 # copy extra fields from originalfctx
2471 attrs = ['rawdata', 'rawflags', '_filenode', '_filerev']
2472 attrs = ['rawdata', 'rawflags', '_filenode', '_filerev']
2472 for attr_ in attrs:
2473 for attr_ in attrs:
2473 if util.safehasattr(originalfctx, attr_):
2474 if util.safehasattr(originalfctx, attr_):
2474 setattr(self, attr_, getattr(originalfctx, attr_))
2475 setattr(self, attr_, getattr(originalfctx, attr_))
2475
2476
2476 def data(self):
2477 def data(self):
2477 return self._datafunc()
2478 return self._datafunc()
2478
2479
2479 class metadataonlyctx(committablectx):
2480 class metadataonlyctx(committablectx):
2480 """Like memctx but it's reusing the manifest of different commit.
2481 """Like memctx but it's reusing the manifest of different commit.
2481 Intended to be used by lightweight operations that are creating
2482 Intended to be used by lightweight operations that are creating
2482 metadata-only changes.
2483 metadata-only changes.
2483
2484
2484 Revision information is supplied at initialization time. 'repo' is the
2485 Revision information is supplied at initialization time. 'repo' is the
2485 current localrepo, 'ctx' is original revision which manifest we're reuisng
2486 current localrepo, 'ctx' is original revision which manifest we're reuisng
2486 'parents' is a sequence of two parent revisions identifiers (pass None for
2487 'parents' is a sequence of two parent revisions identifiers (pass None for
2487 every missing parent), 'text' is the commit.
2488 every missing parent), 'text' is the commit.
2488
2489
2489 user receives the committer name and defaults to current repository
2490 user receives the committer name and defaults to current repository
2490 username, date is the commit date in any format supported by
2491 username, date is the commit date in any format supported by
2491 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2492 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2492 metadata or is left empty.
2493 metadata or is left empty.
2493 """
2494 """
2494 def __new__(cls, repo, originalctx, *args, **kwargs):
2495 def __new__(cls, repo, originalctx, *args, **kwargs):
2495 return super(metadataonlyctx, cls).__new__(cls, repo)
2496 return super(metadataonlyctx, cls).__new__(cls, repo)
2496
2497
2497 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2498 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2498 date=None, extra=None, editor=False):
2499 date=None, extra=None, editor=False):
2499 if text is None:
2500 if text is None:
2500 text = originalctx.description()
2501 text = originalctx.description()
2501 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2502 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2502 self._rev = None
2503 self._rev = None
2503 self._node = None
2504 self._node = None
2504 self._originalctx = originalctx
2505 self._originalctx = originalctx
2505 self._manifestnode = originalctx.manifestnode()
2506 self._manifestnode = originalctx.manifestnode()
2506 if parents is None:
2507 if parents is None:
2507 parents = originalctx.parents()
2508 parents = originalctx.parents()
2508 else:
2509 else:
2509 parents = [repo[p] for p in parents if p is not None]
2510 parents = [repo[p] for p in parents if p is not None]
2510 parents = parents[:]
2511 parents = parents[:]
2511 while len(parents) < 2:
2512 while len(parents) < 2:
2512 parents.append(repo[nullid])
2513 parents.append(repo[nullid])
2513 p1, p2 = self._parents = parents
2514 p1, p2 = self._parents = parents
2514
2515
2515 # sanity check to ensure that the reused manifest parents are
2516 # sanity check to ensure that the reused manifest parents are
2516 # manifests of our commit parents
2517 # manifests of our commit parents
2517 mp1, mp2 = self.manifestctx().parents
2518 mp1, mp2 = self.manifestctx().parents
2518 if p1 != nullid and p1.manifestnode() != mp1:
2519 if p1 != nullid and p1.manifestnode() != mp1:
2519 raise RuntimeError('can\'t reuse the manifest: '
2520 raise RuntimeError('can\'t reuse the manifest: '
2520 'its p1 doesn\'t match the new ctx p1')
2521 'its p1 doesn\'t match the new ctx p1')
2521 if p2 != nullid and p2.manifestnode() != mp2:
2522 if p2 != nullid and p2.manifestnode() != mp2:
2522 raise RuntimeError('can\'t reuse the manifest: '
2523 raise RuntimeError('can\'t reuse the manifest: '
2523 'its p2 doesn\'t match the new ctx p2')
2524 'its p2 doesn\'t match the new ctx p2')
2524
2525
2525 self._files = originalctx.files()
2526 self._files = originalctx.files()
2526 self.substate = {}
2527 self.substate = {}
2527
2528
2528 if editor:
2529 if editor:
2529 self._text = editor(self._repo, self, [])
2530 self._text = editor(self._repo, self, [])
2530 self._repo.savecommitmessage(self._text)
2531 self._repo.savecommitmessage(self._text)
2531
2532
2532 def manifestnode(self):
2533 def manifestnode(self):
2533 return self._manifestnode
2534 return self._manifestnode
2534
2535
2535 @property
2536 @property
2536 def _manifestctx(self):
2537 def _manifestctx(self):
2537 return self._repo.manifestlog[self._manifestnode]
2538 return self._repo.manifestlog[self._manifestnode]
2538
2539
2539 def filectx(self, path, filelog=None):
2540 def filectx(self, path, filelog=None):
2540 return self._originalctx.filectx(path, filelog=filelog)
2541 return self._originalctx.filectx(path, filelog=filelog)
2541
2542
2542 def commit(self):
2543 def commit(self):
2543 """commit context to the repo"""
2544 """commit context to the repo"""
2544 return self._repo.commitctx(self)
2545 return self._repo.commitctx(self)
2545
2546
2546 @property
2547 @property
2547 def _manifest(self):
2548 def _manifest(self):
2548 return self._originalctx.manifest()
2549 return self._originalctx.manifest()
2549
2550
2550 @propertycache
2551 @propertycache
2551 def _status(self):
2552 def _status(self):
2552 """Calculate exact status from ``files`` specified in the ``origctx``
2553 """Calculate exact status from ``files`` specified in the ``origctx``
2553 and parents manifests.
2554 and parents manifests.
2554 """
2555 """
2555 man1 = self.p1().manifest()
2556 man1 = self.p1().manifest()
2556 p2 = self._parents[1]
2557 p2 = self._parents[1]
2557 # "1 < len(self._parents)" can't be used for checking
2558 # "1 < len(self._parents)" can't be used for checking
2558 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2559 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2559 # explicitly initialized by the list, of which length is 2.
2560 # explicitly initialized by the list, of which length is 2.
2560 if p2.node() != nullid:
2561 if p2.node() != nullid:
2561 man2 = p2.manifest()
2562 man2 = p2.manifest()
2562 managing = lambda f: f in man1 or f in man2
2563 managing = lambda f: f in man1 or f in man2
2563 else:
2564 else:
2564 managing = lambda f: f in man1
2565 managing = lambda f: f in man1
2565
2566
2566 modified, added, removed = [], [], []
2567 modified, added, removed = [], [], []
2567 for f in self._files:
2568 for f in self._files:
2568 if not managing(f):
2569 if not managing(f):
2569 added.append(f)
2570 added.append(f)
2570 elif f in self:
2571 elif f in self:
2571 modified.append(f)
2572 modified.append(f)
2572 else:
2573 else:
2573 removed.append(f)
2574 removed.append(f)
2574
2575
2575 return scmutil.status(modified, added, removed, [], [], [], [])
2576 return scmutil.status(modified, added, removed, [], [], [], [])
2576
2577
2577 class arbitraryfilectx(object):
2578 class arbitraryfilectx(object):
2578 """Allows you to use filectx-like functions on a file in an arbitrary
2579 """Allows you to use filectx-like functions on a file in an arbitrary
2579 location on disk, possibly not in the working directory.
2580 location on disk, possibly not in the working directory.
2580 """
2581 """
2581 def __init__(self, path, repo=None):
2582 def __init__(self, path, repo=None):
2582 # Repo is optional because contrib/simplemerge uses this class.
2583 # Repo is optional because contrib/simplemerge uses this class.
2583 self._repo = repo
2584 self._repo = repo
2584 self._path = path
2585 self._path = path
2585
2586
2586 def cmp(self, fctx):
2587 def cmp(self, fctx):
2587 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
2588 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
2588 # path if either side is a symlink.
2589 # path if either side is a symlink.
2589 symlinks = ('l' in self.flags() or 'l' in fctx.flags())
2590 symlinks = ('l' in self.flags() or 'l' in fctx.flags())
2590 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
2591 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
2591 # Add a fast-path for merge if both sides are disk-backed.
2592 # Add a fast-path for merge if both sides are disk-backed.
2592 # Note that filecmp uses the opposite return values (True if same)
2593 # Note that filecmp uses the opposite return values (True if same)
2593 # from our cmp functions (True if different).
2594 # from our cmp functions (True if different).
2594 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
2595 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
2595 return self.data() != fctx.data()
2596 return self.data() != fctx.data()
2596
2597
2597 def path(self):
2598 def path(self):
2598 return self._path
2599 return self._path
2599
2600
2600 def flags(self):
2601 def flags(self):
2601 return ''
2602 return ''
2602
2603
2603 def data(self):
2604 def data(self):
2604 return util.readfile(self._path)
2605 return util.readfile(self._path)
2605
2606
2606 def decodeddata(self):
2607 def decodeddata(self):
2607 with open(self._path, "rb") as f:
2608 with open(self._path, "rb") as f:
2608 return f.read()
2609 return f.read()
2609
2610
2610 def remove(self):
2611 def remove(self):
2611 util.unlink(self._path)
2612 util.unlink(self._path)
2612
2613
2613 def write(self, data, flags, **kwargs):
2614 def write(self, data, flags, **kwargs):
2614 assert not flags
2615 assert not flags
2615 with open(self._path, "w") as f:
2616 with open(self._path, "w") as f:
2616 f.write(data)
2617 f.write(data)
@@ -1,237 +1,236 b''
1 $ hg init
1 $ hg init
2
2
3 audit of .hg
3 audit of .hg
4
4
5 $ hg add .hg/00changelog.i
5 $ hg add .hg/00changelog.i
6 abort: path contains illegal component: .hg/00changelog.i
6 abort: path contains illegal component: .hg/00changelog.i
7 [255]
7 [255]
8
8
9 #if symlink
9 #if symlink
10
10
11 Symlinks
11 Symlinks
12
12
13 $ mkdir a
13 $ mkdir a
14 $ echo a > a/a
14 $ echo a > a/a
15 $ hg ci -Ama
15 $ hg ci -Ama
16 adding a/a
16 adding a/a
17 $ ln -s a b
17 $ ln -s a b
18 $ echo b > a/b
18 $ echo b > a/b
19 $ hg add b/b
19 $ hg add b/b
20 abort: path 'b/b' traverses symbolic link 'b'
20 abort: path 'b/b' traverses symbolic link 'b'
21 [255]
21 [255]
22 $ hg add b
22 $ hg add b
23
23
24 should still fail - maybe
24 should still fail - maybe
25
25
26 $ hg add b/b
26 $ hg add b/b
27 abort: path 'b/b' traverses symbolic link 'b'
27 abort: path 'b/b' traverses symbolic link 'b'
28 [255]
28 [255]
29
29
30 $ hg commit -m 'add symlink b'
30 $ hg commit -m 'add symlink b'
31
31
32
32
33 Test symlink traversing when accessing history:
33 Test symlink traversing when accessing history:
34 -----------------------------------------------
34 -----------------------------------------------
35
35
36 (build a changeset where the path exists as a directory)
36 (build a changeset where the path exists as a directory)
37
37
38 $ hg up 0
38 $ hg up 0
39 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
39 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
40 $ mkdir b
40 $ mkdir b
41 $ echo c > b/a
41 $ echo c > b/a
42 $ hg add b/a
42 $ hg add b/a
43 $ hg ci -m 'add directory b'
43 $ hg ci -m 'add directory b'
44 created new head
44 created new head
45
45
46 Test that hg cat does not do anything wrong the working copy has 'b' as directory
46 Test that hg cat does not do anything wrong the working copy has 'b' as directory
47
47
48 $ hg cat b/a
48 $ hg cat b/a
49 c
49 c
50 $ hg cat -r "desc(directory)" b/a
50 $ hg cat -r "desc(directory)" b/a
51 c
51 c
52 $ hg cat -r "desc(symlink)" b/a
52 $ hg cat -r "desc(symlink)" b/a
53 b/a: no such file in rev bc151a1f53bd
53 b/a: no such file in rev bc151a1f53bd
54 [1]
54 [1]
55
55
56 Test that hg cat does not do anything wrong the working copy has 'b' as a symlink (issue4749)
56 Test that hg cat does not do anything wrong the working copy has 'b' as a symlink (issue4749)
57
57
58 $ hg up 'desc(symlink)'
58 $ hg up 'desc(symlink)'
59 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
59 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
60 $ hg cat b/a
60 $ hg cat b/a
61 b/a: no such file in rev bc151a1f53bd
61 b/a: no such file in rev bc151a1f53bd
62 [1]
62 [1]
63 $ hg cat -r "desc(directory)" b/a
63 $ hg cat -r "desc(directory)" b/a
64 c
64 c
65 $ hg cat -r "desc(symlink)" b/a
65 $ hg cat -r "desc(symlink)" b/a
66 b/a: no such file in rev bc151a1f53bd
66 b/a: no such file in rev bc151a1f53bd
67 [1]
67 [1]
68
68
69 #endif
69 #endif
70
70
71
71
72 unbundle tampered bundle
72 unbundle tampered bundle
73
73
74 $ hg init target
74 $ hg init target
75 $ cd target
75 $ cd target
76 $ hg unbundle "$TESTDIR/bundles/tampered.hg"
76 $ hg unbundle "$TESTDIR/bundles/tampered.hg"
77 adding changesets
77 adding changesets
78 adding manifests
78 adding manifests
79 adding file changes
79 adding file changes
80 added 5 changesets with 6 changes to 6 files (+4 heads)
80 added 5 changesets with 6 changes to 6 files (+4 heads)
81 new changesets b7da9bf6b037:fc1393d727bc
81 new changesets b7da9bf6b037:fc1393d727bc
82 (run 'hg heads' to see heads, 'hg merge' to merge)
82 (run 'hg heads' to see heads, 'hg merge' to merge)
83
83
84 attack .hg/test
84 attack .hg/test
85
85
86 $ hg manifest -r0
86 $ hg manifest -r0
87 .hg/test
87 .hg/test
88 $ hg update -Cr0
88 $ hg update -Cr0
89 abort: path contains illegal component: .hg/test
89 abort: path contains illegal component: .hg/test
90 [255]
90 [255]
91
91
92 attack foo/.hg/test
92 attack foo/.hg/test
93
93
94 $ hg manifest -r1
94 $ hg manifest -r1
95 foo/.hg/test
95 foo/.hg/test
96 $ hg update -Cr1
96 $ hg update -Cr1
97 abort: path 'foo/.hg/test' is inside nested repo 'foo'
97 abort: path 'foo/.hg/test' is inside nested repo 'foo'
98 [255]
98 [255]
99
99
100 attack back/test where back symlinks to ..
100 attack back/test where back symlinks to ..
101
101
102 $ hg manifest -r2
102 $ hg manifest -r2
103 back
103 back
104 back/test
104 back/test
105 #if symlink
105 #if symlink
106 $ hg update -Cr2
106 $ hg update -Cr2
107 abort: path 'back/test' traverses symbolic link 'back'
107 abort: path 'back/test' traverses symbolic link 'back'
108 [255]
108 [255]
109 #else
109 #else
110 ('back' will be a file and cause some other system specific error)
110 ('back' will be a file and cause some other system specific error)
111 $ hg update -Cr2
111 $ hg update -Cr2
112 back: is both a file and a directory
112 abort: $TESTTMP/target/back/test: $ENOTDIR$
113 abort: * (glob)
114 [255]
113 [255]
115 #endif
114 #endif
116
115
117 attack ../test
116 attack ../test
118
117
119 $ hg manifest -r3
118 $ hg manifest -r3
120 ../test
119 ../test
121 $ mkdir ../test
120 $ mkdir ../test
122 $ echo data > ../test/file
121 $ echo data > ../test/file
123 $ hg update -Cr3
122 $ hg update -Cr3
124 abort: path contains illegal component: ../test
123 abort: path contains illegal component: ../test
125 [255]
124 [255]
126 $ cat ../test/file
125 $ cat ../test/file
127 data
126 data
128
127
129 attack /tmp/test
128 attack /tmp/test
130
129
131 $ hg manifest -r4
130 $ hg manifest -r4
132 /tmp/test
131 /tmp/test
133 $ hg update -Cr4
132 $ hg update -Cr4
134 abort: path contains illegal component: /tmp/test
133 abort: path contains illegal component: /tmp/test
135 [255]
134 [255]
136
135
137 $ cd ..
136 $ cd ..
138
137
139 Test symlink traversal on merge:
138 Test symlink traversal on merge:
140 --------------------------------
139 --------------------------------
141
140
142 #if symlink
141 #if symlink
143
142
144 set up symlink hell
143 set up symlink hell
145
144
146 $ mkdir merge-symlink-out
145 $ mkdir merge-symlink-out
147 $ hg init merge-symlink
146 $ hg init merge-symlink
148 $ cd merge-symlink
147 $ cd merge-symlink
149 $ touch base
148 $ touch base
150 $ hg commit -qAm base
149 $ hg commit -qAm base
151 $ ln -s ../merge-symlink-out a
150 $ ln -s ../merge-symlink-out a
152 $ hg commit -qAm 'symlink a -> ../merge-symlink-out'
151 $ hg commit -qAm 'symlink a -> ../merge-symlink-out'
153 $ hg up -q 0
152 $ hg up -q 0
154 $ mkdir a
153 $ mkdir a
155 $ touch a/poisoned
154 $ touch a/poisoned
156 $ hg commit -qAm 'file a/poisoned'
155 $ hg commit -qAm 'file a/poisoned'
157 $ hg log -G -T '{rev}: {desc}\n'
156 $ hg log -G -T '{rev}: {desc}\n'
158 @ 2: file a/poisoned
157 @ 2: file a/poisoned
159 |
158 |
160 | o 1: symlink a -> ../merge-symlink-out
159 | o 1: symlink a -> ../merge-symlink-out
161 |/
160 |/
162 o 0: base
161 o 0: base
163
162
164
163
165 try trivial merge
164 try trivial merge
166
165
167 $ hg up -qC 1
166 $ hg up -qC 1
168 $ hg merge 2
167 $ hg merge 2
169 abort: path 'a/poisoned' traverses symbolic link 'a'
168 abort: path 'a/poisoned' traverses symbolic link 'a'
170 [255]
169 [255]
171
170
172 try rebase onto other revision: cache of audited paths should be discarded,
171 try rebase onto other revision: cache of audited paths should be discarded,
173 and the rebase should fail (issue5628)
172 and the rebase should fail (issue5628)
174
173
175 $ hg up -qC 2
174 $ hg up -qC 2
176 $ hg rebase -s 2 -d 1 --config extensions.rebase=
175 $ hg rebase -s 2 -d 1 --config extensions.rebase=
177 rebasing 2:e73c21d6b244 "file a/poisoned" (tip)
176 rebasing 2:e73c21d6b244 "file a/poisoned" (tip)
178 abort: path 'a/poisoned' traverses symbolic link 'a'
177 abort: path 'a/poisoned' traverses symbolic link 'a'
179 [255]
178 [255]
180 $ ls ../merge-symlink-out
179 $ ls ../merge-symlink-out
181
180
182 $ cd ..
181 $ cd ..
183
182
184 Test symlink traversal on update:
183 Test symlink traversal on update:
185 ---------------------------------
184 ---------------------------------
186
185
187 $ mkdir update-symlink-out
186 $ mkdir update-symlink-out
188 $ hg init update-symlink
187 $ hg init update-symlink
189 $ cd update-symlink
188 $ cd update-symlink
190 $ ln -s ../update-symlink-out a
189 $ ln -s ../update-symlink-out a
191 $ hg commit -qAm 'symlink a -> ../update-symlink-out'
190 $ hg commit -qAm 'symlink a -> ../update-symlink-out'
192 $ hg rm a
191 $ hg rm a
193 $ mkdir a && touch a/b
192 $ mkdir a && touch a/b
194 $ hg ci -qAm 'file a/b' a/b
193 $ hg ci -qAm 'file a/b' a/b
195 $ hg up -qC 0
194 $ hg up -qC 0
196 $ hg rm a
195 $ hg rm a
197 $ mkdir a && touch a/c
196 $ mkdir a && touch a/c
198 $ hg ci -qAm 'rm a, file a/c'
197 $ hg ci -qAm 'rm a, file a/c'
199 $ hg log -G -T '{rev}: {desc}\n'
198 $ hg log -G -T '{rev}: {desc}\n'
200 @ 2: rm a, file a/c
199 @ 2: rm a, file a/c
201 |
200 |
202 | o 1: file a/b
201 | o 1: file a/b
203 |/
202 |/
204 o 0: symlink a -> ../update-symlink-out
203 o 0: symlink a -> ../update-symlink-out
205
204
206
205
207 try linear update where symlink already exists:
206 try linear update where symlink already exists:
208
207
209 $ hg up -qC 0
208 $ hg up -qC 0
210 $ hg up 1
209 $ hg up 1
211 abort: path 'a/b' traverses symbolic link 'a'
210 abort: path 'a/b' traverses symbolic link 'a'
212 [255]
211 [255]
213
212
214 try linear update including symlinked directory and its content: paths are
213 try linear update including symlinked directory and its content: paths are
215 audited first by calculateupdates(), where no symlink is created so both
214 audited first by calculateupdates(), where no symlink is created so both
216 'a' and 'a/b' are taken as good paths. still applyupdates() should fail.
215 'a' and 'a/b' are taken as good paths. still applyupdates() should fail.
217
216
218 $ hg up -qC null
217 $ hg up -qC null
219 $ hg up 1
218 $ hg up 1
220 abort: path 'a/b' traverses symbolic link 'a'
219 abort: path 'a/b' traverses symbolic link 'a'
221 [255]
220 [255]
222 $ ls ../update-symlink-out
221 $ ls ../update-symlink-out
223
222
224 try branch update replacing directory with symlink, and its content: the
223 try branch update replacing directory with symlink, and its content: the
225 path 'a' is audited as a directory first, which should be audited again as
224 path 'a' is audited as a directory first, which should be audited again as
226 a symlink.
225 a symlink.
227
226
228 $ rm -f a
227 $ rm -f a
229 $ hg up -qC 2
228 $ hg up -qC 2
230 $ hg up 1
229 $ hg up 1
231 abort: path 'a/b' traverses symbolic link 'a'
230 abort: path 'a/b' traverses symbolic link 'a'
232 [255]
231 [255]
233 $ ls ../update-symlink-out
232 $ ls ../update-symlink-out
234
233
235 $ cd ..
234 $ cd ..
236
235
237 #endif
236 #endif
General Comments 0
You need to be logged in to leave comments. Login now