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