##// END OF EJS Templates
committablectx: override manifestnode() to return None...
Yuya Nishihara -
r24719:11e8fec0 default
parent child Browse files
Show More
@@ -1,1873 +1,1875 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 node import nullid, nullrev, short, hex, bin
8 from node import nullid, nullrev, short, hex, bin
9 from i18n import _
9 from i18n import _
10 import mdiff, error, util, scmutil, subrepo, patch, encoding, phases
10 import mdiff, error, util, scmutil, subrepo, patch, encoding, phases
11 import match as matchmod
11 import match as matchmod
12 import os, errno, stat
12 import os, errno, stat
13 import obsolete as obsmod
13 import obsolete as obsmod
14 import repoview
14 import repoview
15 import fileset
15 import fileset
16 import revlog
16 import revlog
17
17
18 propertycache = util.propertycache
18 propertycache = util.propertycache
19
19
20 # Phony node value to stand-in for new files in some uses of
20 # Phony node value to stand-in for new files in some uses of
21 # manifests. Manifests support 21-byte hashes for nodes which are
21 # manifests. Manifests support 21-byte hashes for nodes which are
22 # dirty in the working copy.
22 # dirty in the working copy.
23 _newnode = '!' * 21
23 _newnode = '!' * 21
24
24
25 class basectx(object):
25 class basectx(object):
26 """A basectx object represents the common logic for its children:
26 """A basectx object represents the common logic for its children:
27 changectx: read-only context that is already present in the repo,
27 changectx: read-only context that is already present in the repo,
28 workingctx: a context that represents the working directory and can
28 workingctx: a context that represents the working directory and can
29 be committed,
29 be committed,
30 memctx: a context that represents changes in-memory and can also
30 memctx: a context that represents changes in-memory and can also
31 be committed."""
31 be committed."""
32 def __new__(cls, repo, changeid='', *args, **kwargs):
32 def __new__(cls, repo, changeid='', *args, **kwargs):
33 if isinstance(changeid, basectx):
33 if isinstance(changeid, basectx):
34 return changeid
34 return changeid
35
35
36 o = super(basectx, cls).__new__(cls)
36 o = super(basectx, cls).__new__(cls)
37
37
38 o._repo = repo
38 o._repo = repo
39 o._rev = nullrev
39 o._rev = nullrev
40 o._node = nullid
40 o._node = nullid
41
41
42 return o
42 return o
43
43
44 def __str__(self):
44 def __str__(self):
45 return short(self.node())
45 return short(self.node())
46
46
47 def __int__(self):
47 def __int__(self):
48 return self.rev()
48 return self.rev()
49
49
50 def __repr__(self):
50 def __repr__(self):
51 return "<%s %s>" % (type(self).__name__, str(self))
51 return "<%s %s>" % (type(self).__name__, str(self))
52
52
53 def __eq__(self, other):
53 def __eq__(self, other):
54 try:
54 try:
55 return type(self) == type(other) and self._rev == other._rev
55 return type(self) == type(other) and self._rev == other._rev
56 except AttributeError:
56 except AttributeError:
57 return False
57 return False
58
58
59 def __ne__(self, other):
59 def __ne__(self, other):
60 return not (self == other)
60 return not (self == other)
61
61
62 def __contains__(self, key):
62 def __contains__(self, key):
63 return key in self._manifest
63 return key in self._manifest
64
64
65 def __getitem__(self, key):
65 def __getitem__(self, key):
66 return self.filectx(key)
66 return self.filectx(key)
67
67
68 def __iter__(self):
68 def __iter__(self):
69 return iter(self._manifest)
69 return iter(self._manifest)
70
70
71 def _manifestmatches(self, match, s):
71 def _manifestmatches(self, match, s):
72 """generate a new manifest filtered by the match argument
72 """generate a new manifest filtered by the match argument
73
73
74 This method is for internal use only and mainly exists to provide an
74 This method is for internal use only and mainly exists to provide an
75 object oriented way for other contexts to customize the manifest
75 object oriented way for other contexts to customize the manifest
76 generation.
76 generation.
77 """
77 """
78 return self.manifest().matches(match)
78 return self.manifest().matches(match)
79
79
80 def _matchstatus(self, other, match):
80 def _matchstatus(self, other, match):
81 """return match.always if match is none
81 """return match.always if match is none
82
82
83 This internal method provides a way for child objects to override the
83 This internal method provides a way for child objects to override the
84 match operator.
84 match operator.
85 """
85 """
86 return match or matchmod.always(self._repo.root, self._repo.getcwd())
86 return match or matchmod.always(self._repo.root, self._repo.getcwd())
87
87
88 def _buildstatus(self, other, s, match, listignored, listclean,
88 def _buildstatus(self, other, s, match, listignored, listclean,
89 listunknown):
89 listunknown):
90 """build a status with respect to another context"""
90 """build a status with respect to another context"""
91 # Load earliest manifest first for caching reasons. More specifically,
91 # Load earliest manifest first for caching reasons. More specifically,
92 # if you have revisions 1000 and 1001, 1001 is probably stored as a
92 # if you have revisions 1000 and 1001, 1001 is probably stored as a
93 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
93 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
94 # 1000 and cache it so that when you read 1001, we just need to apply a
94 # 1000 and cache it so that when you read 1001, we just need to apply a
95 # delta to what's in the cache. So that's one full reconstruction + one
95 # delta to what's in the cache. So that's one full reconstruction + one
96 # delta application.
96 # delta application.
97 if self.rev() is not None and self.rev() < other.rev():
97 if self.rev() is not None and self.rev() < other.rev():
98 self.manifest()
98 self.manifest()
99 mf1 = other._manifestmatches(match, s)
99 mf1 = other._manifestmatches(match, s)
100 mf2 = self._manifestmatches(match, s)
100 mf2 = self._manifestmatches(match, s)
101
101
102 modified, added = [], []
102 modified, added = [], []
103 removed = []
103 removed = []
104 clean = []
104 clean = []
105 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
105 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
106 deletedset = set(deleted)
106 deletedset = set(deleted)
107 d = mf1.diff(mf2, clean=listclean)
107 d = mf1.diff(mf2, clean=listclean)
108 for fn, value in d.iteritems():
108 for fn, value in d.iteritems():
109 if fn in deletedset:
109 if fn in deletedset:
110 continue
110 continue
111 if value is None:
111 if value is None:
112 clean.append(fn)
112 clean.append(fn)
113 continue
113 continue
114 (node1, flag1), (node2, flag2) = value
114 (node1, flag1), (node2, flag2) = value
115 if node1 is None:
115 if node1 is None:
116 added.append(fn)
116 added.append(fn)
117 elif node2 is None:
117 elif node2 is None:
118 removed.append(fn)
118 removed.append(fn)
119 elif node2 != _newnode:
119 elif node2 != _newnode:
120 # The file was not a new file in mf2, so an entry
120 # The file was not a new file in mf2, so an entry
121 # from diff is really a difference.
121 # from diff is really a difference.
122 modified.append(fn)
122 modified.append(fn)
123 elif self[fn].cmp(other[fn]):
123 elif self[fn].cmp(other[fn]):
124 # node2 was newnode, but the working file doesn't
124 # node2 was newnode, but the working file doesn't
125 # match the one in mf1.
125 # match the one in mf1.
126 modified.append(fn)
126 modified.append(fn)
127 else:
127 else:
128 clean.append(fn)
128 clean.append(fn)
129
129
130 if removed:
130 if removed:
131 # need to filter files if they are already reported as removed
131 # need to filter files if they are already reported as removed
132 unknown = [fn for fn in unknown if fn not in mf1]
132 unknown = [fn for fn in unknown if fn not in mf1]
133 ignored = [fn for fn in ignored if fn not in mf1]
133 ignored = [fn for fn in ignored if fn not in mf1]
134 # if they're deleted, don't report them as removed
134 # if they're deleted, don't report them as removed
135 removed = [fn for fn in removed if fn not in deletedset]
135 removed = [fn for fn in removed if fn not in deletedset]
136
136
137 return scmutil.status(modified, added, removed, deleted, unknown,
137 return scmutil.status(modified, added, removed, deleted, unknown,
138 ignored, clean)
138 ignored, clean)
139
139
140 @propertycache
140 @propertycache
141 def substate(self):
141 def substate(self):
142 return subrepo.state(self, self._repo.ui)
142 return subrepo.state(self, self._repo.ui)
143
143
144 def subrev(self, subpath):
144 def subrev(self, subpath):
145 return self.substate[subpath][1]
145 return self.substate[subpath][1]
146
146
147 def rev(self):
147 def rev(self):
148 return self._rev
148 return self._rev
149 def node(self):
149 def node(self):
150 return self._node
150 return self._node
151 def hex(self):
151 def hex(self):
152 return hex(self.node())
152 return hex(self.node())
153 def manifest(self):
153 def manifest(self):
154 return self._manifest
154 return self._manifest
155 def repo(self):
155 def repo(self):
156 return self._repo
156 return self._repo
157 def phasestr(self):
157 def phasestr(self):
158 return phases.phasenames[self.phase()]
158 return phases.phasenames[self.phase()]
159 def mutable(self):
159 def mutable(self):
160 return self.phase() > phases.public
160 return self.phase() > phases.public
161
161
162 def getfileset(self, expr):
162 def getfileset(self, expr):
163 return fileset.getfileset(self, expr)
163 return fileset.getfileset(self, expr)
164
164
165 def obsolete(self):
165 def obsolete(self):
166 """True if the changeset is obsolete"""
166 """True if the changeset is obsolete"""
167 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
167 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
168
168
169 def extinct(self):
169 def extinct(self):
170 """True if the changeset is extinct"""
170 """True if the changeset is extinct"""
171 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
171 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
172
172
173 def unstable(self):
173 def unstable(self):
174 """True if the changeset is not obsolete but it's ancestor are"""
174 """True if the changeset is not obsolete but it's ancestor are"""
175 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
175 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
176
176
177 def bumped(self):
177 def bumped(self):
178 """True if the changeset try to be a successor of a public changeset
178 """True if the changeset try to be a successor of a public changeset
179
179
180 Only non-public and non-obsolete changesets may be bumped.
180 Only non-public and non-obsolete changesets may be bumped.
181 """
181 """
182 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
182 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
183
183
184 def divergent(self):
184 def divergent(self):
185 """Is a successors of a changeset with multiple possible successors set
185 """Is a successors of a changeset with multiple possible successors set
186
186
187 Only non-public and non-obsolete changesets may be divergent.
187 Only non-public and non-obsolete changesets may be divergent.
188 """
188 """
189 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
189 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
190
190
191 def troubled(self):
191 def troubled(self):
192 """True if the changeset is either unstable, bumped or divergent"""
192 """True if the changeset is either unstable, bumped or divergent"""
193 return self.unstable() or self.bumped() or self.divergent()
193 return self.unstable() or self.bumped() or self.divergent()
194
194
195 def troubles(self):
195 def troubles(self):
196 """return the list of troubles affecting this changesets.
196 """return the list of troubles affecting this changesets.
197
197
198 Troubles are returned as strings. possible values are:
198 Troubles are returned as strings. possible values are:
199 - unstable,
199 - unstable,
200 - bumped,
200 - bumped,
201 - divergent.
201 - divergent.
202 """
202 """
203 troubles = []
203 troubles = []
204 if self.unstable():
204 if self.unstable():
205 troubles.append('unstable')
205 troubles.append('unstable')
206 if self.bumped():
206 if self.bumped():
207 troubles.append('bumped')
207 troubles.append('bumped')
208 if self.divergent():
208 if self.divergent():
209 troubles.append('divergent')
209 troubles.append('divergent')
210 return troubles
210 return troubles
211
211
212 def parents(self):
212 def parents(self):
213 """return contexts for each parent changeset"""
213 """return contexts for each parent changeset"""
214 return self._parents
214 return self._parents
215
215
216 def p1(self):
216 def p1(self):
217 return self._parents[0]
217 return self._parents[0]
218
218
219 def p2(self):
219 def p2(self):
220 if len(self._parents) == 2:
220 if len(self._parents) == 2:
221 return self._parents[1]
221 return self._parents[1]
222 return changectx(self._repo, -1)
222 return changectx(self._repo, -1)
223
223
224 def _fileinfo(self, path):
224 def _fileinfo(self, path):
225 if '_manifest' in self.__dict__:
225 if '_manifest' in self.__dict__:
226 try:
226 try:
227 return self._manifest[path], self._manifest.flags(path)
227 return self._manifest[path], self._manifest.flags(path)
228 except KeyError:
228 except KeyError:
229 raise error.ManifestLookupError(self._node, path,
229 raise error.ManifestLookupError(self._node, path,
230 _('not found in manifest'))
230 _('not found in manifest'))
231 if '_manifestdelta' in self.__dict__ or path in self.files():
231 if '_manifestdelta' in self.__dict__ or path in self.files():
232 if path in self._manifestdelta:
232 if path in self._manifestdelta:
233 return (self._manifestdelta[path],
233 return (self._manifestdelta[path],
234 self._manifestdelta.flags(path))
234 self._manifestdelta.flags(path))
235 node, flag = self._repo.manifest.find(self._changeset[0], path)
235 node, flag = self._repo.manifest.find(self._changeset[0], path)
236 if not node:
236 if not node:
237 raise error.ManifestLookupError(self._node, path,
237 raise error.ManifestLookupError(self._node, path,
238 _('not found in manifest'))
238 _('not found in manifest'))
239
239
240 return node, flag
240 return node, flag
241
241
242 def filenode(self, path):
242 def filenode(self, path):
243 return self._fileinfo(path)[0]
243 return self._fileinfo(path)[0]
244
244
245 def flags(self, path):
245 def flags(self, path):
246 try:
246 try:
247 return self._fileinfo(path)[1]
247 return self._fileinfo(path)[1]
248 except error.LookupError:
248 except error.LookupError:
249 return ''
249 return ''
250
250
251 def sub(self, path):
251 def sub(self, path):
252 return subrepo.subrepo(self, path)
252 return subrepo.subrepo(self, path)
253
253
254 def match(self, pats=[], include=None, exclude=None, default='glob'):
254 def match(self, pats=[], include=None, exclude=None, default='glob'):
255 r = self._repo
255 r = self._repo
256 return matchmod.match(r.root, r.getcwd(), pats,
256 return matchmod.match(r.root, r.getcwd(), pats,
257 include, exclude, default,
257 include, exclude, default,
258 auditor=r.auditor, ctx=self)
258 auditor=r.auditor, ctx=self)
259
259
260 def diff(self, ctx2=None, match=None, **opts):
260 def diff(self, ctx2=None, match=None, **opts):
261 """Returns a diff generator for the given contexts and matcher"""
261 """Returns a diff generator for the given contexts and matcher"""
262 if ctx2 is None:
262 if ctx2 is None:
263 ctx2 = self.p1()
263 ctx2 = self.p1()
264 if ctx2 is not None:
264 if ctx2 is not None:
265 ctx2 = self._repo[ctx2]
265 ctx2 = self._repo[ctx2]
266 diffopts = patch.diffopts(self._repo.ui, opts)
266 diffopts = patch.diffopts(self._repo.ui, opts)
267 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
267 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
268
268
269 def dirs(self):
269 def dirs(self):
270 return self._manifest.dirs()
270 return self._manifest.dirs()
271
271
272 def hasdir(self, dir):
272 def hasdir(self, dir):
273 return self._manifest.hasdir(dir)
273 return self._manifest.hasdir(dir)
274
274
275 def dirty(self, missing=False, merge=True, branch=True):
275 def dirty(self, missing=False, merge=True, branch=True):
276 return False
276 return False
277
277
278 def status(self, other=None, match=None, listignored=False,
278 def status(self, other=None, match=None, listignored=False,
279 listclean=False, listunknown=False, listsubrepos=False):
279 listclean=False, listunknown=False, listsubrepos=False):
280 """return status of files between two nodes or node and working
280 """return status of files between two nodes or node and working
281 directory.
281 directory.
282
282
283 If other is None, compare this node with working directory.
283 If other is None, compare this node with working directory.
284
284
285 returns (modified, added, removed, deleted, unknown, ignored, clean)
285 returns (modified, added, removed, deleted, unknown, ignored, clean)
286 """
286 """
287
287
288 ctx1 = self
288 ctx1 = self
289 ctx2 = self._repo[other]
289 ctx2 = self._repo[other]
290
290
291 # This next code block is, admittedly, fragile logic that tests for
291 # This next code block is, admittedly, fragile logic that tests for
292 # reversing the contexts and wouldn't need to exist if it weren't for
292 # reversing the contexts and wouldn't need to exist if it weren't for
293 # the fast (and common) code path of comparing the working directory
293 # the fast (and common) code path of comparing the working directory
294 # with its first parent.
294 # with its first parent.
295 #
295 #
296 # What we're aiming for here is the ability to call:
296 # What we're aiming for here is the ability to call:
297 #
297 #
298 # workingctx.status(parentctx)
298 # workingctx.status(parentctx)
299 #
299 #
300 # If we always built the manifest for each context and compared those,
300 # If we always built the manifest for each context and compared those,
301 # then we'd be done. But the special case of the above call means we
301 # then we'd be done. But the special case of the above call means we
302 # just copy the manifest of the parent.
302 # just copy the manifest of the parent.
303 reversed = False
303 reversed = False
304 if (not isinstance(ctx1, changectx)
304 if (not isinstance(ctx1, changectx)
305 and isinstance(ctx2, changectx)):
305 and isinstance(ctx2, changectx)):
306 reversed = True
306 reversed = True
307 ctx1, ctx2 = ctx2, ctx1
307 ctx1, ctx2 = ctx2, ctx1
308
308
309 match = ctx2._matchstatus(ctx1, match)
309 match = ctx2._matchstatus(ctx1, match)
310 r = scmutil.status([], [], [], [], [], [], [])
310 r = scmutil.status([], [], [], [], [], [], [])
311 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
311 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
312 listunknown)
312 listunknown)
313
313
314 if reversed:
314 if reversed:
315 # Reverse added and removed. Clear deleted, unknown and ignored as
315 # Reverse added and removed. Clear deleted, unknown and ignored as
316 # these make no sense to reverse.
316 # these make no sense to reverse.
317 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
317 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
318 r.clean)
318 r.clean)
319
319
320 if listsubrepos:
320 if listsubrepos:
321 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
321 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
322 rev2 = ctx2.subrev(subpath)
322 rev2 = ctx2.subrev(subpath)
323 try:
323 try:
324 submatch = matchmod.narrowmatcher(subpath, match)
324 submatch = matchmod.narrowmatcher(subpath, match)
325 s = sub.status(rev2, match=submatch, ignored=listignored,
325 s = sub.status(rev2, match=submatch, ignored=listignored,
326 clean=listclean, unknown=listunknown,
326 clean=listclean, unknown=listunknown,
327 listsubrepos=True)
327 listsubrepos=True)
328 for rfiles, sfiles in zip(r, s):
328 for rfiles, sfiles in zip(r, s):
329 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
329 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
330 except error.LookupError:
330 except error.LookupError:
331 self._repo.ui.status(_("skipping missing "
331 self._repo.ui.status(_("skipping missing "
332 "subrepository: %s\n") % subpath)
332 "subrepository: %s\n") % subpath)
333
333
334 for l in r:
334 for l in r:
335 l.sort()
335 l.sort()
336
336
337 return r
337 return r
338
338
339
339
340 def makememctx(repo, parents, text, user, date, branch, files, store,
340 def makememctx(repo, parents, text, user, date, branch, files, store,
341 editor=None):
341 editor=None):
342 def getfilectx(repo, memctx, path):
342 def getfilectx(repo, memctx, path):
343 data, mode, copied = store.getfile(path)
343 data, mode, copied = store.getfile(path)
344 if data is None:
344 if data is None:
345 return None
345 return None
346 islink, isexec = mode
346 islink, isexec = mode
347 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
347 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
348 copied=copied, memctx=memctx)
348 copied=copied, memctx=memctx)
349 extra = {}
349 extra = {}
350 if branch:
350 if branch:
351 extra['branch'] = encoding.fromlocal(branch)
351 extra['branch'] = encoding.fromlocal(branch)
352 ctx = memctx(repo, parents, text, files, getfilectx, user,
352 ctx = memctx(repo, parents, text, files, getfilectx, user,
353 date, extra, editor)
353 date, extra, editor)
354 return ctx
354 return ctx
355
355
356 class changectx(basectx):
356 class changectx(basectx):
357 """A changecontext object makes access to data related to a particular
357 """A changecontext object makes access to data related to a particular
358 changeset convenient. It represents a read-only context already present in
358 changeset convenient. It represents a read-only context already present in
359 the repo."""
359 the repo."""
360 def __init__(self, repo, changeid=''):
360 def __init__(self, repo, changeid=''):
361 """changeid is a revision number, node, or tag"""
361 """changeid is a revision number, node, or tag"""
362
362
363 # since basectx.__new__ already took care of copying the object, we
363 # since basectx.__new__ already took care of copying the object, we
364 # don't need to do anything in __init__, so we just exit here
364 # don't need to do anything in __init__, so we just exit here
365 if isinstance(changeid, basectx):
365 if isinstance(changeid, basectx):
366 return
366 return
367
367
368 if changeid == '':
368 if changeid == '':
369 changeid = '.'
369 changeid = '.'
370 self._repo = repo
370 self._repo = repo
371
371
372 try:
372 try:
373 if isinstance(changeid, int):
373 if isinstance(changeid, int):
374 self._node = repo.changelog.node(changeid)
374 self._node = repo.changelog.node(changeid)
375 self._rev = changeid
375 self._rev = changeid
376 return
376 return
377 if isinstance(changeid, long):
377 if isinstance(changeid, long):
378 changeid = str(changeid)
378 changeid = str(changeid)
379 if changeid == 'null':
379 if changeid == 'null':
380 self._node = nullid
380 self._node = nullid
381 self._rev = nullrev
381 self._rev = nullrev
382 return
382 return
383 if changeid == 'tip':
383 if changeid == 'tip':
384 self._node = repo.changelog.tip()
384 self._node = repo.changelog.tip()
385 self._rev = repo.changelog.rev(self._node)
385 self._rev = repo.changelog.rev(self._node)
386 return
386 return
387 if changeid == '.' or changeid == repo.dirstate.p1():
387 if changeid == '.' or changeid == repo.dirstate.p1():
388 # this is a hack to delay/avoid loading obsmarkers
388 # this is a hack to delay/avoid loading obsmarkers
389 # when we know that '.' won't be hidden
389 # when we know that '.' won't be hidden
390 self._node = repo.dirstate.p1()
390 self._node = repo.dirstate.p1()
391 self._rev = repo.unfiltered().changelog.rev(self._node)
391 self._rev = repo.unfiltered().changelog.rev(self._node)
392 return
392 return
393 if len(changeid) == 20:
393 if len(changeid) == 20:
394 try:
394 try:
395 self._node = changeid
395 self._node = changeid
396 self._rev = repo.changelog.rev(changeid)
396 self._rev = repo.changelog.rev(changeid)
397 return
397 return
398 except error.FilteredRepoLookupError:
398 except error.FilteredRepoLookupError:
399 raise
399 raise
400 except LookupError:
400 except LookupError:
401 pass
401 pass
402
402
403 try:
403 try:
404 r = int(changeid)
404 r = int(changeid)
405 if str(r) != changeid:
405 if str(r) != changeid:
406 raise ValueError
406 raise ValueError
407 l = len(repo.changelog)
407 l = len(repo.changelog)
408 if r < 0:
408 if r < 0:
409 r += l
409 r += l
410 if r < 0 or r >= l:
410 if r < 0 or r >= l:
411 raise ValueError
411 raise ValueError
412 self._rev = r
412 self._rev = r
413 self._node = repo.changelog.node(r)
413 self._node = repo.changelog.node(r)
414 return
414 return
415 except error.FilteredIndexError:
415 except error.FilteredIndexError:
416 raise
416 raise
417 except (ValueError, OverflowError, IndexError):
417 except (ValueError, OverflowError, IndexError):
418 pass
418 pass
419
419
420 if len(changeid) == 40:
420 if len(changeid) == 40:
421 try:
421 try:
422 self._node = bin(changeid)
422 self._node = bin(changeid)
423 self._rev = repo.changelog.rev(self._node)
423 self._rev = repo.changelog.rev(self._node)
424 return
424 return
425 except error.FilteredLookupError:
425 except error.FilteredLookupError:
426 raise
426 raise
427 except (TypeError, LookupError):
427 except (TypeError, LookupError):
428 pass
428 pass
429
429
430 # lookup bookmarks through the name interface
430 # lookup bookmarks through the name interface
431 try:
431 try:
432 self._node = repo.names.singlenode(repo, changeid)
432 self._node = repo.names.singlenode(repo, changeid)
433 self._rev = repo.changelog.rev(self._node)
433 self._rev = repo.changelog.rev(self._node)
434 return
434 return
435 except KeyError:
435 except KeyError:
436 pass
436 pass
437 except error.FilteredRepoLookupError:
437 except error.FilteredRepoLookupError:
438 raise
438 raise
439 except error.RepoLookupError:
439 except error.RepoLookupError:
440 pass
440 pass
441
441
442 self._node = repo.unfiltered().changelog._partialmatch(changeid)
442 self._node = repo.unfiltered().changelog._partialmatch(changeid)
443 if self._node is not None:
443 if self._node is not None:
444 self._rev = repo.changelog.rev(self._node)
444 self._rev = repo.changelog.rev(self._node)
445 return
445 return
446
446
447 # lookup failed
447 # lookup failed
448 # check if it might have come from damaged dirstate
448 # check if it might have come from damaged dirstate
449 #
449 #
450 # XXX we could avoid the unfiltered if we had a recognizable
450 # XXX we could avoid the unfiltered if we had a recognizable
451 # exception for filtered changeset access
451 # exception for filtered changeset access
452 if changeid in repo.unfiltered().dirstate.parents():
452 if changeid in repo.unfiltered().dirstate.parents():
453 msg = _("working directory has unknown parent '%s'!")
453 msg = _("working directory has unknown parent '%s'!")
454 raise error.Abort(msg % short(changeid))
454 raise error.Abort(msg % short(changeid))
455 try:
455 try:
456 if len(changeid) == 20:
456 if len(changeid) == 20:
457 changeid = hex(changeid)
457 changeid = hex(changeid)
458 except TypeError:
458 except TypeError:
459 pass
459 pass
460 except (error.FilteredIndexError, error.FilteredLookupError,
460 except (error.FilteredIndexError, error.FilteredLookupError,
461 error.FilteredRepoLookupError):
461 error.FilteredRepoLookupError):
462 if repo.filtername == 'visible':
462 if repo.filtername == 'visible':
463 msg = _("hidden revision '%s'") % changeid
463 msg = _("hidden revision '%s'") % changeid
464 hint = _('use --hidden to access hidden revisions')
464 hint = _('use --hidden to access hidden revisions')
465 raise error.FilteredRepoLookupError(msg, hint=hint)
465 raise error.FilteredRepoLookupError(msg, hint=hint)
466 msg = _("filtered revision '%s' (not in '%s' subset)")
466 msg = _("filtered revision '%s' (not in '%s' subset)")
467 msg %= (changeid, repo.filtername)
467 msg %= (changeid, repo.filtername)
468 raise error.FilteredRepoLookupError(msg)
468 raise error.FilteredRepoLookupError(msg)
469 except IndexError:
469 except IndexError:
470 pass
470 pass
471 raise error.RepoLookupError(
471 raise error.RepoLookupError(
472 _("unknown revision '%s'") % changeid)
472 _("unknown revision '%s'") % changeid)
473
473
474 def __hash__(self):
474 def __hash__(self):
475 try:
475 try:
476 return hash(self._rev)
476 return hash(self._rev)
477 except AttributeError:
477 except AttributeError:
478 return id(self)
478 return id(self)
479
479
480 def __nonzero__(self):
480 def __nonzero__(self):
481 return self._rev != nullrev
481 return self._rev != nullrev
482
482
483 @propertycache
483 @propertycache
484 def _changeset(self):
484 def _changeset(self):
485 return self._repo.changelog.read(self.rev())
485 return self._repo.changelog.read(self.rev())
486
486
487 @propertycache
487 @propertycache
488 def _manifest(self):
488 def _manifest(self):
489 return self._repo.manifest.read(self._changeset[0])
489 return self._repo.manifest.read(self._changeset[0])
490
490
491 @propertycache
491 @propertycache
492 def _manifestdelta(self):
492 def _manifestdelta(self):
493 return self._repo.manifest.readdelta(self._changeset[0])
493 return self._repo.manifest.readdelta(self._changeset[0])
494
494
495 @propertycache
495 @propertycache
496 def _parents(self):
496 def _parents(self):
497 p = self._repo.changelog.parentrevs(self._rev)
497 p = self._repo.changelog.parentrevs(self._rev)
498 if p[1] == nullrev:
498 if p[1] == nullrev:
499 p = p[:-1]
499 p = p[:-1]
500 return [changectx(self._repo, x) for x in p]
500 return [changectx(self._repo, x) for x in p]
501
501
502 def changeset(self):
502 def changeset(self):
503 return self._changeset
503 return self._changeset
504 def manifestnode(self):
504 def manifestnode(self):
505 return self._changeset[0]
505 return self._changeset[0]
506
506
507 def user(self):
507 def user(self):
508 return self._changeset[1]
508 return self._changeset[1]
509 def date(self):
509 def date(self):
510 return self._changeset[2]
510 return self._changeset[2]
511 def files(self):
511 def files(self):
512 return self._changeset[3]
512 return self._changeset[3]
513 def description(self):
513 def description(self):
514 return self._changeset[4]
514 return self._changeset[4]
515 def branch(self):
515 def branch(self):
516 return encoding.tolocal(self._changeset[5].get("branch"))
516 return encoding.tolocal(self._changeset[5].get("branch"))
517 def closesbranch(self):
517 def closesbranch(self):
518 return 'close' in self._changeset[5]
518 return 'close' in self._changeset[5]
519 def extra(self):
519 def extra(self):
520 return self._changeset[5]
520 return self._changeset[5]
521 def tags(self):
521 def tags(self):
522 return self._repo.nodetags(self._node)
522 return self._repo.nodetags(self._node)
523 def bookmarks(self):
523 def bookmarks(self):
524 return self._repo.nodebookmarks(self._node)
524 return self._repo.nodebookmarks(self._node)
525 def phase(self):
525 def phase(self):
526 return self._repo._phasecache.phase(self._repo, self._rev)
526 return self._repo._phasecache.phase(self._repo, self._rev)
527 def hidden(self):
527 def hidden(self):
528 return self._rev in repoview.filterrevs(self._repo, 'visible')
528 return self._rev in repoview.filterrevs(self._repo, 'visible')
529
529
530 def children(self):
530 def children(self):
531 """return contexts for each child changeset"""
531 """return contexts for each child changeset"""
532 c = self._repo.changelog.children(self._node)
532 c = self._repo.changelog.children(self._node)
533 return [changectx(self._repo, x) for x in c]
533 return [changectx(self._repo, x) for x in c]
534
534
535 def ancestors(self):
535 def ancestors(self):
536 for a in self._repo.changelog.ancestors([self._rev]):
536 for a in self._repo.changelog.ancestors([self._rev]):
537 yield changectx(self._repo, a)
537 yield changectx(self._repo, a)
538
538
539 def descendants(self):
539 def descendants(self):
540 for d in self._repo.changelog.descendants([self._rev]):
540 for d in self._repo.changelog.descendants([self._rev]):
541 yield changectx(self._repo, d)
541 yield changectx(self._repo, d)
542
542
543 def filectx(self, path, fileid=None, filelog=None):
543 def filectx(self, path, fileid=None, filelog=None):
544 """get a file context from this changeset"""
544 """get a file context from this changeset"""
545 if fileid is None:
545 if fileid is None:
546 fileid = self.filenode(path)
546 fileid = self.filenode(path)
547 return filectx(self._repo, path, fileid=fileid,
547 return filectx(self._repo, path, fileid=fileid,
548 changectx=self, filelog=filelog)
548 changectx=self, filelog=filelog)
549
549
550 def ancestor(self, c2, warn=False):
550 def ancestor(self, c2, warn=False):
551 """return the "best" ancestor context of self and c2
551 """return the "best" ancestor context of self and c2
552
552
553 If there are multiple candidates, it will show a message and check
553 If there are multiple candidates, it will show a message and check
554 merge.preferancestor configuration before falling back to the
554 merge.preferancestor configuration before falling back to the
555 revlog ancestor."""
555 revlog ancestor."""
556 # deal with workingctxs
556 # deal with workingctxs
557 n2 = c2._node
557 n2 = c2._node
558 if n2 is None:
558 if n2 is None:
559 n2 = c2._parents[0]._node
559 n2 = c2._parents[0]._node
560 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
560 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
561 if not cahs:
561 if not cahs:
562 anc = nullid
562 anc = nullid
563 elif len(cahs) == 1:
563 elif len(cahs) == 1:
564 anc = cahs[0]
564 anc = cahs[0]
565 else:
565 else:
566 for r in self._repo.ui.configlist('merge', 'preferancestor'):
566 for r in self._repo.ui.configlist('merge', 'preferancestor'):
567 try:
567 try:
568 ctx = changectx(self._repo, r)
568 ctx = changectx(self._repo, r)
569 except error.RepoLookupError:
569 except error.RepoLookupError:
570 continue
570 continue
571 anc = ctx.node()
571 anc = ctx.node()
572 if anc in cahs:
572 if anc in cahs:
573 break
573 break
574 else:
574 else:
575 anc = self._repo.changelog.ancestor(self._node, n2)
575 anc = self._repo.changelog.ancestor(self._node, n2)
576 if warn:
576 if warn:
577 self._repo.ui.status(
577 self._repo.ui.status(
578 (_("note: using %s as ancestor of %s and %s\n") %
578 (_("note: using %s as ancestor of %s and %s\n") %
579 (short(anc), short(self._node), short(n2))) +
579 (short(anc), short(self._node), short(n2))) +
580 ''.join(_(" alternatively, use --config "
580 ''.join(_(" alternatively, use --config "
581 "merge.preferancestor=%s\n") %
581 "merge.preferancestor=%s\n") %
582 short(n) for n in sorted(cahs) if n != anc))
582 short(n) for n in sorted(cahs) if n != anc))
583 return changectx(self._repo, anc)
583 return changectx(self._repo, anc)
584
584
585 def descendant(self, other):
585 def descendant(self, other):
586 """True if other is descendant of this changeset"""
586 """True if other is descendant of this changeset"""
587 return self._repo.changelog.descendant(self._rev, other._rev)
587 return self._repo.changelog.descendant(self._rev, other._rev)
588
588
589 def walk(self, match):
589 def walk(self, match):
590 '''Generates matching file names.'''
590 '''Generates matching file names.'''
591
591
592 # Override match.bad method to have message with nodeid
592 # Override match.bad method to have message with nodeid
593 oldbad = match.bad
593 oldbad = match.bad
594 def bad(fn, msg):
594 def bad(fn, msg):
595 oldbad(fn, _('no such file in rev %s') % self)
595 oldbad(fn, _('no such file in rev %s') % self)
596 match.bad = bad
596 match.bad = bad
597
597
598 return self._manifest.walk(match)
598 return self._manifest.walk(match)
599
599
600 def matches(self, match):
600 def matches(self, match):
601 return self.walk(match)
601 return self.walk(match)
602
602
603 class basefilectx(object):
603 class basefilectx(object):
604 """A filecontext object represents the common logic for its children:
604 """A filecontext object represents the common logic for its children:
605 filectx: read-only access to a filerevision that is already present
605 filectx: read-only access to a filerevision that is already present
606 in the repo,
606 in the repo,
607 workingfilectx: a filecontext that represents files from the working
607 workingfilectx: a filecontext that represents files from the working
608 directory,
608 directory,
609 memfilectx: a filecontext that represents files in-memory."""
609 memfilectx: a filecontext that represents files in-memory."""
610 def __new__(cls, repo, path, *args, **kwargs):
610 def __new__(cls, repo, path, *args, **kwargs):
611 return super(basefilectx, cls).__new__(cls)
611 return super(basefilectx, cls).__new__(cls)
612
612
613 @propertycache
613 @propertycache
614 def _filelog(self):
614 def _filelog(self):
615 return self._repo.file(self._path)
615 return self._repo.file(self._path)
616
616
617 @propertycache
617 @propertycache
618 def _changeid(self):
618 def _changeid(self):
619 if '_changeid' in self.__dict__:
619 if '_changeid' in self.__dict__:
620 return self._changeid
620 return self._changeid
621 elif '_changectx' in self.__dict__:
621 elif '_changectx' in self.__dict__:
622 return self._changectx.rev()
622 return self._changectx.rev()
623 elif '_descendantrev' in self.__dict__:
623 elif '_descendantrev' in self.__dict__:
624 # this file context was created from a revision with a known
624 # this file context was created from a revision with a known
625 # descendant, we can (lazily) correct for linkrev aliases
625 # descendant, we can (lazily) correct for linkrev aliases
626 return self._adjustlinkrev(self._path, self._filelog,
626 return self._adjustlinkrev(self._path, self._filelog,
627 self._filenode, self._descendantrev)
627 self._filenode, self._descendantrev)
628 else:
628 else:
629 return self._filelog.linkrev(self._filerev)
629 return self._filelog.linkrev(self._filerev)
630
630
631 @propertycache
631 @propertycache
632 def _filenode(self):
632 def _filenode(self):
633 if '_fileid' in self.__dict__:
633 if '_fileid' in self.__dict__:
634 return self._filelog.lookup(self._fileid)
634 return self._filelog.lookup(self._fileid)
635 else:
635 else:
636 return self._changectx.filenode(self._path)
636 return self._changectx.filenode(self._path)
637
637
638 @propertycache
638 @propertycache
639 def _filerev(self):
639 def _filerev(self):
640 return self._filelog.rev(self._filenode)
640 return self._filelog.rev(self._filenode)
641
641
642 @propertycache
642 @propertycache
643 def _repopath(self):
643 def _repopath(self):
644 return self._path
644 return self._path
645
645
646 def __nonzero__(self):
646 def __nonzero__(self):
647 try:
647 try:
648 self._filenode
648 self._filenode
649 return True
649 return True
650 except error.LookupError:
650 except error.LookupError:
651 # file is missing
651 # file is missing
652 return False
652 return False
653
653
654 def __str__(self):
654 def __str__(self):
655 return "%s@%s" % (self.path(), self._changectx)
655 return "%s@%s" % (self.path(), self._changectx)
656
656
657 def __repr__(self):
657 def __repr__(self):
658 return "<%s %s>" % (type(self).__name__, str(self))
658 return "<%s %s>" % (type(self).__name__, str(self))
659
659
660 def __hash__(self):
660 def __hash__(self):
661 try:
661 try:
662 return hash((self._path, self._filenode))
662 return hash((self._path, self._filenode))
663 except AttributeError:
663 except AttributeError:
664 return id(self)
664 return id(self)
665
665
666 def __eq__(self, other):
666 def __eq__(self, other):
667 try:
667 try:
668 return (type(self) == type(other) and self._path == other._path
668 return (type(self) == type(other) and self._path == other._path
669 and self._filenode == other._filenode)
669 and self._filenode == other._filenode)
670 except AttributeError:
670 except AttributeError:
671 return False
671 return False
672
672
673 def __ne__(self, other):
673 def __ne__(self, other):
674 return not (self == other)
674 return not (self == other)
675
675
676 def filerev(self):
676 def filerev(self):
677 return self._filerev
677 return self._filerev
678 def filenode(self):
678 def filenode(self):
679 return self._filenode
679 return self._filenode
680 def flags(self):
680 def flags(self):
681 return self._changectx.flags(self._path)
681 return self._changectx.flags(self._path)
682 def filelog(self):
682 def filelog(self):
683 return self._filelog
683 return self._filelog
684 def rev(self):
684 def rev(self):
685 return self._changeid
685 return self._changeid
686 def linkrev(self):
686 def linkrev(self):
687 return self._filelog.linkrev(self._filerev)
687 return self._filelog.linkrev(self._filerev)
688 def node(self):
688 def node(self):
689 return self._changectx.node()
689 return self._changectx.node()
690 def hex(self):
690 def hex(self):
691 return self._changectx.hex()
691 return self._changectx.hex()
692 def user(self):
692 def user(self):
693 return self._changectx.user()
693 return self._changectx.user()
694 def date(self):
694 def date(self):
695 return self._changectx.date()
695 return self._changectx.date()
696 def files(self):
696 def files(self):
697 return self._changectx.files()
697 return self._changectx.files()
698 def description(self):
698 def description(self):
699 return self._changectx.description()
699 return self._changectx.description()
700 def branch(self):
700 def branch(self):
701 return self._changectx.branch()
701 return self._changectx.branch()
702 def extra(self):
702 def extra(self):
703 return self._changectx.extra()
703 return self._changectx.extra()
704 def phase(self):
704 def phase(self):
705 return self._changectx.phase()
705 return self._changectx.phase()
706 def phasestr(self):
706 def phasestr(self):
707 return self._changectx.phasestr()
707 return self._changectx.phasestr()
708 def manifest(self):
708 def manifest(self):
709 return self._changectx.manifest()
709 return self._changectx.manifest()
710 def changectx(self):
710 def changectx(self):
711 return self._changectx
711 return self._changectx
712 def repo(self):
712 def repo(self):
713 return self._repo
713 return self._repo
714
714
715 def path(self):
715 def path(self):
716 return self._path
716 return self._path
717
717
718 def isbinary(self):
718 def isbinary(self):
719 try:
719 try:
720 return util.binary(self.data())
720 return util.binary(self.data())
721 except IOError:
721 except IOError:
722 return False
722 return False
723 def isexec(self):
723 def isexec(self):
724 return 'x' in self.flags()
724 return 'x' in self.flags()
725 def islink(self):
725 def islink(self):
726 return 'l' in self.flags()
726 return 'l' in self.flags()
727
727
728 def cmp(self, fctx):
728 def cmp(self, fctx):
729 """compare with other file context
729 """compare with other file context
730
730
731 returns True if different than fctx.
731 returns True if different than fctx.
732 """
732 """
733 if (fctx._filerev is None
733 if (fctx._filerev is None
734 and (self._repo._encodefilterpats
734 and (self._repo._encodefilterpats
735 # if file data starts with '\1\n', empty metadata block is
735 # if file data starts with '\1\n', empty metadata block is
736 # prepended, which adds 4 bytes to filelog.size().
736 # prepended, which adds 4 bytes to filelog.size().
737 or self.size() - 4 == fctx.size())
737 or self.size() - 4 == fctx.size())
738 or self.size() == fctx.size()):
738 or self.size() == fctx.size()):
739 return self._filelog.cmp(self._filenode, fctx.data())
739 return self._filelog.cmp(self._filenode, fctx.data())
740
740
741 return True
741 return True
742
742
743 def _adjustlinkrev(self, path, filelog, fnode, srcrev, inclusive=False):
743 def _adjustlinkrev(self, path, filelog, fnode, srcrev, inclusive=False):
744 """return the first ancestor of <srcrev> introducing <fnode>
744 """return the first ancestor of <srcrev> introducing <fnode>
745
745
746 If the linkrev of the file revision does not point to an ancestor of
746 If the linkrev of the file revision does not point to an ancestor of
747 srcrev, we'll walk down the ancestors until we find one introducing
747 srcrev, we'll walk down the ancestors until we find one introducing
748 this file revision.
748 this file revision.
749
749
750 :repo: a localrepository object (used to access changelog and manifest)
750 :repo: a localrepository object (used to access changelog and manifest)
751 :path: the file path
751 :path: the file path
752 :fnode: the nodeid of the file revision
752 :fnode: the nodeid of the file revision
753 :filelog: the filelog of this path
753 :filelog: the filelog of this path
754 :srcrev: the changeset revision we search ancestors from
754 :srcrev: the changeset revision we search ancestors from
755 :inclusive: if true, the src revision will also be checked
755 :inclusive: if true, the src revision will also be checked
756 """
756 """
757 repo = self._repo
757 repo = self._repo
758 cl = repo.unfiltered().changelog
758 cl = repo.unfiltered().changelog
759 ma = repo.manifest
759 ma = repo.manifest
760 # fetch the linkrev
760 # fetch the linkrev
761 fr = filelog.rev(fnode)
761 fr = filelog.rev(fnode)
762 lkr = filelog.linkrev(fr)
762 lkr = filelog.linkrev(fr)
763 # hack to reuse ancestor computation when searching for renames
763 # hack to reuse ancestor computation when searching for renames
764 memberanc = getattr(self, '_ancestrycontext', None)
764 memberanc = getattr(self, '_ancestrycontext', None)
765 iteranc = None
765 iteranc = None
766 if srcrev is None:
766 if srcrev is None:
767 # wctx case, used by workingfilectx during mergecopy
767 # wctx case, used by workingfilectx during mergecopy
768 revs = [p.rev() for p in self._repo[None].parents()]
768 revs = [p.rev() for p in self._repo[None].parents()]
769 inclusive = True # we skipped the real (revless) source
769 inclusive = True # we skipped the real (revless) source
770 else:
770 else:
771 revs = [srcrev]
771 revs = [srcrev]
772 if memberanc is None:
772 if memberanc is None:
773 memberanc = iteranc = cl.ancestors(revs, lkr,
773 memberanc = iteranc = cl.ancestors(revs, lkr,
774 inclusive=inclusive)
774 inclusive=inclusive)
775 # check if this linkrev is an ancestor of srcrev
775 # check if this linkrev is an ancestor of srcrev
776 if lkr not in memberanc:
776 if lkr not in memberanc:
777 if iteranc is None:
777 if iteranc is None:
778 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
778 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
779 for a in iteranc:
779 for a in iteranc:
780 ac = cl.read(a) # get changeset data (we avoid object creation)
780 ac = cl.read(a) # get changeset data (we avoid object creation)
781 if path in ac[3]: # checking the 'files' field.
781 if path in ac[3]: # checking the 'files' field.
782 # The file has been touched, check if the content is
782 # The file has been touched, check if the content is
783 # similar to the one we search for.
783 # similar to the one we search for.
784 if fnode == ma.readfast(ac[0]).get(path):
784 if fnode == ma.readfast(ac[0]).get(path):
785 return a
785 return a
786 # In theory, we should never get out of that loop without a result.
786 # In theory, we should never get out of that loop without a result.
787 # But if manifest uses a buggy file revision (not children of the
787 # But if manifest uses a buggy file revision (not children of the
788 # one it replaces) we could. Such a buggy situation will likely
788 # one it replaces) we could. Such a buggy situation will likely
789 # result is crash somewhere else at to some point.
789 # result is crash somewhere else at to some point.
790 return lkr
790 return lkr
791
791
792 def introrev(self):
792 def introrev(self):
793 """return the rev of the changeset which introduced this file revision
793 """return the rev of the changeset which introduced this file revision
794
794
795 This method is different from linkrev because it take into account the
795 This method is different from linkrev because it take into account the
796 changeset the filectx was created from. It ensures the returned
796 changeset the filectx was created from. It ensures the returned
797 revision is one of its ancestors. This prevents bugs from
797 revision is one of its ancestors. This prevents bugs from
798 'linkrev-shadowing' when a file revision is used by multiple
798 'linkrev-shadowing' when a file revision is used by multiple
799 changesets.
799 changesets.
800 """
800 """
801 lkr = self.linkrev()
801 lkr = self.linkrev()
802 attrs = vars(self)
802 attrs = vars(self)
803 noctx = not ('_changeid' in attrs or '_changectx' in attrs)
803 noctx = not ('_changeid' in attrs or '_changectx' in attrs)
804 if noctx or self.rev() == lkr:
804 if noctx or self.rev() == lkr:
805 return self.linkrev()
805 return self.linkrev()
806 return self._adjustlinkrev(self._path, self._filelog, self._filenode,
806 return self._adjustlinkrev(self._path, self._filelog, self._filenode,
807 self.rev(), inclusive=True)
807 self.rev(), inclusive=True)
808
808
809 def parents(self):
809 def parents(self):
810 _path = self._path
810 _path = self._path
811 fl = self._filelog
811 fl = self._filelog
812 parents = self._filelog.parents(self._filenode)
812 parents = self._filelog.parents(self._filenode)
813 pl = [(_path, node, fl) for node in parents if node != nullid]
813 pl = [(_path, node, fl) for node in parents if node != nullid]
814
814
815 r = fl.renamed(self._filenode)
815 r = fl.renamed(self._filenode)
816 if r:
816 if r:
817 # - In the simple rename case, both parent are nullid, pl is empty.
817 # - In the simple rename case, both parent are nullid, pl is empty.
818 # - In case of merge, only one of the parent is null id and should
818 # - In case of merge, only one of the parent is null id and should
819 # be replaced with the rename information. This parent is -always-
819 # be replaced with the rename information. This parent is -always-
820 # the first one.
820 # the first one.
821 #
821 #
822 # As null id have always been filtered out in the previous list
822 # As null id have always been filtered out in the previous list
823 # comprehension, inserting to 0 will always result in "replacing
823 # comprehension, inserting to 0 will always result in "replacing
824 # first nullid parent with rename information.
824 # first nullid parent with rename information.
825 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
825 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
826
826
827 ret = []
827 ret = []
828 for path, fnode, l in pl:
828 for path, fnode, l in pl:
829 if '_changeid' in vars(self) or '_changectx' in vars(self):
829 if '_changeid' in vars(self) or '_changectx' in vars(self):
830 # If self is associated with a changeset (probably explicitly
830 # If self is associated with a changeset (probably explicitly
831 # fed), ensure the created filectx is associated with a
831 # fed), ensure the created filectx is associated with a
832 # changeset that is an ancestor of self.changectx.
832 # changeset that is an ancestor of self.changectx.
833 # This lets us later use _adjustlinkrev to get a correct link.
833 # This lets us later use _adjustlinkrev to get a correct link.
834 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
834 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
835 fctx._descendantrev = self.rev()
835 fctx._descendantrev = self.rev()
836 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
836 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
837 elif '_descendantrev' in vars(self):
837 elif '_descendantrev' in vars(self):
838 # Otherwise propagate _descendantrev if we have one associated.
838 # Otherwise propagate _descendantrev if we have one associated.
839 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
839 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
840 fctx._descendantrev = self._descendantrev
840 fctx._descendantrev = self._descendantrev
841 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
841 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
842 else:
842 else:
843 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
843 fctx = filectx(self._repo, path, fileid=fnode, filelog=l)
844 ret.append(fctx)
844 ret.append(fctx)
845 return ret
845 return ret
846
846
847 def p1(self):
847 def p1(self):
848 return self.parents()[0]
848 return self.parents()[0]
849
849
850 def p2(self):
850 def p2(self):
851 p = self.parents()
851 p = self.parents()
852 if len(p) == 2:
852 if len(p) == 2:
853 return p[1]
853 return p[1]
854 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
854 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
855
855
856 def annotate(self, follow=False, linenumber=None, diffopts=None):
856 def annotate(self, follow=False, linenumber=None, diffopts=None):
857 '''returns a list of tuples of (ctx, line) for each line
857 '''returns a list of tuples of (ctx, line) for each line
858 in the file, where ctx is the filectx of the node where
858 in the file, where ctx is the filectx of the node where
859 that line was last changed.
859 that line was last changed.
860 This returns tuples of ((ctx, linenumber), line) for each line,
860 This returns tuples of ((ctx, linenumber), line) for each line,
861 if "linenumber" parameter is NOT "None".
861 if "linenumber" parameter is NOT "None".
862 In such tuples, linenumber means one at the first appearance
862 In such tuples, linenumber means one at the first appearance
863 in the managed file.
863 in the managed file.
864 To reduce annotation cost,
864 To reduce annotation cost,
865 this returns fixed value(False is used) as linenumber,
865 this returns fixed value(False is used) as linenumber,
866 if "linenumber" parameter is "False".'''
866 if "linenumber" parameter is "False".'''
867
867
868 if linenumber is None:
868 if linenumber is None:
869 def decorate(text, rev):
869 def decorate(text, rev):
870 return ([rev] * len(text.splitlines()), text)
870 return ([rev] * len(text.splitlines()), text)
871 elif linenumber:
871 elif linenumber:
872 def decorate(text, rev):
872 def decorate(text, rev):
873 size = len(text.splitlines())
873 size = len(text.splitlines())
874 return ([(rev, i) for i in xrange(1, size + 1)], text)
874 return ([(rev, i) for i in xrange(1, size + 1)], text)
875 else:
875 else:
876 def decorate(text, rev):
876 def decorate(text, rev):
877 return ([(rev, False)] * len(text.splitlines()), text)
877 return ([(rev, False)] * len(text.splitlines()), text)
878
878
879 def pair(parent, child):
879 def pair(parent, child):
880 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
880 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
881 refine=True)
881 refine=True)
882 for (a1, a2, b1, b2), t in blocks:
882 for (a1, a2, b1, b2), t in blocks:
883 # Changed blocks ('!') or blocks made only of blank lines ('~')
883 # Changed blocks ('!') or blocks made only of blank lines ('~')
884 # belong to the child.
884 # belong to the child.
885 if t == '=':
885 if t == '=':
886 child[0][b1:b2] = parent[0][a1:a2]
886 child[0][b1:b2] = parent[0][a1:a2]
887 return child
887 return child
888
888
889 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
889 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
890
890
891 def parents(f):
891 def parents(f):
892 pl = f.parents()
892 pl = f.parents()
893
893
894 # Don't return renamed parents if we aren't following.
894 # Don't return renamed parents if we aren't following.
895 if not follow:
895 if not follow:
896 pl = [p for p in pl if p.path() == f.path()]
896 pl = [p for p in pl if p.path() == f.path()]
897
897
898 # renamed filectx won't have a filelog yet, so set it
898 # renamed filectx won't have a filelog yet, so set it
899 # from the cache to save time
899 # from the cache to save time
900 for p in pl:
900 for p in pl:
901 if not '_filelog' in p.__dict__:
901 if not '_filelog' in p.__dict__:
902 p._filelog = getlog(p.path())
902 p._filelog = getlog(p.path())
903
903
904 return pl
904 return pl
905
905
906 # use linkrev to find the first changeset where self appeared
906 # use linkrev to find the first changeset where self appeared
907 base = self
907 base = self
908 introrev = self.introrev()
908 introrev = self.introrev()
909 if self.rev() != introrev:
909 if self.rev() != introrev:
910 base = self.filectx(self.filenode(), changeid=introrev)
910 base = self.filectx(self.filenode(), changeid=introrev)
911 ac = self._repo.changelog.ancestors([introrev], inclusive=True)
911 ac = self._repo.changelog.ancestors([introrev], inclusive=True)
912 base._ancestrycontext = ac
912 base._ancestrycontext = ac
913
913
914 # This algorithm would prefer to be recursive, but Python is a
914 # This algorithm would prefer to be recursive, but Python is a
915 # bit recursion-hostile. Instead we do an iterative
915 # bit recursion-hostile. Instead we do an iterative
916 # depth-first search.
916 # depth-first search.
917
917
918 visit = [base]
918 visit = [base]
919 hist = {}
919 hist = {}
920 pcache = {}
920 pcache = {}
921 needed = {base: 1}
921 needed = {base: 1}
922 while visit:
922 while visit:
923 f = visit[-1]
923 f = visit[-1]
924 pcached = f in pcache
924 pcached = f in pcache
925 if not pcached:
925 if not pcached:
926 pcache[f] = parents(f)
926 pcache[f] = parents(f)
927
927
928 ready = True
928 ready = True
929 pl = pcache[f]
929 pl = pcache[f]
930 for p in pl:
930 for p in pl:
931 if p not in hist:
931 if p not in hist:
932 ready = False
932 ready = False
933 visit.append(p)
933 visit.append(p)
934 if not pcached:
934 if not pcached:
935 needed[p] = needed.get(p, 0) + 1
935 needed[p] = needed.get(p, 0) + 1
936 if ready:
936 if ready:
937 visit.pop()
937 visit.pop()
938 reusable = f in hist
938 reusable = f in hist
939 if reusable:
939 if reusable:
940 curr = hist[f]
940 curr = hist[f]
941 else:
941 else:
942 curr = decorate(f.data(), f)
942 curr = decorate(f.data(), f)
943 for p in pl:
943 for p in pl:
944 if not reusable:
944 if not reusable:
945 curr = pair(hist[p], curr)
945 curr = pair(hist[p], curr)
946 if needed[p] == 1:
946 if needed[p] == 1:
947 del hist[p]
947 del hist[p]
948 del needed[p]
948 del needed[p]
949 else:
949 else:
950 needed[p] -= 1
950 needed[p] -= 1
951
951
952 hist[f] = curr
952 hist[f] = curr
953 pcache[f] = []
953 pcache[f] = []
954
954
955 return zip(hist[base][0], hist[base][1].splitlines(True))
955 return zip(hist[base][0], hist[base][1].splitlines(True))
956
956
957 def ancestors(self, followfirst=False):
957 def ancestors(self, followfirst=False):
958 visit = {}
958 visit = {}
959 c = self
959 c = self
960 if followfirst:
960 if followfirst:
961 cut = 1
961 cut = 1
962 else:
962 else:
963 cut = None
963 cut = None
964
964
965 while True:
965 while True:
966 for parent in c.parents()[:cut]:
966 for parent in c.parents()[:cut]:
967 visit[(parent.linkrev(), parent.filenode())] = parent
967 visit[(parent.linkrev(), parent.filenode())] = parent
968 if not visit:
968 if not visit:
969 break
969 break
970 c = visit.pop(max(visit))
970 c = visit.pop(max(visit))
971 yield c
971 yield c
972
972
973 class filectx(basefilectx):
973 class filectx(basefilectx):
974 """A filecontext object makes access to data related to a particular
974 """A filecontext object makes access to data related to a particular
975 filerevision convenient."""
975 filerevision convenient."""
976 def __init__(self, repo, path, changeid=None, fileid=None,
976 def __init__(self, repo, path, changeid=None, fileid=None,
977 filelog=None, changectx=None):
977 filelog=None, changectx=None):
978 """changeid can be a changeset revision, node, or tag.
978 """changeid can be a changeset revision, node, or tag.
979 fileid can be a file revision or node."""
979 fileid can be a file revision or node."""
980 self._repo = repo
980 self._repo = repo
981 self._path = path
981 self._path = path
982
982
983 assert (changeid is not None
983 assert (changeid is not None
984 or fileid is not None
984 or fileid is not None
985 or changectx is not None), \
985 or changectx is not None), \
986 ("bad args: changeid=%r, fileid=%r, changectx=%r"
986 ("bad args: changeid=%r, fileid=%r, changectx=%r"
987 % (changeid, fileid, changectx))
987 % (changeid, fileid, changectx))
988
988
989 if filelog is not None:
989 if filelog is not None:
990 self._filelog = filelog
990 self._filelog = filelog
991
991
992 if changeid is not None:
992 if changeid is not None:
993 self._changeid = changeid
993 self._changeid = changeid
994 if changectx is not None:
994 if changectx is not None:
995 self._changectx = changectx
995 self._changectx = changectx
996 if fileid is not None:
996 if fileid is not None:
997 self._fileid = fileid
997 self._fileid = fileid
998
998
999 @propertycache
999 @propertycache
1000 def _changectx(self):
1000 def _changectx(self):
1001 try:
1001 try:
1002 return changectx(self._repo, self._changeid)
1002 return changectx(self._repo, self._changeid)
1003 except error.FilteredRepoLookupError:
1003 except error.FilteredRepoLookupError:
1004 # Linkrev may point to any revision in the repository. When the
1004 # Linkrev may point to any revision in the repository. When the
1005 # repository is filtered this may lead to `filectx` trying to build
1005 # repository is filtered this may lead to `filectx` trying to build
1006 # `changectx` for filtered revision. In such case we fallback to
1006 # `changectx` for filtered revision. In such case we fallback to
1007 # creating `changectx` on the unfiltered version of the reposition.
1007 # creating `changectx` on the unfiltered version of the reposition.
1008 # This fallback should not be an issue because `changectx` from
1008 # This fallback should not be an issue because `changectx` from
1009 # `filectx` are not used in complex operations that care about
1009 # `filectx` are not used in complex operations that care about
1010 # filtering.
1010 # filtering.
1011 #
1011 #
1012 # This fallback is a cheap and dirty fix that prevent several
1012 # This fallback is a cheap and dirty fix that prevent several
1013 # crashes. It does not ensure the behavior is correct. However the
1013 # crashes. It does not ensure the behavior is correct. However the
1014 # behavior was not correct before filtering either and "incorrect
1014 # behavior was not correct before filtering either and "incorrect
1015 # behavior" is seen as better as "crash"
1015 # behavior" is seen as better as "crash"
1016 #
1016 #
1017 # Linkrevs have several serious troubles with filtering that are
1017 # Linkrevs have several serious troubles with filtering that are
1018 # complicated to solve. Proper handling of the issue here should be
1018 # complicated to solve. Proper handling of the issue here should be
1019 # considered when solving linkrev issue are on the table.
1019 # considered when solving linkrev issue are on the table.
1020 return changectx(self._repo.unfiltered(), self._changeid)
1020 return changectx(self._repo.unfiltered(), self._changeid)
1021
1021
1022 def filectx(self, fileid, changeid=None):
1022 def filectx(self, fileid, changeid=None):
1023 '''opens an arbitrary revision of the file without
1023 '''opens an arbitrary revision of the file without
1024 opening a new filelog'''
1024 opening a new filelog'''
1025 return filectx(self._repo, self._path, fileid=fileid,
1025 return filectx(self._repo, self._path, fileid=fileid,
1026 filelog=self._filelog, changeid=changeid)
1026 filelog=self._filelog, changeid=changeid)
1027
1027
1028 def data(self):
1028 def data(self):
1029 try:
1029 try:
1030 return self._filelog.read(self._filenode)
1030 return self._filelog.read(self._filenode)
1031 except error.CensoredNodeError:
1031 except error.CensoredNodeError:
1032 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
1032 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
1033 return ""
1033 return ""
1034 raise util.Abort(_("censored node: %s") % short(self._filenode),
1034 raise util.Abort(_("censored node: %s") % short(self._filenode),
1035 hint=_("set censor.policy to ignore errors"))
1035 hint=_("set censor.policy to ignore errors"))
1036
1036
1037 def size(self):
1037 def size(self):
1038 return self._filelog.size(self._filerev)
1038 return self._filelog.size(self._filerev)
1039
1039
1040 def renamed(self):
1040 def renamed(self):
1041 """check if file was actually renamed in this changeset revision
1041 """check if file was actually renamed in this changeset revision
1042
1042
1043 If rename logged in file revision, we report copy for changeset only
1043 If rename logged in file revision, we report copy for changeset only
1044 if file revisions linkrev points back to the changeset in question
1044 if file revisions linkrev points back to the changeset in question
1045 or both changeset parents contain different file revisions.
1045 or both changeset parents contain different file revisions.
1046 """
1046 """
1047
1047
1048 renamed = self._filelog.renamed(self._filenode)
1048 renamed = self._filelog.renamed(self._filenode)
1049 if not renamed:
1049 if not renamed:
1050 return renamed
1050 return renamed
1051
1051
1052 if self.rev() == self.linkrev():
1052 if self.rev() == self.linkrev():
1053 return renamed
1053 return renamed
1054
1054
1055 name = self.path()
1055 name = self.path()
1056 fnode = self._filenode
1056 fnode = self._filenode
1057 for p in self._changectx.parents():
1057 for p in self._changectx.parents():
1058 try:
1058 try:
1059 if fnode == p.filenode(name):
1059 if fnode == p.filenode(name):
1060 return None
1060 return None
1061 except error.LookupError:
1061 except error.LookupError:
1062 pass
1062 pass
1063 return renamed
1063 return renamed
1064
1064
1065 def children(self):
1065 def children(self):
1066 # hard for renames
1066 # hard for renames
1067 c = self._filelog.children(self._filenode)
1067 c = self._filelog.children(self._filenode)
1068 return [filectx(self._repo, self._path, fileid=x,
1068 return [filectx(self._repo, self._path, fileid=x,
1069 filelog=self._filelog) for x in c]
1069 filelog=self._filelog) for x in c]
1070
1070
1071 class committablectx(basectx):
1071 class committablectx(basectx):
1072 """A committablectx object provides common functionality for a context that
1072 """A committablectx object provides common functionality for a context that
1073 wants the ability to commit, e.g. workingctx or memctx."""
1073 wants the ability to commit, e.g. workingctx or memctx."""
1074 def __init__(self, repo, text="", user=None, date=None, extra=None,
1074 def __init__(self, repo, text="", user=None, date=None, extra=None,
1075 changes=None):
1075 changes=None):
1076 self._repo = repo
1076 self._repo = repo
1077 self._rev = None
1077 self._rev = None
1078 self._node = None
1078 self._node = None
1079 self._text = text
1079 self._text = text
1080 if date:
1080 if date:
1081 self._date = util.parsedate(date)
1081 self._date = util.parsedate(date)
1082 if user:
1082 if user:
1083 self._user = user
1083 self._user = user
1084 if changes:
1084 if changes:
1085 self._status = changes
1085 self._status = changes
1086
1086
1087 self._extra = {}
1087 self._extra = {}
1088 if extra:
1088 if extra:
1089 self._extra = extra.copy()
1089 self._extra = extra.copy()
1090 if 'branch' not in self._extra:
1090 if 'branch' not in self._extra:
1091 try:
1091 try:
1092 branch = encoding.fromlocal(self._repo.dirstate.branch())
1092 branch = encoding.fromlocal(self._repo.dirstate.branch())
1093 except UnicodeDecodeError:
1093 except UnicodeDecodeError:
1094 raise util.Abort(_('branch name not in UTF-8!'))
1094 raise util.Abort(_('branch name not in UTF-8!'))
1095 self._extra['branch'] = branch
1095 self._extra['branch'] = branch
1096 if self._extra['branch'] == '':
1096 if self._extra['branch'] == '':
1097 self._extra['branch'] = 'default'
1097 self._extra['branch'] = 'default'
1098
1098
1099 def __str__(self):
1099 def __str__(self):
1100 return str(self._parents[0]) + "+"
1100 return str(self._parents[0]) + "+"
1101
1101
1102 def __nonzero__(self):
1102 def __nonzero__(self):
1103 return True
1103 return True
1104
1104
1105 def _buildflagfunc(self):
1105 def _buildflagfunc(self):
1106 # Create a fallback function for getting file flags when the
1106 # Create a fallback function for getting file flags when the
1107 # filesystem doesn't support them
1107 # filesystem doesn't support them
1108
1108
1109 copiesget = self._repo.dirstate.copies().get
1109 copiesget = self._repo.dirstate.copies().get
1110
1110
1111 if len(self._parents) < 2:
1111 if len(self._parents) < 2:
1112 # when we have one parent, it's easy: copy from parent
1112 # when we have one parent, it's easy: copy from parent
1113 man = self._parents[0].manifest()
1113 man = self._parents[0].manifest()
1114 def func(f):
1114 def func(f):
1115 f = copiesget(f, f)
1115 f = copiesget(f, f)
1116 return man.flags(f)
1116 return man.flags(f)
1117 else:
1117 else:
1118 # merges are tricky: we try to reconstruct the unstored
1118 # merges are tricky: we try to reconstruct the unstored
1119 # result from the merge (issue1802)
1119 # result from the merge (issue1802)
1120 p1, p2 = self._parents
1120 p1, p2 = self._parents
1121 pa = p1.ancestor(p2)
1121 pa = p1.ancestor(p2)
1122 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1122 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1123
1123
1124 def func(f):
1124 def func(f):
1125 f = copiesget(f, f) # may be wrong for merges with copies
1125 f = copiesget(f, f) # may be wrong for merges with copies
1126 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1126 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1127 if fl1 == fl2:
1127 if fl1 == fl2:
1128 return fl1
1128 return fl1
1129 if fl1 == fla:
1129 if fl1 == fla:
1130 return fl2
1130 return fl2
1131 if fl2 == fla:
1131 if fl2 == fla:
1132 return fl1
1132 return fl1
1133 return '' # punt for conflicts
1133 return '' # punt for conflicts
1134
1134
1135 return func
1135 return func
1136
1136
1137 @propertycache
1137 @propertycache
1138 def _flagfunc(self):
1138 def _flagfunc(self):
1139 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1139 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1140
1140
1141 @propertycache
1141 @propertycache
1142 def _manifest(self):
1142 def _manifest(self):
1143 """generate a manifest corresponding to the values in self._status
1143 """generate a manifest corresponding to the values in self._status
1144
1144
1145 This reuse the file nodeid from parent, but we append an extra letter
1145 This reuse the file nodeid from parent, but we append an extra letter
1146 when modified. Modified files get an extra 'm' while added files get
1146 when modified. Modified files get an extra 'm' while added files get
1147 an extra 'a'. This is used by manifests merge to see that files
1147 an extra 'a'. This is used by manifests merge to see that files
1148 are different and by update logic to avoid deleting newly added files.
1148 are different and by update logic to avoid deleting newly added files.
1149 """
1149 """
1150
1150
1151 man1 = self._parents[0].manifest()
1151 man1 = self._parents[0].manifest()
1152 man = man1.copy()
1152 man = man1.copy()
1153 if len(self._parents) > 1:
1153 if len(self._parents) > 1:
1154 man2 = self.p2().manifest()
1154 man2 = self.p2().manifest()
1155 def getman(f):
1155 def getman(f):
1156 if f in man1:
1156 if f in man1:
1157 return man1
1157 return man1
1158 return man2
1158 return man2
1159 else:
1159 else:
1160 getman = lambda f: man1
1160 getman = lambda f: man1
1161
1161
1162 copied = self._repo.dirstate.copies()
1162 copied = self._repo.dirstate.copies()
1163 ff = self._flagfunc
1163 ff = self._flagfunc
1164 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1164 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1165 for f in l:
1165 for f in l:
1166 orig = copied.get(f, f)
1166 orig = copied.get(f, f)
1167 man[f] = getman(orig).get(orig, nullid) + i
1167 man[f] = getman(orig).get(orig, nullid) + i
1168 try:
1168 try:
1169 man.setflag(f, ff(f))
1169 man.setflag(f, ff(f))
1170 except OSError:
1170 except OSError:
1171 pass
1171 pass
1172
1172
1173 for f in self._status.deleted + self._status.removed:
1173 for f in self._status.deleted + self._status.removed:
1174 if f in man:
1174 if f in man:
1175 del man[f]
1175 del man[f]
1176
1176
1177 return man
1177 return man
1178
1178
1179 @propertycache
1179 @propertycache
1180 def _status(self):
1180 def _status(self):
1181 return self._repo.status()
1181 return self._repo.status()
1182
1182
1183 @propertycache
1183 @propertycache
1184 def _user(self):
1184 def _user(self):
1185 return self._repo.ui.username()
1185 return self._repo.ui.username()
1186
1186
1187 @propertycache
1187 @propertycache
1188 def _date(self):
1188 def _date(self):
1189 return util.makedate()
1189 return util.makedate()
1190
1190
1191 def subrev(self, subpath):
1191 def subrev(self, subpath):
1192 return None
1192 return None
1193
1193
1194 def manifestnode(self):
1195 return None
1194 def user(self):
1196 def user(self):
1195 return self._user or self._repo.ui.username()
1197 return self._user or self._repo.ui.username()
1196 def date(self):
1198 def date(self):
1197 return self._date
1199 return self._date
1198 def description(self):
1200 def description(self):
1199 return self._text
1201 return self._text
1200 def files(self):
1202 def files(self):
1201 return sorted(self._status.modified + self._status.added +
1203 return sorted(self._status.modified + self._status.added +
1202 self._status.removed)
1204 self._status.removed)
1203
1205
1204 def modified(self):
1206 def modified(self):
1205 return self._status.modified
1207 return self._status.modified
1206 def added(self):
1208 def added(self):
1207 return self._status.added
1209 return self._status.added
1208 def removed(self):
1210 def removed(self):
1209 return self._status.removed
1211 return self._status.removed
1210 def deleted(self):
1212 def deleted(self):
1211 return self._status.deleted
1213 return self._status.deleted
1212 def branch(self):
1214 def branch(self):
1213 return encoding.tolocal(self._extra['branch'])
1215 return encoding.tolocal(self._extra['branch'])
1214 def closesbranch(self):
1216 def closesbranch(self):
1215 return 'close' in self._extra
1217 return 'close' in self._extra
1216 def extra(self):
1218 def extra(self):
1217 return self._extra
1219 return self._extra
1218
1220
1219 def tags(self):
1221 def tags(self):
1220 t = []
1222 t = []
1221 for p in self.parents():
1223 for p in self.parents():
1222 t.extend(p.tags())
1224 t.extend(p.tags())
1223 return t
1225 return t
1224
1226
1225 def bookmarks(self):
1227 def bookmarks(self):
1226 b = []
1228 b = []
1227 for p in self.parents():
1229 for p in self.parents():
1228 b.extend(p.bookmarks())
1230 b.extend(p.bookmarks())
1229 return b
1231 return b
1230
1232
1231 def phase(self):
1233 def phase(self):
1232 phase = phases.draft # default phase to draft
1234 phase = phases.draft # default phase to draft
1233 for p in self.parents():
1235 for p in self.parents():
1234 phase = max(phase, p.phase())
1236 phase = max(phase, p.phase())
1235 return phase
1237 return phase
1236
1238
1237 def hidden(self):
1239 def hidden(self):
1238 return False
1240 return False
1239
1241
1240 def children(self):
1242 def children(self):
1241 return []
1243 return []
1242
1244
1243 def flags(self, path):
1245 def flags(self, path):
1244 if '_manifest' in self.__dict__:
1246 if '_manifest' in self.__dict__:
1245 try:
1247 try:
1246 return self._manifest.flags(path)
1248 return self._manifest.flags(path)
1247 except KeyError:
1249 except KeyError:
1248 return ''
1250 return ''
1249
1251
1250 try:
1252 try:
1251 return self._flagfunc(path)
1253 return self._flagfunc(path)
1252 except OSError:
1254 except OSError:
1253 return ''
1255 return ''
1254
1256
1255 def ancestor(self, c2):
1257 def ancestor(self, c2):
1256 """return the "best" ancestor context of self and c2"""
1258 """return the "best" ancestor context of self and c2"""
1257 return self._parents[0].ancestor(c2) # punt on two parents for now
1259 return self._parents[0].ancestor(c2) # punt on two parents for now
1258
1260
1259 def walk(self, match):
1261 def walk(self, match):
1260 '''Generates matching file names.'''
1262 '''Generates matching file names.'''
1261 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1263 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1262 True, False))
1264 True, False))
1263
1265
1264 def matches(self, match):
1266 def matches(self, match):
1265 return sorted(self._repo.dirstate.matches(match))
1267 return sorted(self._repo.dirstate.matches(match))
1266
1268
1267 def ancestors(self):
1269 def ancestors(self):
1268 for p in self._parents:
1270 for p in self._parents:
1269 yield p
1271 yield p
1270 for a in self._repo.changelog.ancestors(
1272 for a in self._repo.changelog.ancestors(
1271 [p.rev() for p in self._parents]):
1273 [p.rev() for p in self._parents]):
1272 yield changectx(self._repo, a)
1274 yield changectx(self._repo, a)
1273
1275
1274 def markcommitted(self, node):
1276 def markcommitted(self, node):
1275 """Perform post-commit cleanup necessary after committing this ctx
1277 """Perform post-commit cleanup necessary after committing this ctx
1276
1278
1277 Specifically, this updates backing stores this working context
1279 Specifically, this updates backing stores this working context
1278 wraps to reflect the fact that the changes reflected by this
1280 wraps to reflect the fact that the changes reflected by this
1279 workingctx have been committed. For example, it marks
1281 workingctx have been committed. For example, it marks
1280 modified and added files as normal in the dirstate.
1282 modified and added files as normal in the dirstate.
1281
1283
1282 """
1284 """
1283
1285
1284 self._repo.dirstate.beginparentchange()
1286 self._repo.dirstate.beginparentchange()
1285 for f in self.modified() + self.added():
1287 for f in self.modified() + self.added():
1286 self._repo.dirstate.normal(f)
1288 self._repo.dirstate.normal(f)
1287 for f in self.removed():
1289 for f in self.removed():
1288 self._repo.dirstate.drop(f)
1290 self._repo.dirstate.drop(f)
1289 self._repo.dirstate.setparents(node)
1291 self._repo.dirstate.setparents(node)
1290 self._repo.dirstate.endparentchange()
1292 self._repo.dirstate.endparentchange()
1291
1293
1292 class workingctx(committablectx):
1294 class workingctx(committablectx):
1293 """A workingctx object makes access to data related to
1295 """A workingctx object makes access to data related to
1294 the current working directory convenient.
1296 the current working directory convenient.
1295 date - any valid date string or (unixtime, offset), or None.
1297 date - any valid date string or (unixtime, offset), or None.
1296 user - username string, or None.
1298 user - username string, or None.
1297 extra - a dictionary of extra values, or None.
1299 extra - a dictionary of extra values, or None.
1298 changes - a list of file lists as returned by localrepo.status()
1300 changes - a list of file lists as returned by localrepo.status()
1299 or None to use the repository status.
1301 or None to use the repository status.
1300 """
1302 """
1301 def __init__(self, repo, text="", user=None, date=None, extra=None,
1303 def __init__(self, repo, text="", user=None, date=None, extra=None,
1302 changes=None):
1304 changes=None):
1303 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1305 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1304
1306
1305 def __iter__(self):
1307 def __iter__(self):
1306 d = self._repo.dirstate
1308 d = self._repo.dirstate
1307 for f in d:
1309 for f in d:
1308 if d[f] != 'r':
1310 if d[f] != 'r':
1309 yield f
1311 yield f
1310
1312
1311 def __contains__(self, key):
1313 def __contains__(self, key):
1312 return self._repo.dirstate[key] not in "?r"
1314 return self._repo.dirstate[key] not in "?r"
1313
1315
1314 @propertycache
1316 @propertycache
1315 def _parents(self):
1317 def _parents(self):
1316 p = self._repo.dirstate.parents()
1318 p = self._repo.dirstate.parents()
1317 if p[1] == nullid:
1319 if p[1] == nullid:
1318 p = p[:-1]
1320 p = p[:-1]
1319 return [changectx(self._repo, x) for x in p]
1321 return [changectx(self._repo, x) for x in p]
1320
1322
1321 def filectx(self, path, filelog=None):
1323 def filectx(self, path, filelog=None):
1322 """get a file context from the working directory"""
1324 """get a file context from the working directory"""
1323 return workingfilectx(self._repo, path, workingctx=self,
1325 return workingfilectx(self._repo, path, workingctx=self,
1324 filelog=filelog)
1326 filelog=filelog)
1325
1327
1326 def dirty(self, missing=False, merge=True, branch=True):
1328 def dirty(self, missing=False, merge=True, branch=True):
1327 "check whether a working directory is modified"
1329 "check whether a working directory is modified"
1328 # check subrepos first
1330 # check subrepos first
1329 for s in sorted(self.substate):
1331 for s in sorted(self.substate):
1330 if self.sub(s).dirty():
1332 if self.sub(s).dirty():
1331 return True
1333 return True
1332 # check current working dir
1334 # check current working dir
1333 return ((merge and self.p2()) or
1335 return ((merge and self.p2()) or
1334 (branch and self.branch() != self.p1().branch()) or
1336 (branch and self.branch() != self.p1().branch()) or
1335 self.modified() or self.added() or self.removed() or
1337 self.modified() or self.added() or self.removed() or
1336 (missing and self.deleted()))
1338 (missing and self.deleted()))
1337
1339
1338 def add(self, list, prefix=""):
1340 def add(self, list, prefix=""):
1339 join = lambda f: os.path.join(prefix, f)
1341 join = lambda f: os.path.join(prefix, f)
1340 wlock = self._repo.wlock()
1342 wlock = self._repo.wlock()
1341 ui, ds = self._repo.ui, self._repo.dirstate
1343 ui, ds = self._repo.ui, self._repo.dirstate
1342 try:
1344 try:
1343 rejected = []
1345 rejected = []
1344 lstat = self._repo.wvfs.lstat
1346 lstat = self._repo.wvfs.lstat
1345 for f in list:
1347 for f in list:
1346 scmutil.checkportable(ui, join(f))
1348 scmutil.checkportable(ui, join(f))
1347 try:
1349 try:
1348 st = lstat(f)
1350 st = lstat(f)
1349 except OSError:
1351 except OSError:
1350 ui.warn(_("%s does not exist!\n") % join(f))
1352 ui.warn(_("%s does not exist!\n") % join(f))
1351 rejected.append(f)
1353 rejected.append(f)
1352 continue
1354 continue
1353 if st.st_size > 10000000:
1355 if st.st_size > 10000000:
1354 ui.warn(_("%s: up to %d MB of RAM may be required "
1356 ui.warn(_("%s: up to %d MB of RAM may be required "
1355 "to manage this file\n"
1357 "to manage this file\n"
1356 "(use 'hg revert %s' to cancel the "
1358 "(use 'hg revert %s' to cancel the "
1357 "pending addition)\n")
1359 "pending addition)\n")
1358 % (f, 3 * st.st_size // 1000000, join(f)))
1360 % (f, 3 * st.st_size // 1000000, join(f)))
1359 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1361 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1360 ui.warn(_("%s not added: only files and symlinks "
1362 ui.warn(_("%s not added: only files and symlinks "
1361 "supported currently\n") % join(f))
1363 "supported currently\n") % join(f))
1362 rejected.append(f)
1364 rejected.append(f)
1363 elif ds[f] in 'amn':
1365 elif ds[f] in 'amn':
1364 ui.warn(_("%s already tracked!\n") % join(f))
1366 ui.warn(_("%s already tracked!\n") % join(f))
1365 elif ds[f] == 'r':
1367 elif ds[f] == 'r':
1366 ds.normallookup(f)
1368 ds.normallookup(f)
1367 else:
1369 else:
1368 ds.add(f)
1370 ds.add(f)
1369 return rejected
1371 return rejected
1370 finally:
1372 finally:
1371 wlock.release()
1373 wlock.release()
1372
1374
1373 def forget(self, files, prefix=""):
1375 def forget(self, files, prefix=""):
1374 join = lambda f: os.path.join(prefix, f)
1376 join = lambda f: os.path.join(prefix, f)
1375 wlock = self._repo.wlock()
1377 wlock = self._repo.wlock()
1376 try:
1378 try:
1377 rejected = []
1379 rejected = []
1378 for f in files:
1380 for f in files:
1379 if f not in self._repo.dirstate:
1381 if f not in self._repo.dirstate:
1380 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1382 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1381 rejected.append(f)
1383 rejected.append(f)
1382 elif self._repo.dirstate[f] != 'a':
1384 elif self._repo.dirstate[f] != 'a':
1383 self._repo.dirstate.remove(f)
1385 self._repo.dirstate.remove(f)
1384 else:
1386 else:
1385 self._repo.dirstate.drop(f)
1387 self._repo.dirstate.drop(f)
1386 return rejected
1388 return rejected
1387 finally:
1389 finally:
1388 wlock.release()
1390 wlock.release()
1389
1391
1390 def undelete(self, list):
1392 def undelete(self, list):
1391 pctxs = self.parents()
1393 pctxs = self.parents()
1392 wlock = self._repo.wlock()
1394 wlock = self._repo.wlock()
1393 try:
1395 try:
1394 for f in list:
1396 for f in list:
1395 if self._repo.dirstate[f] != 'r':
1397 if self._repo.dirstate[f] != 'r':
1396 self._repo.ui.warn(_("%s not removed!\n") % f)
1398 self._repo.ui.warn(_("%s not removed!\n") % f)
1397 else:
1399 else:
1398 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1400 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1399 t = fctx.data()
1401 t = fctx.data()
1400 self._repo.wwrite(f, t, fctx.flags())
1402 self._repo.wwrite(f, t, fctx.flags())
1401 self._repo.dirstate.normal(f)
1403 self._repo.dirstate.normal(f)
1402 finally:
1404 finally:
1403 wlock.release()
1405 wlock.release()
1404
1406
1405 def copy(self, source, dest):
1407 def copy(self, source, dest):
1406 try:
1408 try:
1407 st = self._repo.wvfs.lstat(dest)
1409 st = self._repo.wvfs.lstat(dest)
1408 except OSError, err:
1410 except OSError, err:
1409 if err.errno != errno.ENOENT:
1411 if err.errno != errno.ENOENT:
1410 raise
1412 raise
1411 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1413 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1412 return
1414 return
1413 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1415 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1414 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1416 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1415 "symbolic link\n") % dest)
1417 "symbolic link\n") % dest)
1416 else:
1418 else:
1417 wlock = self._repo.wlock()
1419 wlock = self._repo.wlock()
1418 try:
1420 try:
1419 if self._repo.dirstate[dest] in '?':
1421 if self._repo.dirstate[dest] in '?':
1420 self._repo.dirstate.add(dest)
1422 self._repo.dirstate.add(dest)
1421 elif self._repo.dirstate[dest] in 'r':
1423 elif self._repo.dirstate[dest] in 'r':
1422 self._repo.dirstate.normallookup(dest)
1424 self._repo.dirstate.normallookup(dest)
1423 self._repo.dirstate.copy(source, dest)
1425 self._repo.dirstate.copy(source, dest)
1424 finally:
1426 finally:
1425 wlock.release()
1427 wlock.release()
1426
1428
1427 def _filtersuspectsymlink(self, files):
1429 def _filtersuspectsymlink(self, files):
1428 if not files or self._repo.dirstate._checklink:
1430 if not files or self._repo.dirstate._checklink:
1429 return files
1431 return files
1430
1432
1431 # Symlink placeholders may get non-symlink-like contents
1433 # Symlink placeholders may get non-symlink-like contents
1432 # via user error or dereferencing by NFS or Samba servers,
1434 # via user error or dereferencing by NFS or Samba servers,
1433 # so we filter out any placeholders that don't look like a
1435 # so we filter out any placeholders that don't look like a
1434 # symlink
1436 # symlink
1435 sane = []
1437 sane = []
1436 for f in files:
1438 for f in files:
1437 if self.flags(f) == 'l':
1439 if self.flags(f) == 'l':
1438 d = self[f].data()
1440 d = self[f].data()
1439 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1441 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1440 self._repo.ui.debug('ignoring suspect symlink placeholder'
1442 self._repo.ui.debug('ignoring suspect symlink placeholder'
1441 ' "%s"\n' % f)
1443 ' "%s"\n' % f)
1442 continue
1444 continue
1443 sane.append(f)
1445 sane.append(f)
1444 return sane
1446 return sane
1445
1447
1446 def _checklookup(self, files):
1448 def _checklookup(self, files):
1447 # check for any possibly clean files
1449 # check for any possibly clean files
1448 if not files:
1450 if not files:
1449 return [], []
1451 return [], []
1450
1452
1451 modified = []
1453 modified = []
1452 fixup = []
1454 fixup = []
1453 pctx = self._parents[0]
1455 pctx = self._parents[0]
1454 # do a full compare of any files that might have changed
1456 # do a full compare of any files that might have changed
1455 for f in sorted(files):
1457 for f in sorted(files):
1456 if (f not in pctx or self.flags(f) != pctx.flags(f)
1458 if (f not in pctx or self.flags(f) != pctx.flags(f)
1457 or pctx[f].cmp(self[f])):
1459 or pctx[f].cmp(self[f])):
1458 modified.append(f)
1460 modified.append(f)
1459 else:
1461 else:
1460 fixup.append(f)
1462 fixup.append(f)
1461
1463
1462 # update dirstate for files that are actually clean
1464 # update dirstate for files that are actually clean
1463 if fixup:
1465 if fixup:
1464 try:
1466 try:
1465 # updating the dirstate is optional
1467 # updating the dirstate is optional
1466 # so we don't wait on the lock
1468 # so we don't wait on the lock
1467 # wlock can invalidate the dirstate, so cache normal _after_
1469 # wlock can invalidate the dirstate, so cache normal _after_
1468 # taking the lock
1470 # taking the lock
1469 wlock = self._repo.wlock(False)
1471 wlock = self._repo.wlock(False)
1470 normal = self._repo.dirstate.normal
1472 normal = self._repo.dirstate.normal
1471 try:
1473 try:
1472 for f in fixup:
1474 for f in fixup:
1473 normal(f)
1475 normal(f)
1474 finally:
1476 finally:
1475 wlock.release()
1477 wlock.release()
1476 except error.LockError:
1478 except error.LockError:
1477 pass
1479 pass
1478 return modified, fixup
1480 return modified, fixup
1479
1481
1480 def _manifestmatches(self, match, s):
1482 def _manifestmatches(self, match, s):
1481 """Slow path for workingctx
1483 """Slow path for workingctx
1482
1484
1483 The fast path is when we compare the working directory to its parent
1485 The fast path is when we compare the working directory to its parent
1484 which means this function is comparing with a non-parent; therefore we
1486 which means this function is comparing with a non-parent; therefore we
1485 need to build a manifest and return what matches.
1487 need to build a manifest and return what matches.
1486 """
1488 """
1487 mf = self._repo['.']._manifestmatches(match, s)
1489 mf = self._repo['.']._manifestmatches(match, s)
1488 for f in s.modified + s.added:
1490 for f in s.modified + s.added:
1489 mf[f] = _newnode
1491 mf[f] = _newnode
1490 mf.setflag(f, self.flags(f))
1492 mf.setflag(f, self.flags(f))
1491 for f in s.removed:
1493 for f in s.removed:
1492 if f in mf:
1494 if f in mf:
1493 del mf[f]
1495 del mf[f]
1494 return mf
1496 return mf
1495
1497
1496 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1498 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1497 unknown=False):
1499 unknown=False):
1498 '''Gets the status from the dirstate -- internal use only.'''
1500 '''Gets the status from the dirstate -- internal use only.'''
1499 listignored, listclean, listunknown = ignored, clean, unknown
1501 listignored, listclean, listunknown = ignored, clean, unknown
1500 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1502 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1501 subrepos = []
1503 subrepos = []
1502 if '.hgsub' in self:
1504 if '.hgsub' in self:
1503 subrepos = sorted(self.substate)
1505 subrepos = sorted(self.substate)
1504 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1506 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1505 listclean, listunknown)
1507 listclean, listunknown)
1506
1508
1507 # check for any possibly clean files
1509 # check for any possibly clean files
1508 if cmp:
1510 if cmp:
1509 modified2, fixup = self._checklookup(cmp)
1511 modified2, fixup = self._checklookup(cmp)
1510 s.modified.extend(modified2)
1512 s.modified.extend(modified2)
1511
1513
1512 # update dirstate for files that are actually clean
1514 # update dirstate for files that are actually clean
1513 if fixup and listclean:
1515 if fixup and listclean:
1514 s.clean.extend(fixup)
1516 s.clean.extend(fixup)
1515
1517
1516 if match.always():
1518 if match.always():
1517 # cache for performance
1519 # cache for performance
1518 if s.unknown or s.ignored or s.clean:
1520 if s.unknown or s.ignored or s.clean:
1519 # "_status" is cached with list*=False in the normal route
1521 # "_status" is cached with list*=False in the normal route
1520 self._status = scmutil.status(s.modified, s.added, s.removed,
1522 self._status = scmutil.status(s.modified, s.added, s.removed,
1521 s.deleted, [], [], [])
1523 s.deleted, [], [], [])
1522 else:
1524 else:
1523 self._status = s
1525 self._status = s
1524
1526
1525 return s
1527 return s
1526
1528
1527 def _buildstatus(self, other, s, match, listignored, listclean,
1529 def _buildstatus(self, other, s, match, listignored, listclean,
1528 listunknown):
1530 listunknown):
1529 """build a status with respect to another context
1531 """build a status with respect to another context
1530
1532
1531 This includes logic for maintaining the fast path of status when
1533 This includes logic for maintaining the fast path of status when
1532 comparing the working directory against its parent, which is to skip
1534 comparing the working directory against its parent, which is to skip
1533 building a new manifest if self (working directory) is not comparing
1535 building a new manifest if self (working directory) is not comparing
1534 against its parent (repo['.']).
1536 against its parent (repo['.']).
1535 """
1537 """
1536 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1538 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1537 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1539 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1538 # might have accidentally ended up with the entire contents of the file
1540 # might have accidentally ended up with the entire contents of the file
1539 # they are supposed to be linking to.
1541 # they are supposed to be linking to.
1540 s.modified[:] = self._filtersuspectsymlink(s.modified)
1542 s.modified[:] = self._filtersuspectsymlink(s.modified)
1541 if other != self._repo['.']:
1543 if other != self._repo['.']:
1542 s = super(workingctx, self)._buildstatus(other, s, match,
1544 s = super(workingctx, self)._buildstatus(other, s, match,
1543 listignored, listclean,
1545 listignored, listclean,
1544 listunknown)
1546 listunknown)
1545 return s
1547 return s
1546
1548
1547 def _matchstatus(self, other, match):
1549 def _matchstatus(self, other, match):
1548 """override the match method with a filter for directory patterns
1550 """override the match method with a filter for directory patterns
1549
1551
1550 We use inheritance to customize the match.bad method only in cases of
1552 We use inheritance to customize the match.bad method only in cases of
1551 workingctx since it belongs only to the working directory when
1553 workingctx since it belongs only to the working directory when
1552 comparing against the parent changeset.
1554 comparing against the parent changeset.
1553
1555
1554 If we aren't comparing against the working directory's parent, then we
1556 If we aren't comparing against the working directory's parent, then we
1555 just use the default match object sent to us.
1557 just use the default match object sent to us.
1556 """
1558 """
1557 superself = super(workingctx, self)
1559 superself = super(workingctx, self)
1558 match = superself._matchstatus(other, match)
1560 match = superself._matchstatus(other, match)
1559 if other != self._repo['.']:
1561 if other != self._repo['.']:
1560 def bad(f, msg):
1562 def bad(f, msg):
1561 # 'f' may be a directory pattern from 'match.files()',
1563 # 'f' may be a directory pattern from 'match.files()',
1562 # so 'f not in ctx1' is not enough
1564 # so 'f not in ctx1' is not enough
1563 if f not in other and not other.hasdir(f):
1565 if f not in other and not other.hasdir(f):
1564 self._repo.ui.warn('%s: %s\n' %
1566 self._repo.ui.warn('%s: %s\n' %
1565 (self._repo.dirstate.pathto(f), msg))
1567 (self._repo.dirstate.pathto(f), msg))
1566 match.bad = bad
1568 match.bad = bad
1567 return match
1569 return match
1568
1570
1569 class committablefilectx(basefilectx):
1571 class committablefilectx(basefilectx):
1570 """A committablefilectx provides common functionality for a file context
1572 """A committablefilectx provides common functionality for a file context
1571 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1573 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1572 def __init__(self, repo, path, filelog=None, ctx=None):
1574 def __init__(self, repo, path, filelog=None, ctx=None):
1573 self._repo = repo
1575 self._repo = repo
1574 self._path = path
1576 self._path = path
1575 self._changeid = None
1577 self._changeid = None
1576 self._filerev = self._filenode = None
1578 self._filerev = self._filenode = None
1577
1579
1578 if filelog is not None:
1580 if filelog is not None:
1579 self._filelog = filelog
1581 self._filelog = filelog
1580 if ctx:
1582 if ctx:
1581 self._changectx = ctx
1583 self._changectx = ctx
1582
1584
1583 def __nonzero__(self):
1585 def __nonzero__(self):
1584 return True
1586 return True
1585
1587
1586 def linkrev(self):
1588 def linkrev(self):
1587 # linked to self._changectx no matter if file is modified or not
1589 # linked to self._changectx no matter if file is modified or not
1588 return self.rev()
1590 return self.rev()
1589
1591
1590 def parents(self):
1592 def parents(self):
1591 '''return parent filectxs, following copies if necessary'''
1593 '''return parent filectxs, following copies if necessary'''
1592 def filenode(ctx, path):
1594 def filenode(ctx, path):
1593 return ctx._manifest.get(path, nullid)
1595 return ctx._manifest.get(path, nullid)
1594
1596
1595 path = self._path
1597 path = self._path
1596 fl = self._filelog
1598 fl = self._filelog
1597 pcl = self._changectx._parents
1599 pcl = self._changectx._parents
1598 renamed = self.renamed()
1600 renamed = self.renamed()
1599
1601
1600 if renamed:
1602 if renamed:
1601 pl = [renamed + (None,)]
1603 pl = [renamed + (None,)]
1602 else:
1604 else:
1603 pl = [(path, filenode(pcl[0], path), fl)]
1605 pl = [(path, filenode(pcl[0], path), fl)]
1604
1606
1605 for pc in pcl[1:]:
1607 for pc in pcl[1:]:
1606 pl.append((path, filenode(pc, path), fl))
1608 pl.append((path, filenode(pc, path), fl))
1607
1609
1608 return [filectx(self._repo, p, fileid=n, filelog=l)
1610 return [filectx(self._repo, p, fileid=n, filelog=l)
1609 for p, n, l in pl if n != nullid]
1611 for p, n, l in pl if n != nullid]
1610
1612
1611 def children(self):
1613 def children(self):
1612 return []
1614 return []
1613
1615
1614 class workingfilectx(committablefilectx):
1616 class workingfilectx(committablefilectx):
1615 """A workingfilectx object makes access to data related to a particular
1617 """A workingfilectx object makes access to data related to a particular
1616 file in the working directory convenient."""
1618 file in the working directory convenient."""
1617 def __init__(self, repo, path, filelog=None, workingctx=None):
1619 def __init__(self, repo, path, filelog=None, workingctx=None):
1618 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1620 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1619
1621
1620 @propertycache
1622 @propertycache
1621 def _changectx(self):
1623 def _changectx(self):
1622 return workingctx(self._repo)
1624 return workingctx(self._repo)
1623
1625
1624 def data(self):
1626 def data(self):
1625 return self._repo.wread(self._path)
1627 return self._repo.wread(self._path)
1626 def renamed(self):
1628 def renamed(self):
1627 rp = self._repo.dirstate.copied(self._path)
1629 rp = self._repo.dirstate.copied(self._path)
1628 if not rp:
1630 if not rp:
1629 return None
1631 return None
1630 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1632 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1631
1633
1632 def size(self):
1634 def size(self):
1633 return self._repo.wvfs.lstat(self._path).st_size
1635 return self._repo.wvfs.lstat(self._path).st_size
1634 def date(self):
1636 def date(self):
1635 t, tz = self._changectx.date()
1637 t, tz = self._changectx.date()
1636 try:
1638 try:
1637 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1639 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1638 except OSError, err:
1640 except OSError, err:
1639 if err.errno != errno.ENOENT:
1641 if err.errno != errno.ENOENT:
1640 raise
1642 raise
1641 return (t, tz)
1643 return (t, tz)
1642
1644
1643 def cmp(self, fctx):
1645 def cmp(self, fctx):
1644 """compare with other file context
1646 """compare with other file context
1645
1647
1646 returns True if different than fctx.
1648 returns True if different than fctx.
1647 """
1649 """
1648 # fctx should be a filectx (not a workingfilectx)
1650 # fctx should be a filectx (not a workingfilectx)
1649 # invert comparison to reuse the same code path
1651 # invert comparison to reuse the same code path
1650 return fctx.cmp(self)
1652 return fctx.cmp(self)
1651
1653
1652 def remove(self, ignoremissing=False):
1654 def remove(self, ignoremissing=False):
1653 """wraps unlink for a repo's working directory"""
1655 """wraps unlink for a repo's working directory"""
1654 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1656 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1655
1657
1656 def write(self, data, flags):
1658 def write(self, data, flags):
1657 """wraps repo.wwrite"""
1659 """wraps repo.wwrite"""
1658 self._repo.wwrite(self._path, data, flags)
1660 self._repo.wwrite(self._path, data, flags)
1659
1661
1660 class workingcommitctx(workingctx):
1662 class workingcommitctx(workingctx):
1661 """A workingcommitctx object makes access to data related to
1663 """A workingcommitctx object makes access to data related to
1662 the revision being committed convenient.
1664 the revision being committed convenient.
1663
1665
1664 This hides changes in the working directory, if they aren't
1666 This hides changes in the working directory, if they aren't
1665 committed in this context.
1667 committed in this context.
1666 """
1668 """
1667 def __init__(self, repo, changes,
1669 def __init__(self, repo, changes,
1668 text="", user=None, date=None, extra=None):
1670 text="", user=None, date=None, extra=None):
1669 super(workingctx, self).__init__(repo, text, user, date, extra,
1671 super(workingctx, self).__init__(repo, text, user, date, extra,
1670 changes)
1672 changes)
1671
1673
1672 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1674 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1673 unknown=False):
1675 unknown=False):
1674 """Return matched files only in ``self._status``
1676 """Return matched files only in ``self._status``
1675
1677
1676 Uncommitted files appear "clean" via this context, even if
1678 Uncommitted files appear "clean" via this context, even if
1677 they aren't actually so in the working directory.
1679 they aren't actually so in the working directory.
1678 """
1680 """
1679 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1681 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1680 if clean:
1682 if clean:
1681 clean = [f for f in self._manifest if f not in self._changedset]
1683 clean = [f for f in self._manifest if f not in self._changedset]
1682 else:
1684 else:
1683 clean = []
1685 clean = []
1684 return scmutil.status([f for f in self._status.modified if match(f)],
1686 return scmutil.status([f for f in self._status.modified if match(f)],
1685 [f for f in self._status.added if match(f)],
1687 [f for f in self._status.added if match(f)],
1686 [f for f in self._status.removed if match(f)],
1688 [f for f in self._status.removed if match(f)],
1687 [], [], [], clean)
1689 [], [], [], clean)
1688
1690
1689 @propertycache
1691 @propertycache
1690 def _changedset(self):
1692 def _changedset(self):
1691 """Return the set of files changed in this context
1693 """Return the set of files changed in this context
1692 """
1694 """
1693 changed = set(self._status.modified)
1695 changed = set(self._status.modified)
1694 changed.update(self._status.added)
1696 changed.update(self._status.added)
1695 changed.update(self._status.removed)
1697 changed.update(self._status.removed)
1696 return changed
1698 return changed
1697
1699
1698 class memctx(committablectx):
1700 class memctx(committablectx):
1699 """Use memctx to perform in-memory commits via localrepo.commitctx().
1701 """Use memctx to perform in-memory commits via localrepo.commitctx().
1700
1702
1701 Revision information is supplied at initialization time while
1703 Revision information is supplied at initialization time while
1702 related files data and is made available through a callback
1704 related files data and is made available through a callback
1703 mechanism. 'repo' is the current localrepo, 'parents' is a
1705 mechanism. 'repo' is the current localrepo, 'parents' is a
1704 sequence of two parent revisions identifiers (pass None for every
1706 sequence of two parent revisions identifiers (pass None for every
1705 missing parent), 'text' is the commit message and 'files' lists
1707 missing parent), 'text' is the commit message and 'files' lists
1706 names of files touched by the revision (normalized and relative to
1708 names of files touched by the revision (normalized and relative to
1707 repository root).
1709 repository root).
1708
1710
1709 filectxfn(repo, memctx, path) is a callable receiving the
1711 filectxfn(repo, memctx, path) is a callable receiving the
1710 repository, the current memctx object and the normalized path of
1712 repository, the current memctx object and the normalized path of
1711 requested file, relative to repository root. It is fired by the
1713 requested file, relative to repository root. It is fired by the
1712 commit function for every file in 'files', but calls order is
1714 commit function for every file in 'files', but calls order is
1713 undefined. If the file is available in the revision being
1715 undefined. If the file is available in the revision being
1714 committed (updated or added), filectxfn returns a memfilectx
1716 committed (updated or added), filectxfn returns a memfilectx
1715 object. If the file was removed, filectxfn raises an
1717 object. If the file was removed, filectxfn raises an
1716 IOError. Moved files are represented by marking the source file
1718 IOError. Moved files are represented by marking the source file
1717 removed and the new file added with copy information (see
1719 removed and the new file added with copy information (see
1718 memfilectx).
1720 memfilectx).
1719
1721
1720 user receives the committer name and defaults to current
1722 user receives the committer name and defaults to current
1721 repository username, date is the commit date in any format
1723 repository username, date is the commit date in any format
1722 supported by util.parsedate() and defaults to current date, extra
1724 supported by util.parsedate() and defaults to current date, extra
1723 is a dictionary of metadata or is left empty.
1725 is a dictionary of metadata or is left empty.
1724 """
1726 """
1725
1727
1726 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1728 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1727 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1729 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1728 # this field to determine what to do in filectxfn.
1730 # this field to determine what to do in filectxfn.
1729 _returnnoneformissingfiles = True
1731 _returnnoneformissingfiles = True
1730
1732
1731 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1733 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1732 date=None, extra=None, editor=False):
1734 date=None, extra=None, editor=False):
1733 super(memctx, self).__init__(repo, text, user, date, extra)
1735 super(memctx, self).__init__(repo, text, user, date, extra)
1734 self._rev = None
1736 self._rev = None
1735 self._node = None
1737 self._node = None
1736 parents = [(p or nullid) for p in parents]
1738 parents = [(p or nullid) for p in parents]
1737 p1, p2 = parents
1739 p1, p2 = parents
1738 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1740 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1739 files = sorted(set(files))
1741 files = sorted(set(files))
1740 self._files = files
1742 self._files = files
1741 self.substate = {}
1743 self.substate = {}
1742
1744
1743 # if store is not callable, wrap it in a function
1745 # if store is not callable, wrap it in a function
1744 if not callable(filectxfn):
1746 if not callable(filectxfn):
1745 def getfilectx(repo, memctx, path):
1747 def getfilectx(repo, memctx, path):
1746 fctx = filectxfn[path]
1748 fctx = filectxfn[path]
1747 # this is weird but apparently we only keep track of one parent
1749 # this is weird but apparently we only keep track of one parent
1748 # (why not only store that instead of a tuple?)
1750 # (why not only store that instead of a tuple?)
1749 copied = fctx.renamed()
1751 copied = fctx.renamed()
1750 if copied:
1752 if copied:
1751 copied = copied[0]
1753 copied = copied[0]
1752 return memfilectx(repo, path, fctx.data(),
1754 return memfilectx(repo, path, fctx.data(),
1753 islink=fctx.islink(), isexec=fctx.isexec(),
1755 islink=fctx.islink(), isexec=fctx.isexec(),
1754 copied=copied, memctx=memctx)
1756 copied=copied, memctx=memctx)
1755 self._filectxfn = getfilectx
1757 self._filectxfn = getfilectx
1756 else:
1758 else:
1757 # "util.cachefunc" reduces invocation of possibly expensive
1759 # "util.cachefunc" reduces invocation of possibly expensive
1758 # "filectxfn" for performance (e.g. converting from another VCS)
1760 # "filectxfn" for performance (e.g. converting from another VCS)
1759 self._filectxfn = util.cachefunc(filectxfn)
1761 self._filectxfn = util.cachefunc(filectxfn)
1760
1762
1761 if extra:
1763 if extra:
1762 self._extra = extra.copy()
1764 self._extra = extra.copy()
1763 else:
1765 else:
1764 self._extra = {}
1766 self._extra = {}
1765
1767
1766 if self._extra.get('branch', '') == '':
1768 if self._extra.get('branch', '') == '':
1767 self._extra['branch'] = 'default'
1769 self._extra['branch'] = 'default'
1768
1770
1769 if editor:
1771 if editor:
1770 self._text = editor(self._repo, self, [])
1772 self._text = editor(self._repo, self, [])
1771 self._repo.savecommitmessage(self._text)
1773 self._repo.savecommitmessage(self._text)
1772
1774
1773 def filectx(self, path, filelog=None):
1775 def filectx(self, path, filelog=None):
1774 """get a file context from the working directory
1776 """get a file context from the working directory
1775
1777
1776 Returns None if file doesn't exist and should be removed."""
1778 Returns None if file doesn't exist and should be removed."""
1777 return self._filectxfn(self._repo, self, path)
1779 return self._filectxfn(self._repo, self, path)
1778
1780
1779 def commit(self):
1781 def commit(self):
1780 """commit context to the repo"""
1782 """commit context to the repo"""
1781 return self._repo.commitctx(self)
1783 return self._repo.commitctx(self)
1782
1784
1783 @propertycache
1785 @propertycache
1784 def _manifest(self):
1786 def _manifest(self):
1785 """generate a manifest based on the return values of filectxfn"""
1787 """generate a manifest based on the return values of filectxfn"""
1786
1788
1787 # keep this simple for now; just worry about p1
1789 # keep this simple for now; just worry about p1
1788 pctx = self._parents[0]
1790 pctx = self._parents[0]
1789 man = pctx.manifest().copy()
1791 man = pctx.manifest().copy()
1790
1792
1791 for f in self._status.modified:
1793 for f in self._status.modified:
1792 p1node = nullid
1794 p1node = nullid
1793 p2node = nullid
1795 p2node = nullid
1794 p = pctx[f].parents() # if file isn't in pctx, check p2?
1796 p = pctx[f].parents() # if file isn't in pctx, check p2?
1795 if len(p) > 0:
1797 if len(p) > 0:
1796 p1node = p[0].node()
1798 p1node = p[0].node()
1797 if len(p) > 1:
1799 if len(p) > 1:
1798 p2node = p[1].node()
1800 p2node = p[1].node()
1799 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1801 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1800
1802
1801 for f in self._status.added:
1803 for f in self._status.added:
1802 man[f] = revlog.hash(self[f].data(), nullid, nullid)
1804 man[f] = revlog.hash(self[f].data(), nullid, nullid)
1803
1805
1804 for f in self._status.removed:
1806 for f in self._status.removed:
1805 if f in man:
1807 if f in man:
1806 del man[f]
1808 del man[f]
1807
1809
1808 return man
1810 return man
1809
1811
1810 @propertycache
1812 @propertycache
1811 def _status(self):
1813 def _status(self):
1812 """Calculate exact status from ``files`` specified at construction
1814 """Calculate exact status from ``files`` specified at construction
1813 """
1815 """
1814 man1 = self.p1().manifest()
1816 man1 = self.p1().manifest()
1815 p2 = self._parents[1]
1817 p2 = self._parents[1]
1816 # "1 < len(self._parents)" can't be used for checking
1818 # "1 < len(self._parents)" can't be used for checking
1817 # existence of the 2nd parent, because "memctx._parents" is
1819 # existence of the 2nd parent, because "memctx._parents" is
1818 # explicitly initialized by the list, of which length is 2.
1820 # explicitly initialized by the list, of which length is 2.
1819 if p2.node() != nullid:
1821 if p2.node() != nullid:
1820 man2 = p2.manifest()
1822 man2 = p2.manifest()
1821 managing = lambda f: f in man1 or f in man2
1823 managing = lambda f: f in man1 or f in man2
1822 else:
1824 else:
1823 managing = lambda f: f in man1
1825 managing = lambda f: f in man1
1824
1826
1825 modified, added, removed = [], [], []
1827 modified, added, removed = [], [], []
1826 for f in self._files:
1828 for f in self._files:
1827 if not managing(f):
1829 if not managing(f):
1828 added.append(f)
1830 added.append(f)
1829 elif self[f]:
1831 elif self[f]:
1830 modified.append(f)
1832 modified.append(f)
1831 else:
1833 else:
1832 removed.append(f)
1834 removed.append(f)
1833
1835
1834 return scmutil.status(modified, added, removed, [], [], [], [])
1836 return scmutil.status(modified, added, removed, [], [], [], [])
1835
1837
1836 class memfilectx(committablefilectx):
1838 class memfilectx(committablefilectx):
1837 """memfilectx represents an in-memory file to commit.
1839 """memfilectx represents an in-memory file to commit.
1838
1840
1839 See memctx and committablefilectx for more details.
1841 See memctx and committablefilectx for more details.
1840 """
1842 """
1841 def __init__(self, repo, path, data, islink=False,
1843 def __init__(self, repo, path, data, islink=False,
1842 isexec=False, copied=None, memctx=None):
1844 isexec=False, copied=None, memctx=None):
1843 """
1845 """
1844 path is the normalized file path relative to repository root.
1846 path is the normalized file path relative to repository root.
1845 data is the file content as a string.
1847 data is the file content as a string.
1846 islink is True if the file is a symbolic link.
1848 islink is True if the file is a symbolic link.
1847 isexec is True if the file is executable.
1849 isexec is True if the file is executable.
1848 copied is the source file path if current file was copied in the
1850 copied is the source file path if current file was copied in the
1849 revision being committed, or None."""
1851 revision being committed, or None."""
1850 super(memfilectx, self).__init__(repo, path, None, memctx)
1852 super(memfilectx, self).__init__(repo, path, None, memctx)
1851 self._data = data
1853 self._data = data
1852 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1854 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1853 self._copied = None
1855 self._copied = None
1854 if copied:
1856 if copied:
1855 self._copied = (copied, nullid)
1857 self._copied = (copied, nullid)
1856
1858
1857 def data(self):
1859 def data(self):
1858 return self._data
1860 return self._data
1859 def size(self):
1861 def size(self):
1860 return len(self.data())
1862 return len(self.data())
1861 def flags(self):
1863 def flags(self):
1862 return self._flags
1864 return self._flags
1863 def renamed(self):
1865 def renamed(self):
1864 return self._copied
1866 return self._copied
1865
1867
1866 def remove(self, ignoremissing=False):
1868 def remove(self, ignoremissing=False):
1867 """wraps unlink for a repo's working directory"""
1869 """wraps unlink for a repo's working directory"""
1868 # need to figure out what to do here
1870 # need to figure out what to do here
1869 del self._changectx[self._path]
1871 del self._changectx[self._path]
1870
1872
1871 def write(self, data, flags):
1873 def write(self, data, flags):
1872 """wraps repo.wwrite"""
1874 """wraps repo.wwrite"""
1873 self._data = data
1875 self._data = data
General Comments 0
You need to be logged in to leave comments. Login now