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