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