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