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