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