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