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