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