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