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