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