##// END OF EJS Templates
namespaces: remove weakref; always pass in repo...
Ryan McElroy -
r23561:3c2419e0 default
parent child Browse files
Show More
@@ -1,1689 +1,1689 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 return self.manifest().matches(match)
74 return self.manifest().matches(match)
75
75
76 def _matchstatus(self, other, match):
76 def _matchstatus(self, other, match):
77 """return match.always if match is none
77 """return match.always if match is none
78
78
79 This internal method provides a way for child objects to override the
79 This internal method provides a way for child objects to override the
80 match operator.
80 match operator.
81 """
81 """
82 return match or matchmod.always(self._repo.root, self._repo.getcwd())
82 return match or matchmod.always(self._repo.root, self._repo.getcwd())
83
83
84 def _buildstatus(self, other, s, match, listignored, listclean,
84 def _buildstatus(self, other, s, match, listignored, listclean,
85 listunknown):
85 listunknown):
86 """build a status with respect to another context"""
86 """build a status with respect to another context"""
87 # Load earliest manifest first for caching reasons. More specifically,
87 # Load earliest manifest first for caching reasons. More specifically,
88 # if you have revisions 1000 and 1001, 1001 is probably stored as a
88 # if you have revisions 1000 and 1001, 1001 is probably stored as a
89 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
89 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
90 # 1000 and cache it so that when you read 1001, we just need to apply a
90 # 1000 and cache it so that when you read 1001, we just need to apply a
91 # delta to what's in the cache. So that's one full reconstruction + one
91 # delta to what's in the cache. So that's one full reconstruction + one
92 # delta application.
92 # delta application.
93 if self.rev() is not None and self.rev() < other.rev():
93 if self.rev() is not None and self.rev() < other.rev():
94 self.manifest()
94 self.manifest()
95 mf1 = other._manifestmatches(match, s)
95 mf1 = other._manifestmatches(match, s)
96 mf2 = self._manifestmatches(match, s)
96 mf2 = self._manifestmatches(match, s)
97
97
98 modified, added, clean = [], [], []
98 modified, added, clean = [], [], []
99 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
99 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
100 deletedset = set(deleted)
100 deletedset = set(deleted)
101 withflags = mf1.withflags() | mf2.withflags()
101 withflags = mf1.withflags() | mf2.withflags()
102 for fn, mf2node in mf2.iteritems():
102 for fn, mf2node in mf2.iteritems():
103 if fn in mf1:
103 if fn in mf1:
104 if (fn not in deletedset and
104 if (fn not in deletedset and
105 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
105 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
106 (mf1[fn] != mf2node and
106 (mf1[fn] != mf2node and
107 (mf2node or self[fn].cmp(other[fn]))))):
107 (mf2node or self[fn].cmp(other[fn]))))):
108 modified.append(fn)
108 modified.append(fn)
109 elif listclean:
109 elif listclean:
110 clean.append(fn)
110 clean.append(fn)
111 del mf1[fn]
111 del mf1[fn]
112 elif fn not in deletedset:
112 elif fn not in deletedset:
113 added.append(fn)
113 added.append(fn)
114 removed = mf1.keys()
114 removed = mf1.keys()
115 if removed:
115 if removed:
116 # need to filter files if they are already reported as removed
116 # need to filter files if they are already reported as removed
117 unknown = [fn for fn in unknown if fn not in mf1]
117 unknown = [fn for fn in unknown if fn not in mf1]
118 ignored = [fn for fn in ignored if fn not in mf1]
118 ignored = [fn for fn in ignored if fn not in mf1]
119
119
120 return scmutil.status(modified, added, removed, deleted, unknown,
120 return scmutil.status(modified, added, removed, deleted, unknown,
121 ignored, clean)
121 ignored, clean)
122
122
123 @propertycache
123 @propertycache
124 def substate(self):
124 def substate(self):
125 return subrepo.state(self, self._repo.ui)
125 return subrepo.state(self, self._repo.ui)
126
126
127 def subrev(self, subpath):
127 def subrev(self, subpath):
128 return self.substate[subpath][1]
128 return self.substate[subpath][1]
129
129
130 def rev(self):
130 def rev(self):
131 return self._rev
131 return self._rev
132 def node(self):
132 def node(self):
133 return self._node
133 return self._node
134 def hex(self):
134 def hex(self):
135 return hex(self.node())
135 return hex(self.node())
136 def manifest(self):
136 def manifest(self):
137 return self._manifest
137 return self._manifest
138 def phasestr(self):
138 def phasestr(self):
139 return phases.phasenames[self.phase()]
139 return phases.phasenames[self.phase()]
140 def mutable(self):
140 def mutable(self):
141 return self.phase() > phases.public
141 return self.phase() > phases.public
142
142
143 def getfileset(self, expr):
143 def getfileset(self, expr):
144 return fileset.getfileset(self, expr)
144 return fileset.getfileset(self, expr)
145
145
146 def obsolete(self):
146 def obsolete(self):
147 """True if the changeset is obsolete"""
147 """True if the changeset is obsolete"""
148 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
148 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
149
149
150 def extinct(self):
150 def extinct(self):
151 """True if the changeset is extinct"""
151 """True if the changeset is extinct"""
152 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
152 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
153
153
154 def unstable(self):
154 def unstable(self):
155 """True if the changeset is not obsolete but it's ancestor are"""
155 """True if the changeset is not obsolete but it's ancestor are"""
156 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
156 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
157
157
158 def bumped(self):
158 def bumped(self):
159 """True if the changeset try to be a successor of a public changeset
159 """True if the changeset try to be a successor of a public changeset
160
160
161 Only non-public and non-obsolete changesets may be bumped.
161 Only non-public and non-obsolete changesets may be bumped.
162 """
162 """
163 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
163 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
164
164
165 def divergent(self):
165 def divergent(self):
166 """Is a successors of a changeset with multiple possible successors set
166 """Is a successors of a changeset with multiple possible successors set
167
167
168 Only non-public and non-obsolete changesets may be divergent.
168 Only non-public and non-obsolete changesets may be divergent.
169 """
169 """
170 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
170 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
171
171
172 def troubled(self):
172 def troubled(self):
173 """True if the changeset is either unstable, bumped or divergent"""
173 """True if the changeset is either unstable, bumped or divergent"""
174 return self.unstable() or self.bumped() or self.divergent()
174 return self.unstable() or self.bumped() or self.divergent()
175
175
176 def troubles(self):
176 def troubles(self):
177 """return the list of troubles affecting this changesets.
177 """return the list of troubles affecting this changesets.
178
178
179 Troubles are returned as strings. possible values are:
179 Troubles are returned as strings. possible values are:
180 - unstable,
180 - unstable,
181 - bumped,
181 - bumped,
182 - divergent.
182 - divergent.
183 """
183 """
184 troubles = []
184 troubles = []
185 if self.unstable():
185 if self.unstable():
186 troubles.append('unstable')
186 troubles.append('unstable')
187 if self.bumped():
187 if self.bumped():
188 troubles.append('bumped')
188 troubles.append('bumped')
189 if self.divergent():
189 if self.divergent():
190 troubles.append('divergent')
190 troubles.append('divergent')
191 return troubles
191 return troubles
192
192
193 def parents(self):
193 def parents(self):
194 """return contexts for each parent changeset"""
194 """return contexts for each parent changeset"""
195 return self._parents
195 return self._parents
196
196
197 def p1(self):
197 def p1(self):
198 return self._parents[0]
198 return self._parents[0]
199
199
200 def p2(self):
200 def p2(self):
201 if len(self._parents) == 2:
201 if len(self._parents) == 2:
202 return self._parents[1]
202 return self._parents[1]
203 return changectx(self._repo, -1)
203 return changectx(self._repo, -1)
204
204
205 def _fileinfo(self, path):
205 def _fileinfo(self, path):
206 if '_manifest' in self.__dict__:
206 if '_manifest' in self.__dict__:
207 try:
207 try:
208 return self._manifest[path], self._manifest.flags(path)
208 return self._manifest[path], self._manifest.flags(path)
209 except KeyError:
209 except KeyError:
210 raise error.ManifestLookupError(self._node, path,
210 raise error.ManifestLookupError(self._node, path,
211 _('not found in manifest'))
211 _('not found in manifest'))
212 if '_manifestdelta' in self.__dict__ or path in self.files():
212 if '_manifestdelta' in self.__dict__ or path in self.files():
213 if path in self._manifestdelta:
213 if path in self._manifestdelta:
214 return (self._manifestdelta[path],
214 return (self._manifestdelta[path],
215 self._manifestdelta.flags(path))
215 self._manifestdelta.flags(path))
216 node, flag = self._repo.manifest.find(self._changeset[0], path)
216 node, flag = self._repo.manifest.find(self._changeset[0], path)
217 if not node:
217 if not node:
218 raise error.ManifestLookupError(self._node, path,
218 raise error.ManifestLookupError(self._node, path,
219 _('not found in manifest'))
219 _('not found in manifest'))
220
220
221 return node, flag
221 return node, flag
222
222
223 def filenode(self, path):
223 def filenode(self, path):
224 return self._fileinfo(path)[0]
224 return self._fileinfo(path)[0]
225
225
226 def flags(self, path):
226 def flags(self, path):
227 try:
227 try:
228 return self._fileinfo(path)[1]
228 return self._fileinfo(path)[1]
229 except error.LookupError:
229 except error.LookupError:
230 return ''
230 return ''
231
231
232 def sub(self, path):
232 def sub(self, path):
233 return subrepo.subrepo(self, path)
233 return subrepo.subrepo(self, path)
234
234
235 def match(self, pats=[], include=None, exclude=None, default='glob'):
235 def match(self, pats=[], include=None, exclude=None, default='glob'):
236 r = self._repo
236 r = self._repo
237 return matchmod.match(r.root, r.getcwd(), pats,
237 return matchmod.match(r.root, r.getcwd(), pats,
238 include, exclude, default,
238 include, exclude, default,
239 auditor=r.auditor, ctx=self)
239 auditor=r.auditor, ctx=self)
240
240
241 def diff(self, ctx2=None, match=None, **opts):
241 def diff(self, ctx2=None, match=None, **opts):
242 """Returns a diff generator for the given contexts and matcher"""
242 """Returns a diff generator for the given contexts and matcher"""
243 if ctx2 is None:
243 if ctx2 is None:
244 ctx2 = self.p1()
244 ctx2 = self.p1()
245 if ctx2 is not None:
245 if ctx2 is not None:
246 ctx2 = self._repo[ctx2]
246 ctx2 = self._repo[ctx2]
247 diffopts = patch.diffopts(self._repo.ui, opts)
247 diffopts = patch.diffopts(self._repo.ui, opts)
248 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
248 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
249
249
250 @propertycache
250 @propertycache
251 def _dirs(self):
251 def _dirs(self):
252 return scmutil.dirs(self._manifest)
252 return scmutil.dirs(self._manifest)
253
253
254 def dirs(self):
254 def dirs(self):
255 return self._dirs
255 return self._dirs
256
256
257 def dirty(self, missing=False, merge=True, branch=True):
257 def dirty(self, missing=False, merge=True, branch=True):
258 return False
258 return False
259
259
260 def status(self, other=None, match=None, listignored=False,
260 def status(self, other=None, match=None, listignored=False,
261 listclean=False, listunknown=False, listsubrepos=False):
261 listclean=False, listunknown=False, listsubrepos=False):
262 """return status of files between two nodes or node and working
262 """return status of files between two nodes or node and working
263 directory.
263 directory.
264
264
265 If other is None, compare this node with working directory.
265 If other is None, compare this node with working directory.
266
266
267 returns (modified, added, removed, deleted, unknown, ignored, clean)
267 returns (modified, added, removed, deleted, unknown, ignored, clean)
268 """
268 """
269
269
270 ctx1 = self
270 ctx1 = self
271 ctx2 = self._repo[other]
271 ctx2 = self._repo[other]
272
272
273 # This next code block is, admittedly, fragile logic that tests for
273 # This next code block is, admittedly, fragile logic that tests for
274 # reversing the contexts and wouldn't need to exist if it weren't for
274 # reversing the contexts and wouldn't need to exist if it weren't for
275 # the fast (and common) code path of comparing the working directory
275 # the fast (and common) code path of comparing the working directory
276 # with its first parent.
276 # with its first parent.
277 #
277 #
278 # What we're aiming for here is the ability to call:
278 # What we're aiming for here is the ability to call:
279 #
279 #
280 # workingctx.status(parentctx)
280 # workingctx.status(parentctx)
281 #
281 #
282 # If we always built the manifest for each context and compared those,
282 # If we always built the manifest for each context and compared those,
283 # then we'd be done. But the special case of the above call means we
283 # then we'd be done. But the special case of the above call means we
284 # just copy the manifest of the parent.
284 # just copy the manifest of the parent.
285 reversed = False
285 reversed = False
286 if (not isinstance(ctx1, changectx)
286 if (not isinstance(ctx1, changectx)
287 and isinstance(ctx2, changectx)):
287 and isinstance(ctx2, changectx)):
288 reversed = True
288 reversed = True
289 ctx1, ctx2 = ctx2, ctx1
289 ctx1, ctx2 = ctx2, ctx1
290
290
291 match = ctx2._matchstatus(ctx1, match)
291 match = ctx2._matchstatus(ctx1, match)
292 r = scmutil.status([], [], [], [], [], [], [])
292 r = scmutil.status([], [], [], [], [], [], [])
293 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
293 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
294 listunknown)
294 listunknown)
295
295
296 if reversed:
296 if reversed:
297 # Reverse added and removed. Clear deleted, unknown and ignored as
297 # Reverse added and removed. Clear deleted, unknown and ignored as
298 # these make no sense to reverse.
298 # these make no sense to reverse.
299 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
299 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
300 r.clean)
300 r.clean)
301
301
302 if listsubrepos:
302 if listsubrepos:
303 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
303 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
304 rev2 = ctx2.subrev(subpath)
304 rev2 = ctx2.subrev(subpath)
305 try:
305 try:
306 submatch = matchmod.narrowmatcher(subpath, match)
306 submatch = matchmod.narrowmatcher(subpath, match)
307 s = sub.status(rev2, match=submatch, ignored=listignored,
307 s = sub.status(rev2, match=submatch, ignored=listignored,
308 clean=listclean, unknown=listunknown,
308 clean=listclean, unknown=listunknown,
309 listsubrepos=True)
309 listsubrepos=True)
310 for rfiles, sfiles in zip(r, s):
310 for rfiles, sfiles in zip(r, s):
311 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
311 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
312 except error.LookupError:
312 except error.LookupError:
313 self._repo.ui.status(_("skipping missing "
313 self._repo.ui.status(_("skipping missing "
314 "subrepository: %s\n") % subpath)
314 "subrepository: %s\n") % subpath)
315
315
316 for l in r:
316 for l in r:
317 l.sort()
317 l.sort()
318
318
319 return r
319 return r
320
320
321
321
322 def makememctx(repo, parents, text, user, date, branch, files, store,
322 def makememctx(repo, parents, text, user, date, branch, files, store,
323 editor=None):
323 editor=None):
324 def getfilectx(repo, memctx, path):
324 def getfilectx(repo, memctx, path):
325 data, mode, copied = store.getfile(path)
325 data, mode, copied = store.getfile(path)
326 if data is None:
326 if data is None:
327 return None
327 return None
328 islink, isexec = mode
328 islink, isexec = mode
329 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
329 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
330 copied=copied, memctx=memctx)
330 copied=copied, memctx=memctx)
331 extra = {}
331 extra = {}
332 if branch:
332 if branch:
333 extra['branch'] = encoding.fromlocal(branch)
333 extra['branch'] = encoding.fromlocal(branch)
334 ctx = memctx(repo, parents, text, files, getfilectx, user,
334 ctx = memctx(repo, parents, text, files, getfilectx, user,
335 date, extra, editor)
335 date, extra, editor)
336 return ctx
336 return ctx
337
337
338 class changectx(basectx):
338 class changectx(basectx):
339 """A changecontext object makes access to data related to a particular
339 """A changecontext object makes access to data related to a particular
340 changeset convenient. It represents a read-only context already present in
340 changeset convenient. It represents a read-only context already present in
341 the repo."""
341 the repo."""
342 def __init__(self, repo, changeid=''):
342 def __init__(self, repo, changeid=''):
343 """changeid is a revision number, node, or tag"""
343 """changeid is a revision number, node, or tag"""
344
344
345 # since basectx.__new__ already took care of copying the object, we
345 # since basectx.__new__ already took care of copying the object, we
346 # don't need to do anything in __init__, so we just exit here
346 # don't need to do anything in __init__, so we just exit here
347 if isinstance(changeid, basectx):
347 if isinstance(changeid, basectx):
348 return
348 return
349
349
350 if changeid == '':
350 if changeid == '':
351 changeid = '.'
351 changeid = '.'
352 self._repo = repo
352 self._repo = repo
353
353
354 try:
354 try:
355 if isinstance(changeid, int):
355 if isinstance(changeid, int):
356 self._node = repo.changelog.node(changeid)
356 self._node = repo.changelog.node(changeid)
357 self._rev = changeid
357 self._rev = changeid
358 return
358 return
359 if isinstance(changeid, long):
359 if isinstance(changeid, long):
360 changeid = str(changeid)
360 changeid = str(changeid)
361 if changeid == '.':
361 if changeid == '.':
362 self._node = repo.dirstate.p1()
362 self._node = repo.dirstate.p1()
363 self._rev = repo.changelog.rev(self._node)
363 self._rev = repo.changelog.rev(self._node)
364 return
364 return
365 if changeid == 'null':
365 if changeid == 'null':
366 self._node = nullid
366 self._node = nullid
367 self._rev = nullrev
367 self._rev = nullrev
368 return
368 return
369 if changeid == 'tip':
369 if changeid == 'tip':
370 self._node = repo.changelog.tip()
370 self._node = repo.changelog.tip()
371 self._rev = repo.changelog.rev(self._node)
371 self._rev = repo.changelog.rev(self._node)
372 return
372 return
373 if len(changeid) == 20:
373 if len(changeid) == 20:
374 try:
374 try:
375 self._node = changeid
375 self._node = changeid
376 self._rev = repo.changelog.rev(changeid)
376 self._rev = repo.changelog.rev(changeid)
377 return
377 return
378 except error.FilteredRepoLookupError:
378 except error.FilteredRepoLookupError:
379 raise
379 raise
380 except LookupError:
380 except LookupError:
381 pass
381 pass
382
382
383 try:
383 try:
384 r = int(changeid)
384 r = int(changeid)
385 if str(r) != changeid:
385 if str(r) != changeid:
386 raise ValueError
386 raise ValueError
387 l = len(repo.changelog)
387 l = len(repo.changelog)
388 if r < 0:
388 if r < 0:
389 r += l
389 r += l
390 if r < 0 or r >= l:
390 if r < 0 or r >= l:
391 raise ValueError
391 raise ValueError
392 self._rev = r
392 self._rev = r
393 self._node = repo.changelog.node(r)
393 self._node = repo.changelog.node(r)
394 return
394 return
395 except error.FilteredIndexError:
395 except error.FilteredIndexError:
396 raise
396 raise
397 except (ValueError, OverflowError, IndexError):
397 except (ValueError, OverflowError, IndexError):
398 pass
398 pass
399
399
400 if len(changeid) == 40:
400 if len(changeid) == 40:
401 try:
401 try:
402 self._node = bin(changeid)
402 self._node = bin(changeid)
403 self._rev = repo.changelog.rev(self._node)
403 self._rev = repo.changelog.rev(self._node)
404 return
404 return
405 except error.FilteredLookupError:
405 except error.FilteredLookupError:
406 raise
406 raise
407 except (TypeError, LookupError):
407 except (TypeError, LookupError):
408 pass
408 pass
409
409
410 # lookup bookmarks through the name interface
410 # lookup bookmarks through the name interface
411 try:
411 try:
412 self._node = repo.names.singlenode(changeid)
412 self._node = repo.names.singlenode(repo, changeid)
413 self._rev = repo.changelog.rev(self._node)
413 self._rev = repo.changelog.rev(self._node)
414 return
414 return
415 except KeyError:
415 except KeyError:
416 pass
416 pass
417
417
418 if changeid in repo._tagscache.tags:
418 if changeid in repo._tagscache.tags:
419 self._node = repo._tagscache.tags[changeid]
419 self._node = repo._tagscache.tags[changeid]
420 self._rev = repo.changelog.rev(self._node)
420 self._rev = repo.changelog.rev(self._node)
421 return
421 return
422 try:
422 try:
423 self._node = repo.branchtip(changeid)
423 self._node = repo.branchtip(changeid)
424 self._rev = repo.changelog.rev(self._node)
424 self._rev = repo.changelog.rev(self._node)
425 return
425 return
426 except error.FilteredRepoLookupError:
426 except error.FilteredRepoLookupError:
427 raise
427 raise
428 except error.RepoLookupError:
428 except error.RepoLookupError:
429 pass
429 pass
430
430
431 self._node = repo.unfiltered().changelog._partialmatch(changeid)
431 self._node = repo.unfiltered().changelog._partialmatch(changeid)
432 if self._node is not None:
432 if self._node is not None:
433 self._rev = repo.changelog.rev(self._node)
433 self._rev = repo.changelog.rev(self._node)
434 return
434 return
435
435
436 # lookup failed
436 # lookup failed
437 # check if it might have come from damaged dirstate
437 # check if it might have come from damaged dirstate
438 #
438 #
439 # XXX we could avoid the unfiltered if we had a recognizable
439 # XXX we could avoid the unfiltered if we had a recognizable
440 # exception for filtered changeset access
440 # exception for filtered changeset access
441 if changeid in repo.unfiltered().dirstate.parents():
441 if changeid in repo.unfiltered().dirstate.parents():
442 msg = _("working directory has unknown parent '%s'!")
442 msg = _("working directory has unknown parent '%s'!")
443 raise error.Abort(msg % short(changeid))
443 raise error.Abort(msg % short(changeid))
444 try:
444 try:
445 if len(changeid) == 20:
445 if len(changeid) == 20:
446 changeid = hex(changeid)
446 changeid = hex(changeid)
447 except TypeError:
447 except TypeError:
448 pass
448 pass
449 except (error.FilteredIndexError, error.FilteredLookupError,
449 except (error.FilteredIndexError, error.FilteredLookupError,
450 error.FilteredRepoLookupError):
450 error.FilteredRepoLookupError):
451 if repo.filtername == 'visible':
451 if repo.filtername == 'visible':
452 msg = _("hidden revision '%s'") % changeid
452 msg = _("hidden revision '%s'") % changeid
453 hint = _('use --hidden to access hidden revisions')
453 hint = _('use --hidden to access hidden revisions')
454 raise error.FilteredRepoLookupError(msg, hint=hint)
454 raise error.FilteredRepoLookupError(msg, hint=hint)
455 msg = _("filtered revision '%s' (not in '%s' subset)")
455 msg = _("filtered revision '%s' (not in '%s' subset)")
456 msg %= (changeid, repo.filtername)
456 msg %= (changeid, repo.filtername)
457 raise error.FilteredRepoLookupError(msg)
457 raise error.FilteredRepoLookupError(msg)
458 except IndexError:
458 except IndexError:
459 pass
459 pass
460 raise error.RepoLookupError(
460 raise error.RepoLookupError(
461 _("unknown revision '%s'") % changeid)
461 _("unknown revision '%s'") % changeid)
462
462
463 def __hash__(self):
463 def __hash__(self):
464 try:
464 try:
465 return hash(self._rev)
465 return hash(self._rev)
466 except AttributeError:
466 except AttributeError:
467 return id(self)
467 return id(self)
468
468
469 def __nonzero__(self):
469 def __nonzero__(self):
470 return self._rev != nullrev
470 return self._rev != nullrev
471
471
472 @propertycache
472 @propertycache
473 def _changeset(self):
473 def _changeset(self):
474 return self._repo.changelog.read(self.rev())
474 return self._repo.changelog.read(self.rev())
475
475
476 @propertycache
476 @propertycache
477 def _manifest(self):
477 def _manifest(self):
478 return self._repo.manifest.read(self._changeset[0])
478 return self._repo.manifest.read(self._changeset[0])
479
479
480 @propertycache
480 @propertycache
481 def _manifestdelta(self):
481 def _manifestdelta(self):
482 return self._repo.manifest.readdelta(self._changeset[0])
482 return self._repo.manifest.readdelta(self._changeset[0])
483
483
484 @propertycache
484 @propertycache
485 def _parents(self):
485 def _parents(self):
486 p = self._repo.changelog.parentrevs(self._rev)
486 p = self._repo.changelog.parentrevs(self._rev)
487 if p[1] == nullrev:
487 if p[1] == nullrev:
488 p = p[:-1]
488 p = p[:-1]
489 return [changectx(self._repo, x) for x in p]
489 return [changectx(self._repo, x) for x in p]
490
490
491 def changeset(self):
491 def changeset(self):
492 return self._changeset
492 return self._changeset
493 def manifestnode(self):
493 def manifestnode(self):
494 return self._changeset[0]
494 return self._changeset[0]
495
495
496 def user(self):
496 def user(self):
497 return self._changeset[1]
497 return self._changeset[1]
498 def date(self):
498 def date(self):
499 return self._changeset[2]
499 return self._changeset[2]
500 def files(self):
500 def files(self):
501 return self._changeset[3]
501 return self._changeset[3]
502 def description(self):
502 def description(self):
503 return self._changeset[4]
503 return self._changeset[4]
504 def branch(self):
504 def branch(self):
505 return encoding.tolocal(self._changeset[5].get("branch"))
505 return encoding.tolocal(self._changeset[5].get("branch"))
506 def closesbranch(self):
506 def closesbranch(self):
507 return 'close' in self._changeset[5]
507 return 'close' in self._changeset[5]
508 def extra(self):
508 def extra(self):
509 return self._changeset[5]
509 return self._changeset[5]
510 def tags(self):
510 def tags(self):
511 return self._repo.nodetags(self._node)
511 return self._repo.nodetags(self._node)
512 def bookmarks(self):
512 def bookmarks(self):
513 return self._repo.nodebookmarks(self._node)
513 return self._repo.nodebookmarks(self._node)
514 def phase(self):
514 def phase(self):
515 return self._repo._phasecache.phase(self._repo, self._rev)
515 return self._repo._phasecache.phase(self._repo, self._rev)
516 def hidden(self):
516 def hidden(self):
517 return self._rev in repoview.filterrevs(self._repo, 'visible')
517 return self._rev in repoview.filterrevs(self._repo, 'visible')
518
518
519 def children(self):
519 def children(self):
520 """return contexts for each child changeset"""
520 """return contexts for each child changeset"""
521 c = self._repo.changelog.children(self._node)
521 c = self._repo.changelog.children(self._node)
522 return [changectx(self._repo, x) for x in c]
522 return [changectx(self._repo, x) for x in c]
523
523
524 def ancestors(self):
524 def ancestors(self):
525 for a in self._repo.changelog.ancestors([self._rev]):
525 for a in self._repo.changelog.ancestors([self._rev]):
526 yield changectx(self._repo, a)
526 yield changectx(self._repo, a)
527
527
528 def descendants(self):
528 def descendants(self):
529 for d in self._repo.changelog.descendants([self._rev]):
529 for d in self._repo.changelog.descendants([self._rev]):
530 yield changectx(self._repo, d)
530 yield changectx(self._repo, d)
531
531
532 def filectx(self, path, fileid=None, filelog=None):
532 def filectx(self, path, fileid=None, filelog=None):
533 """get a file context from this changeset"""
533 """get a file context from this changeset"""
534 if fileid is None:
534 if fileid is None:
535 fileid = self.filenode(path)
535 fileid = self.filenode(path)
536 return filectx(self._repo, path, fileid=fileid,
536 return filectx(self._repo, path, fileid=fileid,
537 changectx=self, filelog=filelog)
537 changectx=self, filelog=filelog)
538
538
539 def ancestor(self, c2, warn=False):
539 def ancestor(self, c2, warn=False):
540 """return the "best" ancestor context of self and c2
540 """return the "best" ancestor context of self and c2
541
541
542 If there are multiple candidates, it will show a message and check
542 If there are multiple candidates, it will show a message and check
543 merge.preferancestor configuration before falling back to the
543 merge.preferancestor configuration before falling back to the
544 revlog ancestor."""
544 revlog ancestor."""
545 # deal with workingctxs
545 # deal with workingctxs
546 n2 = c2._node
546 n2 = c2._node
547 if n2 is None:
547 if n2 is None:
548 n2 = c2._parents[0]._node
548 n2 = c2._parents[0]._node
549 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
549 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
550 if not cahs:
550 if not cahs:
551 anc = nullid
551 anc = nullid
552 elif len(cahs) == 1:
552 elif len(cahs) == 1:
553 anc = cahs[0]
553 anc = cahs[0]
554 else:
554 else:
555 for r in self._repo.ui.configlist('merge', 'preferancestor'):
555 for r in self._repo.ui.configlist('merge', 'preferancestor'):
556 try:
556 try:
557 ctx = changectx(self._repo, r)
557 ctx = changectx(self._repo, r)
558 except error.RepoLookupError:
558 except error.RepoLookupError:
559 continue
559 continue
560 anc = ctx.node()
560 anc = ctx.node()
561 if anc in cahs:
561 if anc in cahs:
562 break
562 break
563 else:
563 else:
564 anc = self._repo.changelog.ancestor(self._node, n2)
564 anc = self._repo.changelog.ancestor(self._node, n2)
565 if warn:
565 if warn:
566 self._repo.ui.status(
566 self._repo.ui.status(
567 (_("note: using %s as ancestor of %s and %s\n") %
567 (_("note: using %s as ancestor of %s and %s\n") %
568 (short(anc), short(self._node), short(n2))) +
568 (short(anc), short(self._node), short(n2))) +
569 ''.join(_(" alternatively, use --config "
569 ''.join(_(" alternatively, use --config "
570 "merge.preferancestor=%s\n") %
570 "merge.preferancestor=%s\n") %
571 short(n) for n in sorted(cahs) if n != anc))
571 short(n) for n in sorted(cahs) if n != anc))
572 return changectx(self._repo, anc)
572 return changectx(self._repo, anc)
573
573
574 def descendant(self, other):
574 def descendant(self, other):
575 """True if other is descendant of this changeset"""
575 """True if other is descendant of this changeset"""
576 return self._repo.changelog.descendant(self._rev, other._rev)
576 return self._repo.changelog.descendant(self._rev, other._rev)
577
577
578 def walk(self, match):
578 def walk(self, match):
579 fset = set(match.files())
579 fset = set(match.files())
580 # for dirstate.walk, files=['.'] means "walk the whole tree".
580 # for dirstate.walk, files=['.'] means "walk the whole tree".
581 # follow that here, too
581 # follow that here, too
582 fset.discard('.')
582 fset.discard('.')
583
583
584 # avoid the entire walk if we're only looking for specific files
584 # avoid the entire walk if we're only looking for specific files
585 if fset and not match.anypats():
585 if fset and not match.anypats():
586 if util.all([fn in self for fn in fset]):
586 if util.all([fn in self for fn in fset]):
587 for fn in sorted(fset):
587 for fn in sorted(fset):
588 if match(fn):
588 if match(fn):
589 yield fn
589 yield fn
590 raise StopIteration
590 raise StopIteration
591
591
592 for fn in self:
592 for fn in self:
593 if fn in fset:
593 if fn in fset:
594 # specified pattern is the exact name
594 # specified pattern is the exact name
595 fset.remove(fn)
595 fset.remove(fn)
596 if match(fn):
596 if match(fn):
597 yield fn
597 yield fn
598 for fn in sorted(fset):
598 for fn in sorted(fset):
599 if fn in self._dirs:
599 if fn in self._dirs:
600 # specified pattern is a directory
600 # specified pattern is a directory
601 continue
601 continue
602 match.bad(fn, _('no such file in rev %s') % self)
602 match.bad(fn, _('no such file in rev %s') % self)
603
603
604 def matches(self, match):
604 def matches(self, match):
605 return self.walk(match)
605 return self.walk(match)
606
606
607 class basefilectx(object):
607 class basefilectx(object):
608 """A filecontext object represents the common logic for its children:
608 """A filecontext object represents the common logic for its children:
609 filectx: read-only access to a filerevision that is already present
609 filectx: read-only access to a filerevision that is already present
610 in the repo,
610 in the repo,
611 workingfilectx: a filecontext that represents files from the working
611 workingfilectx: a filecontext that represents files from the working
612 directory,
612 directory,
613 memfilectx: a filecontext that represents files in-memory."""
613 memfilectx: a filecontext that represents files in-memory."""
614 def __new__(cls, repo, path, *args, **kwargs):
614 def __new__(cls, repo, path, *args, **kwargs):
615 return super(basefilectx, cls).__new__(cls)
615 return super(basefilectx, cls).__new__(cls)
616
616
617 @propertycache
617 @propertycache
618 def _filelog(self):
618 def _filelog(self):
619 return self._repo.file(self._path)
619 return self._repo.file(self._path)
620
620
621 @propertycache
621 @propertycache
622 def _changeid(self):
622 def _changeid(self):
623 if '_changeid' in self.__dict__:
623 if '_changeid' in self.__dict__:
624 return self._changeid
624 return self._changeid
625 elif '_changectx' in self.__dict__:
625 elif '_changectx' in self.__dict__:
626 return self._changectx.rev()
626 return self._changectx.rev()
627 else:
627 else:
628 return self._filelog.linkrev(self._filerev)
628 return self._filelog.linkrev(self._filerev)
629
629
630 @propertycache
630 @propertycache
631 def _filenode(self):
631 def _filenode(self):
632 if '_fileid' in self.__dict__:
632 if '_fileid' in self.__dict__:
633 return self._filelog.lookup(self._fileid)
633 return self._filelog.lookup(self._fileid)
634 else:
634 else:
635 return self._changectx.filenode(self._path)
635 return self._changectx.filenode(self._path)
636
636
637 @propertycache
637 @propertycache
638 def _filerev(self):
638 def _filerev(self):
639 return self._filelog.rev(self._filenode)
639 return self._filelog.rev(self._filenode)
640
640
641 @propertycache
641 @propertycache
642 def _repopath(self):
642 def _repopath(self):
643 return self._path
643 return self._path
644
644
645 def __nonzero__(self):
645 def __nonzero__(self):
646 try:
646 try:
647 self._filenode
647 self._filenode
648 return True
648 return True
649 except error.LookupError:
649 except error.LookupError:
650 # file is missing
650 # file is missing
651 return False
651 return False
652
652
653 def __str__(self):
653 def __str__(self):
654 return "%s@%s" % (self.path(), self._changectx)
654 return "%s@%s" % (self.path(), self._changectx)
655
655
656 def __repr__(self):
656 def __repr__(self):
657 return "<%s %s>" % (type(self).__name__, str(self))
657 return "<%s %s>" % (type(self).__name__, str(self))
658
658
659 def __hash__(self):
659 def __hash__(self):
660 try:
660 try:
661 return hash((self._path, self._filenode))
661 return hash((self._path, self._filenode))
662 except AttributeError:
662 except AttributeError:
663 return id(self)
663 return id(self)
664
664
665 def __eq__(self, other):
665 def __eq__(self, other):
666 try:
666 try:
667 return (type(self) == type(other) and self._path == other._path
667 return (type(self) == type(other) and self._path == other._path
668 and self._filenode == other._filenode)
668 and self._filenode == other._filenode)
669 except AttributeError:
669 except AttributeError:
670 return False
670 return False
671
671
672 def __ne__(self, other):
672 def __ne__(self, other):
673 return not (self == other)
673 return not (self == other)
674
674
675 def filerev(self):
675 def filerev(self):
676 return self._filerev
676 return self._filerev
677 def filenode(self):
677 def filenode(self):
678 return self._filenode
678 return self._filenode
679 def flags(self):
679 def flags(self):
680 return self._changectx.flags(self._path)
680 return self._changectx.flags(self._path)
681 def filelog(self):
681 def filelog(self):
682 return self._filelog
682 return self._filelog
683 def rev(self):
683 def rev(self):
684 return self._changeid
684 return self._changeid
685 def linkrev(self):
685 def linkrev(self):
686 return self._filelog.linkrev(self._filerev)
686 return self._filelog.linkrev(self._filerev)
687 def node(self):
687 def node(self):
688 return self._changectx.node()
688 return self._changectx.node()
689 def hex(self):
689 def hex(self):
690 return self._changectx.hex()
690 return self._changectx.hex()
691 def user(self):
691 def user(self):
692 return self._changectx.user()
692 return self._changectx.user()
693 def date(self):
693 def date(self):
694 return self._changectx.date()
694 return self._changectx.date()
695 def files(self):
695 def files(self):
696 return self._changectx.files()
696 return self._changectx.files()
697 def description(self):
697 def description(self):
698 return self._changectx.description()
698 return self._changectx.description()
699 def branch(self):
699 def branch(self):
700 return self._changectx.branch()
700 return self._changectx.branch()
701 def extra(self):
701 def extra(self):
702 return self._changectx.extra()
702 return self._changectx.extra()
703 def phase(self):
703 def phase(self):
704 return self._changectx.phase()
704 return self._changectx.phase()
705 def phasestr(self):
705 def phasestr(self):
706 return self._changectx.phasestr()
706 return self._changectx.phasestr()
707 def manifest(self):
707 def manifest(self):
708 return self._changectx.manifest()
708 return self._changectx.manifest()
709 def changectx(self):
709 def changectx(self):
710 return self._changectx
710 return self._changectx
711
711
712 def path(self):
712 def path(self):
713 return self._path
713 return self._path
714
714
715 def isbinary(self):
715 def isbinary(self):
716 try:
716 try:
717 return util.binary(self.data())
717 return util.binary(self.data())
718 except IOError:
718 except IOError:
719 return False
719 return False
720 def isexec(self):
720 def isexec(self):
721 return 'x' in self.flags()
721 return 'x' in self.flags()
722 def islink(self):
722 def islink(self):
723 return 'l' in self.flags()
723 return 'l' in self.flags()
724
724
725 def cmp(self, fctx):
725 def cmp(self, fctx):
726 """compare with other file context
726 """compare with other file context
727
727
728 returns True if different than fctx.
728 returns True if different than fctx.
729 """
729 """
730 if (fctx._filerev is None
730 if (fctx._filerev is None
731 and (self._repo._encodefilterpats
731 and (self._repo._encodefilterpats
732 # if file data starts with '\1\n', empty metadata block is
732 # if file data starts with '\1\n', empty metadata block is
733 # prepended, which adds 4 bytes to filelog.size().
733 # prepended, which adds 4 bytes to filelog.size().
734 or self.size() - 4 == fctx.size())
734 or self.size() - 4 == fctx.size())
735 or self.size() == fctx.size()):
735 or self.size() == fctx.size()):
736 return self._filelog.cmp(self._filenode, fctx.data())
736 return self._filelog.cmp(self._filenode, fctx.data())
737
737
738 return True
738 return True
739
739
740 def parents(self):
740 def parents(self):
741 _path = self._path
741 _path = self._path
742 fl = self._filelog
742 fl = self._filelog
743 pl = [(_path, n, fl) for n in self._filelog.parents(self._filenode)]
743 pl = [(_path, n, fl) for n in self._filelog.parents(self._filenode)]
744
744
745 r = self._filelog.renamed(self._filenode)
745 r = self._filelog.renamed(self._filenode)
746 if r:
746 if r:
747 pl[0] = (r[0], r[1], None)
747 pl[0] = (r[0], r[1], None)
748
748
749 return [filectx(self._repo, p, fileid=n, filelog=l)
749 return [filectx(self._repo, p, fileid=n, filelog=l)
750 for p, n, l in pl if n != nullid]
750 for p, n, l in pl if n != nullid]
751
751
752 def p1(self):
752 def p1(self):
753 return self.parents()[0]
753 return self.parents()[0]
754
754
755 def p2(self):
755 def p2(self):
756 p = self.parents()
756 p = self.parents()
757 if len(p) == 2:
757 if len(p) == 2:
758 return p[1]
758 return p[1]
759 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
759 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
760
760
761 def annotate(self, follow=False, linenumber=None, diffopts=None):
761 def annotate(self, follow=False, linenumber=None, diffopts=None):
762 '''returns a list of tuples of (ctx, line) for each line
762 '''returns a list of tuples of (ctx, line) for each line
763 in the file, where ctx is the filectx of the node where
763 in the file, where ctx is the filectx of the node where
764 that line was last changed.
764 that line was last changed.
765 This returns tuples of ((ctx, linenumber), line) for each line,
765 This returns tuples of ((ctx, linenumber), line) for each line,
766 if "linenumber" parameter is NOT "None".
766 if "linenumber" parameter is NOT "None".
767 In such tuples, linenumber means one at the first appearance
767 In such tuples, linenumber means one at the first appearance
768 in the managed file.
768 in the managed file.
769 To reduce annotation cost,
769 To reduce annotation cost,
770 this returns fixed value(False is used) as linenumber,
770 this returns fixed value(False is used) as linenumber,
771 if "linenumber" parameter is "False".'''
771 if "linenumber" parameter is "False".'''
772
772
773 if linenumber is None:
773 if linenumber is None:
774 def decorate(text, rev):
774 def decorate(text, rev):
775 return ([rev] * len(text.splitlines()), text)
775 return ([rev] * len(text.splitlines()), text)
776 elif linenumber:
776 elif linenumber:
777 def decorate(text, rev):
777 def decorate(text, rev):
778 size = len(text.splitlines())
778 size = len(text.splitlines())
779 return ([(rev, i) for i in xrange(1, size + 1)], text)
779 return ([(rev, i) for i in xrange(1, size + 1)], text)
780 else:
780 else:
781 def decorate(text, rev):
781 def decorate(text, rev):
782 return ([(rev, False)] * len(text.splitlines()), text)
782 return ([(rev, False)] * len(text.splitlines()), text)
783
783
784 def pair(parent, child):
784 def pair(parent, child):
785 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
785 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
786 refine=True)
786 refine=True)
787 for (a1, a2, b1, b2), t in blocks:
787 for (a1, a2, b1, b2), t in blocks:
788 # Changed blocks ('!') or blocks made only of blank lines ('~')
788 # Changed blocks ('!') or blocks made only of blank lines ('~')
789 # belong to the child.
789 # belong to the child.
790 if t == '=':
790 if t == '=':
791 child[0][b1:b2] = parent[0][a1:a2]
791 child[0][b1:b2] = parent[0][a1:a2]
792 return child
792 return child
793
793
794 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
794 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
795
795
796 def parents(f):
796 def parents(f):
797 pl = f.parents()
797 pl = f.parents()
798
798
799 # Don't return renamed parents if we aren't following.
799 # Don't return renamed parents if we aren't following.
800 if not follow:
800 if not follow:
801 pl = [p for p in pl if p.path() == f.path()]
801 pl = [p for p in pl if p.path() == f.path()]
802
802
803 # renamed filectx won't have a filelog yet, so set it
803 # renamed filectx won't have a filelog yet, so set it
804 # from the cache to save time
804 # from the cache to save time
805 for p in pl:
805 for p in pl:
806 if not '_filelog' in p.__dict__:
806 if not '_filelog' in p.__dict__:
807 p._filelog = getlog(p.path())
807 p._filelog = getlog(p.path())
808
808
809 return pl
809 return pl
810
810
811 # use linkrev to find the first changeset where self appeared
811 # use linkrev to find the first changeset where self appeared
812 if self.rev() != self.linkrev():
812 if self.rev() != self.linkrev():
813 base = self.filectx(self.filenode())
813 base = self.filectx(self.filenode())
814 else:
814 else:
815 base = self
815 base = self
816
816
817 # This algorithm would prefer to be recursive, but Python is a
817 # This algorithm would prefer to be recursive, but Python is a
818 # bit recursion-hostile. Instead we do an iterative
818 # bit recursion-hostile. Instead we do an iterative
819 # depth-first search.
819 # depth-first search.
820
820
821 visit = [base]
821 visit = [base]
822 hist = {}
822 hist = {}
823 pcache = {}
823 pcache = {}
824 needed = {base: 1}
824 needed = {base: 1}
825 while visit:
825 while visit:
826 f = visit[-1]
826 f = visit[-1]
827 pcached = f in pcache
827 pcached = f in pcache
828 if not pcached:
828 if not pcached:
829 pcache[f] = parents(f)
829 pcache[f] = parents(f)
830
830
831 ready = True
831 ready = True
832 pl = pcache[f]
832 pl = pcache[f]
833 for p in pl:
833 for p in pl:
834 if p not in hist:
834 if p not in hist:
835 ready = False
835 ready = False
836 visit.append(p)
836 visit.append(p)
837 if not pcached:
837 if not pcached:
838 needed[p] = needed.get(p, 0) + 1
838 needed[p] = needed.get(p, 0) + 1
839 if ready:
839 if ready:
840 visit.pop()
840 visit.pop()
841 reusable = f in hist
841 reusable = f in hist
842 if reusable:
842 if reusable:
843 curr = hist[f]
843 curr = hist[f]
844 else:
844 else:
845 curr = decorate(f.data(), f)
845 curr = decorate(f.data(), f)
846 for p in pl:
846 for p in pl:
847 if not reusable:
847 if not reusable:
848 curr = pair(hist[p], curr)
848 curr = pair(hist[p], curr)
849 if needed[p] == 1:
849 if needed[p] == 1:
850 del hist[p]
850 del hist[p]
851 del needed[p]
851 del needed[p]
852 else:
852 else:
853 needed[p] -= 1
853 needed[p] -= 1
854
854
855 hist[f] = curr
855 hist[f] = curr
856 pcache[f] = []
856 pcache[f] = []
857
857
858 return zip(hist[base][0], hist[base][1].splitlines(True))
858 return zip(hist[base][0], hist[base][1].splitlines(True))
859
859
860 def ancestors(self, followfirst=False):
860 def ancestors(self, followfirst=False):
861 visit = {}
861 visit = {}
862 c = self
862 c = self
863 cut = followfirst and 1 or None
863 cut = followfirst and 1 or None
864 while True:
864 while True:
865 for parent in c.parents()[:cut]:
865 for parent in c.parents()[:cut]:
866 visit[(parent.rev(), parent.node())] = parent
866 visit[(parent.rev(), parent.node())] = parent
867 if not visit:
867 if not visit:
868 break
868 break
869 c = visit.pop(max(visit))
869 c = visit.pop(max(visit))
870 yield c
870 yield c
871
871
872 class filectx(basefilectx):
872 class filectx(basefilectx):
873 """A filecontext object makes access to data related to a particular
873 """A filecontext object makes access to data related to a particular
874 filerevision convenient."""
874 filerevision convenient."""
875 def __init__(self, repo, path, changeid=None, fileid=None,
875 def __init__(self, repo, path, changeid=None, fileid=None,
876 filelog=None, changectx=None):
876 filelog=None, changectx=None):
877 """changeid can be a changeset revision, node, or tag.
877 """changeid can be a changeset revision, node, or tag.
878 fileid can be a file revision or node."""
878 fileid can be a file revision or node."""
879 self._repo = repo
879 self._repo = repo
880 self._path = path
880 self._path = path
881
881
882 assert (changeid is not None
882 assert (changeid is not None
883 or fileid is not None
883 or fileid is not None
884 or changectx is not None), \
884 or changectx is not None), \
885 ("bad args: changeid=%r, fileid=%r, changectx=%r"
885 ("bad args: changeid=%r, fileid=%r, changectx=%r"
886 % (changeid, fileid, changectx))
886 % (changeid, fileid, changectx))
887
887
888 if filelog is not None:
888 if filelog is not None:
889 self._filelog = filelog
889 self._filelog = filelog
890
890
891 if changeid is not None:
891 if changeid is not None:
892 self._changeid = changeid
892 self._changeid = changeid
893 if changectx is not None:
893 if changectx is not None:
894 self._changectx = changectx
894 self._changectx = changectx
895 if fileid is not None:
895 if fileid is not None:
896 self._fileid = fileid
896 self._fileid = fileid
897
897
898 @propertycache
898 @propertycache
899 def _changectx(self):
899 def _changectx(self):
900 try:
900 try:
901 return changectx(self._repo, self._changeid)
901 return changectx(self._repo, self._changeid)
902 except error.RepoLookupError:
902 except error.RepoLookupError:
903 # Linkrev may point to any revision in the repository. When the
903 # Linkrev may point to any revision in the repository. When the
904 # repository is filtered this may lead to `filectx` trying to build
904 # repository is filtered this may lead to `filectx` trying to build
905 # `changectx` for filtered revision. In such case we fallback to
905 # `changectx` for filtered revision. In such case we fallback to
906 # creating `changectx` on the unfiltered version of the reposition.
906 # creating `changectx` on the unfiltered version of the reposition.
907 # This fallback should not be an issue because `changectx` from
907 # This fallback should not be an issue because `changectx` from
908 # `filectx` are not used in complex operations that care about
908 # `filectx` are not used in complex operations that care about
909 # filtering.
909 # filtering.
910 #
910 #
911 # This fallback is a cheap and dirty fix that prevent several
911 # This fallback is a cheap and dirty fix that prevent several
912 # crashes. It does not ensure the behavior is correct. However the
912 # crashes. It does not ensure the behavior is correct. However the
913 # behavior was not correct before filtering either and "incorrect
913 # behavior was not correct before filtering either and "incorrect
914 # behavior" is seen as better as "crash"
914 # behavior" is seen as better as "crash"
915 #
915 #
916 # Linkrevs have several serious troubles with filtering that are
916 # Linkrevs have several serious troubles with filtering that are
917 # complicated to solve. Proper handling of the issue here should be
917 # complicated to solve. Proper handling of the issue here should be
918 # considered when solving linkrev issue are on the table.
918 # considered when solving linkrev issue are on the table.
919 return changectx(self._repo.unfiltered(), self._changeid)
919 return changectx(self._repo.unfiltered(), self._changeid)
920
920
921 def filectx(self, fileid):
921 def filectx(self, fileid):
922 '''opens an arbitrary revision of the file without
922 '''opens an arbitrary revision of the file without
923 opening a new filelog'''
923 opening a new filelog'''
924 return filectx(self._repo, self._path, fileid=fileid,
924 return filectx(self._repo, self._path, fileid=fileid,
925 filelog=self._filelog)
925 filelog=self._filelog)
926
926
927 def data(self):
927 def data(self):
928 try:
928 try:
929 return self._filelog.read(self._filenode)
929 return self._filelog.read(self._filenode)
930 except error.CensoredNodeError:
930 except error.CensoredNodeError:
931 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
931 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
932 return ""
932 return ""
933 raise util.Abort(_("censored node: %s") % short(self._filenode),
933 raise util.Abort(_("censored node: %s") % short(self._filenode),
934 hint=_("set censor.policy to ignore errors"))
934 hint=_("set censor.policy to ignore errors"))
935
935
936 def size(self):
936 def size(self):
937 return self._filelog.size(self._filerev)
937 return self._filelog.size(self._filerev)
938
938
939 def renamed(self):
939 def renamed(self):
940 """check if file was actually renamed in this changeset revision
940 """check if file was actually renamed in this changeset revision
941
941
942 If rename logged in file revision, we report copy for changeset only
942 If rename logged in file revision, we report copy for changeset only
943 if file revisions linkrev points back to the changeset in question
943 if file revisions linkrev points back to the changeset in question
944 or both changeset parents contain different file revisions.
944 or both changeset parents contain different file revisions.
945 """
945 """
946
946
947 renamed = self._filelog.renamed(self._filenode)
947 renamed = self._filelog.renamed(self._filenode)
948 if not renamed:
948 if not renamed:
949 return renamed
949 return renamed
950
950
951 if self.rev() == self.linkrev():
951 if self.rev() == self.linkrev():
952 return renamed
952 return renamed
953
953
954 name = self.path()
954 name = self.path()
955 fnode = self._filenode
955 fnode = self._filenode
956 for p in self._changectx.parents():
956 for p in self._changectx.parents():
957 try:
957 try:
958 if fnode == p.filenode(name):
958 if fnode == p.filenode(name):
959 return None
959 return None
960 except error.LookupError:
960 except error.LookupError:
961 pass
961 pass
962 return renamed
962 return renamed
963
963
964 def children(self):
964 def children(self):
965 # hard for renames
965 # hard for renames
966 c = self._filelog.children(self._filenode)
966 c = self._filelog.children(self._filenode)
967 return [filectx(self._repo, self._path, fileid=x,
967 return [filectx(self._repo, self._path, fileid=x,
968 filelog=self._filelog) for x in c]
968 filelog=self._filelog) for x in c]
969
969
970 class committablectx(basectx):
970 class committablectx(basectx):
971 """A committablectx object provides common functionality for a context that
971 """A committablectx object provides common functionality for a context that
972 wants the ability to commit, e.g. workingctx or memctx."""
972 wants the ability to commit, e.g. workingctx or memctx."""
973 def __init__(self, repo, text="", user=None, date=None, extra=None,
973 def __init__(self, repo, text="", user=None, date=None, extra=None,
974 changes=None):
974 changes=None):
975 self._repo = repo
975 self._repo = repo
976 self._rev = None
976 self._rev = None
977 self._node = None
977 self._node = None
978 self._text = text
978 self._text = text
979 if date:
979 if date:
980 self._date = util.parsedate(date)
980 self._date = util.parsedate(date)
981 if user:
981 if user:
982 self._user = user
982 self._user = user
983 if changes:
983 if changes:
984 self._status = changes
984 self._status = changes
985
985
986 self._extra = {}
986 self._extra = {}
987 if extra:
987 if extra:
988 self._extra = extra.copy()
988 self._extra = extra.copy()
989 if 'branch' not in self._extra:
989 if 'branch' not in self._extra:
990 try:
990 try:
991 branch = encoding.fromlocal(self._repo.dirstate.branch())
991 branch = encoding.fromlocal(self._repo.dirstate.branch())
992 except UnicodeDecodeError:
992 except UnicodeDecodeError:
993 raise util.Abort(_('branch name not in UTF-8!'))
993 raise util.Abort(_('branch name not in UTF-8!'))
994 self._extra['branch'] = branch
994 self._extra['branch'] = branch
995 if self._extra['branch'] == '':
995 if self._extra['branch'] == '':
996 self._extra['branch'] = 'default'
996 self._extra['branch'] = 'default'
997
997
998 def __str__(self):
998 def __str__(self):
999 return str(self._parents[0]) + "+"
999 return str(self._parents[0]) + "+"
1000
1000
1001 def __nonzero__(self):
1001 def __nonzero__(self):
1002 return True
1002 return True
1003
1003
1004 def _buildflagfunc(self):
1004 def _buildflagfunc(self):
1005 # Create a fallback function for getting file flags when the
1005 # Create a fallback function for getting file flags when the
1006 # filesystem doesn't support them
1006 # filesystem doesn't support them
1007
1007
1008 copiesget = self._repo.dirstate.copies().get
1008 copiesget = self._repo.dirstate.copies().get
1009
1009
1010 if len(self._parents) < 2:
1010 if len(self._parents) < 2:
1011 # when we have one parent, it's easy: copy from parent
1011 # when we have one parent, it's easy: copy from parent
1012 man = self._parents[0].manifest()
1012 man = self._parents[0].manifest()
1013 def func(f):
1013 def func(f):
1014 f = copiesget(f, f)
1014 f = copiesget(f, f)
1015 return man.flags(f)
1015 return man.flags(f)
1016 else:
1016 else:
1017 # merges are tricky: we try to reconstruct the unstored
1017 # merges are tricky: we try to reconstruct the unstored
1018 # result from the merge (issue1802)
1018 # result from the merge (issue1802)
1019 p1, p2 = self._parents
1019 p1, p2 = self._parents
1020 pa = p1.ancestor(p2)
1020 pa = p1.ancestor(p2)
1021 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1021 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1022
1022
1023 def func(f):
1023 def func(f):
1024 f = copiesget(f, f) # may be wrong for merges with copies
1024 f = copiesget(f, f) # may be wrong for merges with copies
1025 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1025 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1026 if fl1 == fl2:
1026 if fl1 == fl2:
1027 return fl1
1027 return fl1
1028 if fl1 == fla:
1028 if fl1 == fla:
1029 return fl2
1029 return fl2
1030 if fl2 == fla:
1030 if fl2 == fla:
1031 return fl1
1031 return fl1
1032 return '' # punt for conflicts
1032 return '' # punt for conflicts
1033
1033
1034 return func
1034 return func
1035
1035
1036 @propertycache
1036 @propertycache
1037 def _flagfunc(self):
1037 def _flagfunc(self):
1038 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1038 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1039
1039
1040 @propertycache
1040 @propertycache
1041 def _manifest(self):
1041 def _manifest(self):
1042 """generate a manifest corresponding to the values in self._status
1042 """generate a manifest corresponding to the values in self._status
1043
1043
1044 This reuse the file nodeid from parent, but we append an extra letter
1044 This reuse the file nodeid from parent, but we append an extra letter
1045 when modified. Modified files get an extra 'm' while added files get
1045 when modified. Modified files get an extra 'm' while added files get
1046 an extra 'a'. This is used by manifests merge to see that files
1046 an extra 'a'. This is used by manifests merge to see that files
1047 are different and by update logic to avoid deleting newly added files.
1047 are different and by update logic to avoid deleting newly added files.
1048 """
1048 """
1049
1049
1050 man1 = self._parents[0].manifest()
1050 man1 = self._parents[0].manifest()
1051 man = man1.copy()
1051 man = man1.copy()
1052 if len(self._parents) > 1:
1052 if len(self._parents) > 1:
1053 man2 = self.p2().manifest()
1053 man2 = self.p2().manifest()
1054 def getman(f):
1054 def getman(f):
1055 if f in man1:
1055 if f in man1:
1056 return man1
1056 return man1
1057 return man2
1057 return man2
1058 else:
1058 else:
1059 getman = lambda f: man1
1059 getman = lambda f: man1
1060
1060
1061 copied = self._repo.dirstate.copies()
1061 copied = self._repo.dirstate.copies()
1062 ff = self._flagfunc
1062 ff = self._flagfunc
1063 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1063 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1064 for f in l:
1064 for f in l:
1065 orig = copied.get(f, f)
1065 orig = copied.get(f, f)
1066 man[f] = getman(orig).get(orig, nullid) + i
1066 man[f] = getman(orig).get(orig, nullid) + i
1067 try:
1067 try:
1068 man.setflag(f, ff(f))
1068 man.setflag(f, ff(f))
1069 except OSError:
1069 except OSError:
1070 pass
1070 pass
1071
1071
1072 for f in self._status.deleted + self._status.removed:
1072 for f in self._status.deleted + self._status.removed:
1073 if f in man:
1073 if f in man:
1074 del man[f]
1074 del man[f]
1075
1075
1076 return man
1076 return man
1077
1077
1078 @propertycache
1078 @propertycache
1079 def _status(self):
1079 def _status(self):
1080 return self._repo.status()
1080 return self._repo.status()
1081
1081
1082 @propertycache
1082 @propertycache
1083 def _user(self):
1083 def _user(self):
1084 return self._repo.ui.username()
1084 return self._repo.ui.username()
1085
1085
1086 @propertycache
1086 @propertycache
1087 def _date(self):
1087 def _date(self):
1088 return util.makedate()
1088 return util.makedate()
1089
1089
1090 def subrev(self, subpath):
1090 def subrev(self, subpath):
1091 return None
1091 return None
1092
1092
1093 def user(self):
1093 def user(self):
1094 return self._user or self._repo.ui.username()
1094 return self._user or self._repo.ui.username()
1095 def date(self):
1095 def date(self):
1096 return self._date
1096 return self._date
1097 def description(self):
1097 def description(self):
1098 return self._text
1098 return self._text
1099 def files(self):
1099 def files(self):
1100 return sorted(self._status.modified + self._status.added +
1100 return sorted(self._status.modified + self._status.added +
1101 self._status.removed)
1101 self._status.removed)
1102
1102
1103 def modified(self):
1103 def modified(self):
1104 return self._status.modified
1104 return self._status.modified
1105 def added(self):
1105 def added(self):
1106 return self._status.added
1106 return self._status.added
1107 def removed(self):
1107 def removed(self):
1108 return self._status.removed
1108 return self._status.removed
1109 def deleted(self):
1109 def deleted(self):
1110 return self._status.deleted
1110 return self._status.deleted
1111 def unknown(self):
1111 def unknown(self):
1112 return self._status.unknown
1112 return self._status.unknown
1113 def ignored(self):
1113 def ignored(self):
1114 return self._status.ignored
1114 return self._status.ignored
1115 def clean(self):
1115 def clean(self):
1116 return self._status.clean
1116 return self._status.clean
1117 def branch(self):
1117 def branch(self):
1118 return encoding.tolocal(self._extra['branch'])
1118 return encoding.tolocal(self._extra['branch'])
1119 def closesbranch(self):
1119 def closesbranch(self):
1120 return 'close' in self._extra
1120 return 'close' in self._extra
1121 def extra(self):
1121 def extra(self):
1122 return self._extra
1122 return self._extra
1123
1123
1124 def tags(self):
1124 def tags(self):
1125 t = []
1125 t = []
1126 for p in self.parents():
1126 for p in self.parents():
1127 t.extend(p.tags())
1127 t.extend(p.tags())
1128 return t
1128 return t
1129
1129
1130 def bookmarks(self):
1130 def bookmarks(self):
1131 b = []
1131 b = []
1132 for p in self.parents():
1132 for p in self.parents():
1133 b.extend(p.bookmarks())
1133 b.extend(p.bookmarks())
1134 return b
1134 return b
1135
1135
1136 def phase(self):
1136 def phase(self):
1137 phase = phases.draft # default phase to draft
1137 phase = phases.draft # default phase to draft
1138 for p in self.parents():
1138 for p in self.parents():
1139 phase = max(phase, p.phase())
1139 phase = max(phase, p.phase())
1140 return phase
1140 return phase
1141
1141
1142 def hidden(self):
1142 def hidden(self):
1143 return False
1143 return False
1144
1144
1145 def children(self):
1145 def children(self):
1146 return []
1146 return []
1147
1147
1148 def flags(self, path):
1148 def flags(self, path):
1149 if '_manifest' in self.__dict__:
1149 if '_manifest' in self.__dict__:
1150 try:
1150 try:
1151 return self._manifest.flags(path)
1151 return self._manifest.flags(path)
1152 except KeyError:
1152 except KeyError:
1153 return ''
1153 return ''
1154
1154
1155 try:
1155 try:
1156 return self._flagfunc(path)
1156 return self._flagfunc(path)
1157 except OSError:
1157 except OSError:
1158 return ''
1158 return ''
1159
1159
1160 def ancestor(self, c2):
1160 def ancestor(self, c2):
1161 """return the "best" ancestor context of self and c2"""
1161 """return the "best" ancestor context of self and c2"""
1162 return self._parents[0].ancestor(c2) # punt on two parents for now
1162 return self._parents[0].ancestor(c2) # punt on two parents for now
1163
1163
1164 def walk(self, match):
1164 def walk(self, match):
1165 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1165 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1166 True, False))
1166 True, False))
1167
1167
1168 def matches(self, match):
1168 def matches(self, match):
1169 return sorted(self._repo.dirstate.matches(match))
1169 return sorted(self._repo.dirstate.matches(match))
1170
1170
1171 def ancestors(self):
1171 def ancestors(self):
1172 for a in self._repo.changelog.ancestors(
1172 for a in self._repo.changelog.ancestors(
1173 [p.rev() for p in self._parents]):
1173 [p.rev() for p in self._parents]):
1174 yield changectx(self._repo, a)
1174 yield changectx(self._repo, a)
1175
1175
1176 def markcommitted(self, node):
1176 def markcommitted(self, node):
1177 """Perform post-commit cleanup necessary after committing this ctx
1177 """Perform post-commit cleanup necessary after committing this ctx
1178
1178
1179 Specifically, this updates backing stores this working context
1179 Specifically, this updates backing stores this working context
1180 wraps to reflect the fact that the changes reflected by this
1180 wraps to reflect the fact that the changes reflected by this
1181 workingctx have been committed. For example, it marks
1181 workingctx have been committed. For example, it marks
1182 modified and added files as normal in the dirstate.
1182 modified and added files as normal in the dirstate.
1183
1183
1184 """
1184 """
1185
1185
1186 self._repo.dirstate.beginparentchange()
1186 self._repo.dirstate.beginparentchange()
1187 for f in self.modified() + self.added():
1187 for f in self.modified() + self.added():
1188 self._repo.dirstate.normal(f)
1188 self._repo.dirstate.normal(f)
1189 for f in self.removed():
1189 for f in self.removed():
1190 self._repo.dirstate.drop(f)
1190 self._repo.dirstate.drop(f)
1191 self._repo.dirstate.setparents(node)
1191 self._repo.dirstate.setparents(node)
1192 self._repo.dirstate.endparentchange()
1192 self._repo.dirstate.endparentchange()
1193
1193
1194 def dirs(self):
1194 def dirs(self):
1195 return self._repo.dirstate.dirs()
1195 return self._repo.dirstate.dirs()
1196
1196
1197 class workingctx(committablectx):
1197 class workingctx(committablectx):
1198 """A workingctx object makes access to data related to
1198 """A workingctx object makes access to data related to
1199 the current working directory convenient.
1199 the current working directory convenient.
1200 date - any valid date string or (unixtime, offset), or None.
1200 date - any valid date string or (unixtime, offset), or None.
1201 user - username string, or None.
1201 user - username string, or None.
1202 extra - a dictionary of extra values, or None.
1202 extra - a dictionary of extra values, or None.
1203 changes - a list of file lists as returned by localrepo.status()
1203 changes - a list of file lists as returned by localrepo.status()
1204 or None to use the repository status.
1204 or None to use the repository status.
1205 """
1205 """
1206 def __init__(self, repo, text="", user=None, date=None, extra=None,
1206 def __init__(self, repo, text="", user=None, date=None, extra=None,
1207 changes=None):
1207 changes=None):
1208 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1208 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1209
1209
1210 def __iter__(self):
1210 def __iter__(self):
1211 d = self._repo.dirstate
1211 d = self._repo.dirstate
1212 for f in d:
1212 for f in d:
1213 if d[f] != 'r':
1213 if d[f] != 'r':
1214 yield f
1214 yield f
1215
1215
1216 def __contains__(self, key):
1216 def __contains__(self, key):
1217 return self._repo.dirstate[key] not in "?r"
1217 return self._repo.dirstate[key] not in "?r"
1218
1218
1219 @propertycache
1219 @propertycache
1220 def _parents(self):
1220 def _parents(self):
1221 p = self._repo.dirstate.parents()
1221 p = self._repo.dirstate.parents()
1222 if p[1] == nullid:
1222 if p[1] == nullid:
1223 p = p[:-1]
1223 p = p[:-1]
1224 return [changectx(self._repo, x) for x in p]
1224 return [changectx(self._repo, x) for x in p]
1225
1225
1226 def filectx(self, path, filelog=None):
1226 def filectx(self, path, filelog=None):
1227 """get a file context from the working directory"""
1227 """get a file context from the working directory"""
1228 return workingfilectx(self._repo, path, workingctx=self,
1228 return workingfilectx(self._repo, path, workingctx=self,
1229 filelog=filelog)
1229 filelog=filelog)
1230
1230
1231 def dirty(self, missing=False, merge=True, branch=True):
1231 def dirty(self, missing=False, merge=True, branch=True):
1232 "check whether a working directory is modified"
1232 "check whether a working directory is modified"
1233 # check subrepos first
1233 # check subrepos first
1234 for s in sorted(self.substate):
1234 for s in sorted(self.substate):
1235 if self.sub(s).dirty():
1235 if self.sub(s).dirty():
1236 return True
1236 return True
1237 # check current working dir
1237 # check current working dir
1238 return ((merge and self.p2()) or
1238 return ((merge and self.p2()) or
1239 (branch and self.branch() != self.p1().branch()) or
1239 (branch and self.branch() != self.p1().branch()) or
1240 self.modified() or self.added() or self.removed() or
1240 self.modified() or self.added() or self.removed() or
1241 (missing and self.deleted()))
1241 (missing and self.deleted()))
1242
1242
1243 def add(self, list, prefix=""):
1243 def add(self, list, prefix=""):
1244 join = lambda f: os.path.join(prefix, f)
1244 join = lambda f: os.path.join(prefix, f)
1245 wlock = self._repo.wlock()
1245 wlock = self._repo.wlock()
1246 ui, ds = self._repo.ui, self._repo.dirstate
1246 ui, ds = self._repo.ui, self._repo.dirstate
1247 try:
1247 try:
1248 rejected = []
1248 rejected = []
1249 lstat = self._repo.wvfs.lstat
1249 lstat = self._repo.wvfs.lstat
1250 for f in list:
1250 for f in list:
1251 scmutil.checkportable(ui, join(f))
1251 scmutil.checkportable(ui, join(f))
1252 try:
1252 try:
1253 st = lstat(f)
1253 st = lstat(f)
1254 except OSError:
1254 except OSError:
1255 ui.warn(_("%s does not exist!\n") % join(f))
1255 ui.warn(_("%s does not exist!\n") % join(f))
1256 rejected.append(f)
1256 rejected.append(f)
1257 continue
1257 continue
1258 if st.st_size > 10000000:
1258 if st.st_size > 10000000:
1259 ui.warn(_("%s: up to %d MB of RAM may be required "
1259 ui.warn(_("%s: up to %d MB of RAM may be required "
1260 "to manage this file\n"
1260 "to manage this file\n"
1261 "(use 'hg revert %s' to cancel the "
1261 "(use 'hg revert %s' to cancel the "
1262 "pending addition)\n")
1262 "pending addition)\n")
1263 % (f, 3 * st.st_size // 1000000, join(f)))
1263 % (f, 3 * st.st_size // 1000000, join(f)))
1264 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1264 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1265 ui.warn(_("%s not added: only files and symlinks "
1265 ui.warn(_("%s not added: only files and symlinks "
1266 "supported currently\n") % join(f))
1266 "supported currently\n") % join(f))
1267 rejected.append(f)
1267 rejected.append(f)
1268 elif ds[f] in 'amn':
1268 elif ds[f] in 'amn':
1269 ui.warn(_("%s already tracked!\n") % join(f))
1269 ui.warn(_("%s already tracked!\n") % join(f))
1270 elif ds[f] == 'r':
1270 elif ds[f] == 'r':
1271 ds.normallookup(f)
1271 ds.normallookup(f)
1272 else:
1272 else:
1273 ds.add(f)
1273 ds.add(f)
1274 return rejected
1274 return rejected
1275 finally:
1275 finally:
1276 wlock.release()
1276 wlock.release()
1277
1277
1278 def forget(self, files, prefix=""):
1278 def forget(self, files, prefix=""):
1279 join = lambda f: os.path.join(prefix, f)
1279 join = lambda f: os.path.join(prefix, f)
1280 wlock = self._repo.wlock()
1280 wlock = self._repo.wlock()
1281 try:
1281 try:
1282 rejected = []
1282 rejected = []
1283 for f in files:
1283 for f in files:
1284 if f not in self._repo.dirstate:
1284 if f not in self._repo.dirstate:
1285 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1285 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1286 rejected.append(f)
1286 rejected.append(f)
1287 elif self._repo.dirstate[f] != 'a':
1287 elif self._repo.dirstate[f] != 'a':
1288 self._repo.dirstate.remove(f)
1288 self._repo.dirstate.remove(f)
1289 else:
1289 else:
1290 self._repo.dirstate.drop(f)
1290 self._repo.dirstate.drop(f)
1291 return rejected
1291 return rejected
1292 finally:
1292 finally:
1293 wlock.release()
1293 wlock.release()
1294
1294
1295 def undelete(self, list):
1295 def undelete(self, list):
1296 pctxs = self.parents()
1296 pctxs = self.parents()
1297 wlock = self._repo.wlock()
1297 wlock = self._repo.wlock()
1298 try:
1298 try:
1299 for f in list:
1299 for f in list:
1300 if self._repo.dirstate[f] != 'r':
1300 if self._repo.dirstate[f] != 'r':
1301 self._repo.ui.warn(_("%s not removed!\n") % f)
1301 self._repo.ui.warn(_("%s not removed!\n") % f)
1302 else:
1302 else:
1303 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1303 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1304 t = fctx.data()
1304 t = fctx.data()
1305 self._repo.wwrite(f, t, fctx.flags())
1305 self._repo.wwrite(f, t, fctx.flags())
1306 self._repo.dirstate.normal(f)
1306 self._repo.dirstate.normal(f)
1307 finally:
1307 finally:
1308 wlock.release()
1308 wlock.release()
1309
1309
1310 def copy(self, source, dest):
1310 def copy(self, source, dest):
1311 try:
1311 try:
1312 st = self._repo.wvfs.lstat(dest)
1312 st = self._repo.wvfs.lstat(dest)
1313 except OSError, err:
1313 except OSError, err:
1314 if err.errno != errno.ENOENT:
1314 if err.errno != errno.ENOENT:
1315 raise
1315 raise
1316 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1316 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1317 return
1317 return
1318 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1318 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1319 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1319 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1320 "symbolic link\n") % dest)
1320 "symbolic link\n") % dest)
1321 else:
1321 else:
1322 wlock = self._repo.wlock()
1322 wlock = self._repo.wlock()
1323 try:
1323 try:
1324 if self._repo.dirstate[dest] in '?':
1324 if self._repo.dirstate[dest] in '?':
1325 self._repo.dirstate.add(dest)
1325 self._repo.dirstate.add(dest)
1326 elif self._repo.dirstate[dest] in 'r':
1326 elif self._repo.dirstate[dest] in 'r':
1327 self._repo.dirstate.normallookup(dest)
1327 self._repo.dirstate.normallookup(dest)
1328 self._repo.dirstate.copy(source, dest)
1328 self._repo.dirstate.copy(source, dest)
1329 finally:
1329 finally:
1330 wlock.release()
1330 wlock.release()
1331
1331
1332 def _filtersuspectsymlink(self, files):
1332 def _filtersuspectsymlink(self, files):
1333 if not files or self._repo.dirstate._checklink:
1333 if not files or self._repo.dirstate._checklink:
1334 return files
1334 return files
1335
1335
1336 # Symlink placeholders may get non-symlink-like contents
1336 # Symlink placeholders may get non-symlink-like contents
1337 # via user error or dereferencing by NFS or Samba servers,
1337 # via user error or dereferencing by NFS or Samba servers,
1338 # so we filter out any placeholders that don't look like a
1338 # so we filter out any placeholders that don't look like a
1339 # symlink
1339 # symlink
1340 sane = []
1340 sane = []
1341 for f in files:
1341 for f in files:
1342 if self.flags(f) == 'l':
1342 if self.flags(f) == 'l':
1343 d = self[f].data()
1343 d = self[f].data()
1344 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1344 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1345 self._repo.ui.debug('ignoring suspect symlink placeholder'
1345 self._repo.ui.debug('ignoring suspect symlink placeholder'
1346 ' "%s"\n' % f)
1346 ' "%s"\n' % f)
1347 continue
1347 continue
1348 sane.append(f)
1348 sane.append(f)
1349 return sane
1349 return sane
1350
1350
1351 def _checklookup(self, files):
1351 def _checklookup(self, files):
1352 # check for any possibly clean files
1352 # check for any possibly clean files
1353 if not files:
1353 if not files:
1354 return [], []
1354 return [], []
1355
1355
1356 modified = []
1356 modified = []
1357 fixup = []
1357 fixup = []
1358 pctx = self._parents[0]
1358 pctx = self._parents[0]
1359 # do a full compare of any files that might have changed
1359 # do a full compare of any files that might have changed
1360 for f in sorted(files):
1360 for f in sorted(files):
1361 if (f not in pctx or self.flags(f) != pctx.flags(f)
1361 if (f not in pctx or self.flags(f) != pctx.flags(f)
1362 or pctx[f].cmp(self[f])):
1362 or pctx[f].cmp(self[f])):
1363 modified.append(f)
1363 modified.append(f)
1364 else:
1364 else:
1365 fixup.append(f)
1365 fixup.append(f)
1366
1366
1367 # update dirstate for files that are actually clean
1367 # update dirstate for files that are actually clean
1368 if fixup:
1368 if fixup:
1369 try:
1369 try:
1370 # updating the dirstate is optional
1370 # updating the dirstate is optional
1371 # so we don't wait on the lock
1371 # so we don't wait on the lock
1372 # wlock can invalidate the dirstate, so cache normal _after_
1372 # wlock can invalidate the dirstate, so cache normal _after_
1373 # taking the lock
1373 # taking the lock
1374 wlock = self._repo.wlock(False)
1374 wlock = self._repo.wlock(False)
1375 normal = self._repo.dirstate.normal
1375 normal = self._repo.dirstate.normal
1376 try:
1376 try:
1377 for f in fixup:
1377 for f in fixup:
1378 normal(f)
1378 normal(f)
1379 finally:
1379 finally:
1380 wlock.release()
1380 wlock.release()
1381 except error.LockError:
1381 except error.LockError:
1382 pass
1382 pass
1383 return modified, fixup
1383 return modified, fixup
1384
1384
1385 def _manifestmatches(self, match, s):
1385 def _manifestmatches(self, match, s):
1386 """Slow path for workingctx
1386 """Slow path for workingctx
1387
1387
1388 The fast path is when we compare the working directory to its parent
1388 The fast path is when we compare the working directory to its parent
1389 which means this function is comparing with a non-parent; therefore we
1389 which means this function is comparing with a non-parent; therefore we
1390 need to build a manifest and return what matches.
1390 need to build a manifest and return what matches.
1391 """
1391 """
1392 mf = self._repo['.']._manifestmatches(match, s)
1392 mf = self._repo['.']._manifestmatches(match, s)
1393 for f in s.modified + s.added:
1393 for f in s.modified + s.added:
1394 mf[f] = None
1394 mf[f] = None
1395 mf.setflag(f, self.flags(f))
1395 mf.setflag(f, self.flags(f))
1396 for f in s.removed:
1396 for f in s.removed:
1397 if f in mf:
1397 if f in mf:
1398 del mf[f]
1398 del mf[f]
1399 return mf
1399 return mf
1400
1400
1401 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1401 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1402 unknown=False):
1402 unknown=False):
1403 '''Gets the status from the dirstate -- internal use only.'''
1403 '''Gets the status from the dirstate -- internal use only.'''
1404 listignored, listclean, listunknown = ignored, clean, unknown
1404 listignored, listclean, listunknown = ignored, clean, unknown
1405 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1405 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1406 subrepos = []
1406 subrepos = []
1407 if '.hgsub' in self:
1407 if '.hgsub' in self:
1408 subrepos = sorted(self.substate)
1408 subrepos = sorted(self.substate)
1409 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1409 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1410 listclean, listunknown)
1410 listclean, listunknown)
1411
1411
1412 # check for any possibly clean files
1412 # check for any possibly clean files
1413 if cmp:
1413 if cmp:
1414 modified2, fixup = self._checklookup(cmp)
1414 modified2, fixup = self._checklookup(cmp)
1415 s.modified.extend(modified2)
1415 s.modified.extend(modified2)
1416
1416
1417 # update dirstate for files that are actually clean
1417 # update dirstate for files that are actually clean
1418 if fixup and listclean:
1418 if fixup and listclean:
1419 s.clean.extend(fixup)
1419 s.clean.extend(fixup)
1420
1420
1421 return s
1421 return s
1422
1422
1423 def _buildstatus(self, other, s, match, listignored, listclean,
1423 def _buildstatus(self, other, s, match, listignored, listclean,
1424 listunknown):
1424 listunknown):
1425 """build a status with respect to another context
1425 """build a status with respect to another context
1426
1426
1427 This includes logic for maintaining the fast path of status when
1427 This includes logic for maintaining the fast path of status when
1428 comparing the working directory against its parent, which is to skip
1428 comparing the working directory against its parent, which is to skip
1429 building a new manifest if self (working directory) is not comparing
1429 building a new manifest if self (working directory) is not comparing
1430 against its parent (repo['.']).
1430 against its parent (repo['.']).
1431 """
1431 """
1432 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1432 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1433 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1433 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1434 # might have accidentally ended up with the entire contents of the file
1434 # might have accidentally ended up with the entire contents of the file
1435 # they are supposed to be linking to.
1435 # they are supposed to be linking to.
1436 s.modified[:] = self._filtersuspectsymlink(s.modified)
1436 s.modified[:] = self._filtersuspectsymlink(s.modified)
1437 if other != self._repo['.']:
1437 if other != self._repo['.']:
1438 s = super(workingctx, self)._buildstatus(other, s, match,
1438 s = super(workingctx, self)._buildstatus(other, s, match,
1439 listignored, listclean,
1439 listignored, listclean,
1440 listunknown)
1440 listunknown)
1441 self._status = s
1441 self._status = s
1442 return s
1442 return s
1443
1443
1444 def _matchstatus(self, other, match):
1444 def _matchstatus(self, other, match):
1445 """override the match method with a filter for directory patterns
1445 """override the match method with a filter for directory patterns
1446
1446
1447 We use inheritance to customize the match.bad method only in cases of
1447 We use inheritance to customize the match.bad method only in cases of
1448 workingctx since it belongs only to the working directory when
1448 workingctx since it belongs only to the working directory when
1449 comparing against the parent changeset.
1449 comparing against the parent changeset.
1450
1450
1451 If we aren't comparing against the working directory's parent, then we
1451 If we aren't comparing against the working directory's parent, then we
1452 just use the default match object sent to us.
1452 just use the default match object sent to us.
1453 """
1453 """
1454 superself = super(workingctx, self)
1454 superself = super(workingctx, self)
1455 match = superself._matchstatus(other, match)
1455 match = superself._matchstatus(other, match)
1456 if other != self._repo['.']:
1456 if other != self._repo['.']:
1457 def bad(f, msg):
1457 def bad(f, msg):
1458 # 'f' may be a directory pattern from 'match.files()',
1458 # 'f' may be a directory pattern from 'match.files()',
1459 # so 'f not in ctx1' is not enough
1459 # so 'f not in ctx1' is not enough
1460 if f not in other and f not in other.dirs():
1460 if f not in other and f not in other.dirs():
1461 self._repo.ui.warn('%s: %s\n' %
1461 self._repo.ui.warn('%s: %s\n' %
1462 (self._repo.dirstate.pathto(f), msg))
1462 (self._repo.dirstate.pathto(f), msg))
1463 match.bad = bad
1463 match.bad = bad
1464 return match
1464 return match
1465
1465
1466 class committablefilectx(basefilectx):
1466 class committablefilectx(basefilectx):
1467 """A committablefilectx provides common functionality for a file context
1467 """A committablefilectx provides common functionality for a file context
1468 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1468 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1469 def __init__(self, repo, path, filelog=None, ctx=None):
1469 def __init__(self, repo, path, filelog=None, ctx=None):
1470 self._repo = repo
1470 self._repo = repo
1471 self._path = path
1471 self._path = path
1472 self._changeid = None
1472 self._changeid = None
1473 self._filerev = self._filenode = None
1473 self._filerev = self._filenode = None
1474
1474
1475 if filelog is not None:
1475 if filelog is not None:
1476 self._filelog = filelog
1476 self._filelog = filelog
1477 if ctx:
1477 if ctx:
1478 self._changectx = ctx
1478 self._changectx = ctx
1479
1479
1480 def __nonzero__(self):
1480 def __nonzero__(self):
1481 return True
1481 return True
1482
1482
1483 def parents(self):
1483 def parents(self):
1484 '''return parent filectxs, following copies if necessary'''
1484 '''return parent filectxs, following copies if necessary'''
1485 def filenode(ctx, path):
1485 def filenode(ctx, path):
1486 return ctx._manifest.get(path, nullid)
1486 return ctx._manifest.get(path, nullid)
1487
1487
1488 path = self._path
1488 path = self._path
1489 fl = self._filelog
1489 fl = self._filelog
1490 pcl = self._changectx._parents
1490 pcl = self._changectx._parents
1491 renamed = self.renamed()
1491 renamed = self.renamed()
1492
1492
1493 if renamed:
1493 if renamed:
1494 pl = [renamed + (None,)]
1494 pl = [renamed + (None,)]
1495 else:
1495 else:
1496 pl = [(path, filenode(pcl[0], path), fl)]
1496 pl = [(path, filenode(pcl[0], path), fl)]
1497
1497
1498 for pc in pcl[1:]:
1498 for pc in pcl[1:]:
1499 pl.append((path, filenode(pc, path), fl))
1499 pl.append((path, filenode(pc, path), fl))
1500
1500
1501 return [filectx(self._repo, p, fileid=n, filelog=l)
1501 return [filectx(self._repo, p, fileid=n, filelog=l)
1502 for p, n, l in pl if n != nullid]
1502 for p, n, l in pl if n != nullid]
1503
1503
1504 def children(self):
1504 def children(self):
1505 return []
1505 return []
1506
1506
1507 class workingfilectx(committablefilectx):
1507 class workingfilectx(committablefilectx):
1508 """A workingfilectx object makes access to data related to a particular
1508 """A workingfilectx object makes access to data related to a particular
1509 file in the working directory convenient."""
1509 file in the working directory convenient."""
1510 def __init__(self, repo, path, filelog=None, workingctx=None):
1510 def __init__(self, repo, path, filelog=None, workingctx=None):
1511 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1511 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1512
1512
1513 @propertycache
1513 @propertycache
1514 def _changectx(self):
1514 def _changectx(self):
1515 return workingctx(self._repo)
1515 return workingctx(self._repo)
1516
1516
1517 def data(self):
1517 def data(self):
1518 return self._repo.wread(self._path)
1518 return self._repo.wread(self._path)
1519 def renamed(self):
1519 def renamed(self):
1520 rp = self._repo.dirstate.copied(self._path)
1520 rp = self._repo.dirstate.copied(self._path)
1521 if not rp:
1521 if not rp:
1522 return None
1522 return None
1523 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1523 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1524
1524
1525 def size(self):
1525 def size(self):
1526 return self._repo.wvfs.lstat(self._path).st_size
1526 return self._repo.wvfs.lstat(self._path).st_size
1527 def date(self):
1527 def date(self):
1528 t, tz = self._changectx.date()
1528 t, tz = self._changectx.date()
1529 try:
1529 try:
1530 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1530 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1531 except OSError, err:
1531 except OSError, err:
1532 if err.errno != errno.ENOENT:
1532 if err.errno != errno.ENOENT:
1533 raise
1533 raise
1534 return (t, tz)
1534 return (t, tz)
1535
1535
1536 def cmp(self, fctx):
1536 def cmp(self, fctx):
1537 """compare with other file context
1537 """compare with other file context
1538
1538
1539 returns True if different than fctx.
1539 returns True if different than fctx.
1540 """
1540 """
1541 # fctx should be a filectx (not a workingfilectx)
1541 # fctx should be a filectx (not a workingfilectx)
1542 # invert comparison to reuse the same code path
1542 # invert comparison to reuse the same code path
1543 return fctx.cmp(self)
1543 return fctx.cmp(self)
1544
1544
1545 def remove(self, ignoremissing=False):
1545 def remove(self, ignoremissing=False):
1546 """wraps unlink for a repo's working directory"""
1546 """wraps unlink for a repo's working directory"""
1547 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1547 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1548
1548
1549 def write(self, data, flags):
1549 def write(self, data, flags):
1550 """wraps repo.wwrite"""
1550 """wraps repo.wwrite"""
1551 self._repo.wwrite(self._path, data, flags)
1551 self._repo.wwrite(self._path, data, flags)
1552
1552
1553 class memctx(committablectx):
1553 class memctx(committablectx):
1554 """Use memctx to perform in-memory commits via localrepo.commitctx().
1554 """Use memctx to perform in-memory commits via localrepo.commitctx().
1555
1555
1556 Revision information is supplied at initialization time while
1556 Revision information is supplied at initialization time while
1557 related files data and is made available through a callback
1557 related files data and is made available through a callback
1558 mechanism. 'repo' is the current localrepo, 'parents' is a
1558 mechanism. 'repo' is the current localrepo, 'parents' is a
1559 sequence of two parent revisions identifiers (pass None for every
1559 sequence of two parent revisions identifiers (pass None for every
1560 missing parent), 'text' is the commit message and 'files' lists
1560 missing parent), 'text' is the commit message and 'files' lists
1561 names of files touched by the revision (normalized and relative to
1561 names of files touched by the revision (normalized and relative to
1562 repository root).
1562 repository root).
1563
1563
1564 filectxfn(repo, memctx, path) is a callable receiving the
1564 filectxfn(repo, memctx, path) is a callable receiving the
1565 repository, the current memctx object and the normalized path of
1565 repository, the current memctx object and the normalized path of
1566 requested file, relative to repository root. It is fired by the
1566 requested file, relative to repository root. It is fired by the
1567 commit function for every file in 'files', but calls order is
1567 commit function for every file in 'files', but calls order is
1568 undefined. If the file is available in the revision being
1568 undefined. If the file is available in the revision being
1569 committed (updated or added), filectxfn returns a memfilectx
1569 committed (updated or added), filectxfn returns a memfilectx
1570 object. If the file was removed, filectxfn raises an
1570 object. If the file was removed, filectxfn raises an
1571 IOError. Moved files are represented by marking the source file
1571 IOError. Moved files are represented by marking the source file
1572 removed and the new file added with copy information (see
1572 removed and the new file added with copy information (see
1573 memfilectx).
1573 memfilectx).
1574
1574
1575 user receives the committer name and defaults to current
1575 user receives the committer name and defaults to current
1576 repository username, date is the commit date in any format
1576 repository username, date is the commit date in any format
1577 supported by util.parsedate() and defaults to current date, extra
1577 supported by util.parsedate() and defaults to current date, extra
1578 is a dictionary of metadata or is left empty.
1578 is a dictionary of metadata or is left empty.
1579 """
1579 """
1580
1580
1581 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1581 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1582 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1582 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1583 # this field to determine what to do in filectxfn.
1583 # this field to determine what to do in filectxfn.
1584 _returnnoneformissingfiles = True
1584 _returnnoneformissingfiles = True
1585
1585
1586 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1586 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1587 date=None, extra=None, editor=False):
1587 date=None, extra=None, editor=False):
1588 super(memctx, self).__init__(repo, text, user, date, extra)
1588 super(memctx, self).__init__(repo, text, user, date, extra)
1589 self._rev = None
1589 self._rev = None
1590 self._node = None
1590 self._node = None
1591 parents = [(p or nullid) for p in parents]
1591 parents = [(p or nullid) for p in parents]
1592 p1, p2 = parents
1592 p1, p2 = parents
1593 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1593 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1594 files = sorted(set(files))
1594 files = sorted(set(files))
1595 self._status = scmutil.status(files, [], [], [], [], [], [])
1595 self._status = scmutil.status(files, [], [], [], [], [], [])
1596 self._filectxfn = filectxfn
1596 self._filectxfn = filectxfn
1597 self.substate = {}
1597 self.substate = {}
1598
1598
1599 # if store is not callable, wrap it in a function
1599 # if store is not callable, wrap it in a function
1600 if not callable(filectxfn):
1600 if not callable(filectxfn):
1601 def getfilectx(repo, memctx, path):
1601 def getfilectx(repo, memctx, path):
1602 fctx = filectxfn[path]
1602 fctx = filectxfn[path]
1603 # this is weird but apparently we only keep track of one parent
1603 # this is weird but apparently we only keep track of one parent
1604 # (why not only store that instead of a tuple?)
1604 # (why not only store that instead of a tuple?)
1605 copied = fctx.renamed()
1605 copied = fctx.renamed()
1606 if copied:
1606 if copied:
1607 copied = copied[0]
1607 copied = copied[0]
1608 return memfilectx(repo, path, fctx.data(),
1608 return memfilectx(repo, path, fctx.data(),
1609 islink=fctx.islink(), isexec=fctx.isexec(),
1609 islink=fctx.islink(), isexec=fctx.isexec(),
1610 copied=copied, memctx=memctx)
1610 copied=copied, memctx=memctx)
1611 self._filectxfn = getfilectx
1611 self._filectxfn = getfilectx
1612
1612
1613 self._extra = extra and extra.copy() or {}
1613 self._extra = extra and extra.copy() or {}
1614 if self._extra.get('branch', '') == '':
1614 if self._extra.get('branch', '') == '':
1615 self._extra['branch'] = 'default'
1615 self._extra['branch'] = 'default'
1616
1616
1617 if editor:
1617 if editor:
1618 self._text = editor(self._repo, self, [])
1618 self._text = editor(self._repo, self, [])
1619 self._repo.savecommitmessage(self._text)
1619 self._repo.savecommitmessage(self._text)
1620
1620
1621 def filectx(self, path, filelog=None):
1621 def filectx(self, path, filelog=None):
1622 """get a file context from the working directory
1622 """get a file context from the working directory
1623
1623
1624 Returns None if file doesn't exist and should be removed."""
1624 Returns None if file doesn't exist and should be removed."""
1625 return self._filectxfn(self._repo, self, path)
1625 return self._filectxfn(self._repo, self, path)
1626
1626
1627 def commit(self):
1627 def commit(self):
1628 """commit context to the repo"""
1628 """commit context to the repo"""
1629 return self._repo.commitctx(self)
1629 return self._repo.commitctx(self)
1630
1630
1631 @propertycache
1631 @propertycache
1632 def _manifest(self):
1632 def _manifest(self):
1633 """generate a manifest based on the return values of filectxfn"""
1633 """generate a manifest based on the return values of filectxfn"""
1634
1634
1635 # keep this simple for now; just worry about p1
1635 # keep this simple for now; just worry about p1
1636 pctx = self._parents[0]
1636 pctx = self._parents[0]
1637 man = pctx.manifest().copy()
1637 man = pctx.manifest().copy()
1638
1638
1639 for f, fnode in man.iteritems():
1639 for f, fnode in man.iteritems():
1640 p1node = nullid
1640 p1node = nullid
1641 p2node = nullid
1641 p2node = nullid
1642 p = pctx[f].parents() # if file isn't in pctx, check p2?
1642 p = pctx[f].parents() # if file isn't in pctx, check p2?
1643 if len(p) > 0:
1643 if len(p) > 0:
1644 p1node = p[0].node()
1644 p1node = p[0].node()
1645 if len(p) > 1:
1645 if len(p) > 1:
1646 p2node = p[1].node()
1646 p2node = p[1].node()
1647 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1647 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1648
1648
1649 return man
1649 return man
1650
1650
1651
1651
1652 class memfilectx(committablefilectx):
1652 class memfilectx(committablefilectx):
1653 """memfilectx represents an in-memory file to commit.
1653 """memfilectx represents an in-memory file to commit.
1654
1654
1655 See memctx and committablefilectx for more details.
1655 See memctx and committablefilectx for more details.
1656 """
1656 """
1657 def __init__(self, repo, path, data, islink=False,
1657 def __init__(self, repo, path, data, islink=False,
1658 isexec=False, copied=None, memctx=None):
1658 isexec=False, copied=None, memctx=None):
1659 """
1659 """
1660 path is the normalized file path relative to repository root.
1660 path is the normalized file path relative to repository root.
1661 data is the file content as a string.
1661 data is the file content as a string.
1662 islink is True if the file is a symbolic link.
1662 islink is True if the file is a symbolic link.
1663 isexec is True if the file is executable.
1663 isexec is True if the file is executable.
1664 copied is the source file path if current file was copied in the
1664 copied is the source file path if current file was copied in the
1665 revision being committed, or None."""
1665 revision being committed, or None."""
1666 super(memfilectx, self).__init__(repo, path, None, memctx)
1666 super(memfilectx, self).__init__(repo, path, None, memctx)
1667 self._data = data
1667 self._data = data
1668 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1668 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1669 self._copied = None
1669 self._copied = None
1670 if copied:
1670 if copied:
1671 self._copied = (copied, nullid)
1671 self._copied = (copied, nullid)
1672
1672
1673 def data(self):
1673 def data(self):
1674 return self._data
1674 return self._data
1675 def size(self):
1675 def size(self):
1676 return len(self.data())
1676 return len(self.data())
1677 def flags(self):
1677 def flags(self):
1678 return self._flags
1678 return self._flags
1679 def renamed(self):
1679 def renamed(self):
1680 return self._copied
1680 return self._copied
1681
1681
1682 def remove(self, ignoremissing=False):
1682 def remove(self, ignoremissing=False):
1683 """wraps unlink for a repo's working directory"""
1683 """wraps unlink for a repo's working directory"""
1684 # need to figure out what to do here
1684 # need to figure out what to do here
1685 del self._changectx[self._path]
1685 del self._changectx[self._path]
1686
1686
1687 def write(self, data, flags):
1687 def write(self, data, flags):
1688 """wraps repo.wwrite"""
1688 """wraps repo.wwrite"""
1689 self._data = data
1689 self._data = data
@@ -1,1827 +1,1827 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-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 from node import hex, nullid, short
7 from node import hex, nullid, short
8 from i18n import _
8 from i18n import _
9 import urllib
9 import urllib
10 import peer, changegroup, subrepo, pushkey, obsolete, repoview
10 import peer, changegroup, subrepo, pushkey, obsolete, repoview
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
12 import lock as lockmod
12 import lock as lockmod
13 import transaction, store, encoding, exchange, bundle2
13 import transaction, store, encoding, exchange, bundle2
14 import scmutil, util, extensions, hook, error, revset
14 import scmutil, util, extensions, hook, error, revset
15 import match as matchmod
15 import match as matchmod
16 import merge as mergemod
16 import merge as mergemod
17 import tags as tagsmod
17 import tags as tagsmod
18 from lock import release
18 from lock import release
19 import weakref, errno, os, time, inspect
19 import weakref, errno, os, time, inspect
20 import branchmap, pathutil
20 import branchmap, pathutil
21 import namespaces
21 import namespaces
22 propertycache = util.propertycache
22 propertycache = util.propertycache
23 filecache = scmutil.filecache
23 filecache = scmutil.filecache
24
24
25 class repofilecache(filecache):
25 class repofilecache(filecache):
26 """All filecache usage on repo are done for logic that should be unfiltered
26 """All filecache usage on repo are done for logic that should be unfiltered
27 """
27 """
28
28
29 def __get__(self, repo, type=None):
29 def __get__(self, repo, type=None):
30 return super(repofilecache, self).__get__(repo.unfiltered(), type)
30 return super(repofilecache, self).__get__(repo.unfiltered(), type)
31 def __set__(self, repo, value):
31 def __set__(self, repo, value):
32 return super(repofilecache, self).__set__(repo.unfiltered(), value)
32 return super(repofilecache, self).__set__(repo.unfiltered(), value)
33 def __delete__(self, repo):
33 def __delete__(self, repo):
34 return super(repofilecache, self).__delete__(repo.unfiltered())
34 return super(repofilecache, self).__delete__(repo.unfiltered())
35
35
36 class storecache(repofilecache):
36 class storecache(repofilecache):
37 """filecache for files in the store"""
37 """filecache for files in the store"""
38 def join(self, obj, fname):
38 def join(self, obj, fname):
39 return obj.sjoin(fname)
39 return obj.sjoin(fname)
40
40
41 class unfilteredpropertycache(propertycache):
41 class unfilteredpropertycache(propertycache):
42 """propertycache that apply to unfiltered repo only"""
42 """propertycache that apply to unfiltered repo only"""
43
43
44 def __get__(self, repo, type=None):
44 def __get__(self, repo, type=None):
45 unfi = repo.unfiltered()
45 unfi = repo.unfiltered()
46 if unfi is repo:
46 if unfi is repo:
47 return super(unfilteredpropertycache, self).__get__(unfi)
47 return super(unfilteredpropertycache, self).__get__(unfi)
48 return getattr(unfi, self.name)
48 return getattr(unfi, self.name)
49
49
50 class filteredpropertycache(propertycache):
50 class filteredpropertycache(propertycache):
51 """propertycache that must take filtering in account"""
51 """propertycache that must take filtering in account"""
52
52
53 def cachevalue(self, obj, value):
53 def cachevalue(self, obj, value):
54 object.__setattr__(obj, self.name, value)
54 object.__setattr__(obj, self.name, value)
55
55
56
56
57 def hasunfilteredcache(repo, name):
57 def hasunfilteredcache(repo, name):
58 """check if a repo has an unfilteredpropertycache value for <name>"""
58 """check if a repo has an unfilteredpropertycache value for <name>"""
59 return name in vars(repo.unfiltered())
59 return name in vars(repo.unfiltered())
60
60
61 def unfilteredmethod(orig):
61 def unfilteredmethod(orig):
62 """decorate method that always need to be run on unfiltered version"""
62 """decorate method that always need to be run on unfiltered version"""
63 def wrapper(repo, *args, **kwargs):
63 def wrapper(repo, *args, **kwargs):
64 return orig(repo.unfiltered(), *args, **kwargs)
64 return orig(repo.unfiltered(), *args, **kwargs)
65 return wrapper
65 return wrapper
66
66
67 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
67 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
68 'unbundle'))
68 'unbundle'))
69 legacycaps = moderncaps.union(set(['changegroupsubset']))
69 legacycaps = moderncaps.union(set(['changegroupsubset']))
70
70
71 class localpeer(peer.peerrepository):
71 class localpeer(peer.peerrepository):
72 '''peer for a local repo; reflects only the most recent API'''
72 '''peer for a local repo; reflects only the most recent API'''
73
73
74 def __init__(self, repo, caps=moderncaps):
74 def __init__(self, repo, caps=moderncaps):
75 peer.peerrepository.__init__(self)
75 peer.peerrepository.__init__(self)
76 self._repo = repo.filtered('served')
76 self._repo = repo.filtered('served')
77 self.ui = repo.ui
77 self.ui = repo.ui
78 self._caps = repo._restrictcapabilities(caps)
78 self._caps = repo._restrictcapabilities(caps)
79 self.requirements = repo.requirements
79 self.requirements = repo.requirements
80 self.supportedformats = repo.supportedformats
80 self.supportedformats = repo.supportedformats
81
81
82 def close(self):
82 def close(self):
83 self._repo.close()
83 self._repo.close()
84
84
85 def _capabilities(self):
85 def _capabilities(self):
86 return self._caps
86 return self._caps
87
87
88 def local(self):
88 def local(self):
89 return self._repo
89 return self._repo
90
90
91 def canpush(self):
91 def canpush(self):
92 return True
92 return True
93
93
94 def url(self):
94 def url(self):
95 return self._repo.url()
95 return self._repo.url()
96
96
97 def lookup(self, key):
97 def lookup(self, key):
98 return self._repo.lookup(key)
98 return self._repo.lookup(key)
99
99
100 def branchmap(self):
100 def branchmap(self):
101 return self._repo.branchmap()
101 return self._repo.branchmap()
102
102
103 def heads(self):
103 def heads(self):
104 return self._repo.heads()
104 return self._repo.heads()
105
105
106 def known(self, nodes):
106 def known(self, nodes):
107 return self._repo.known(nodes)
107 return self._repo.known(nodes)
108
108
109 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
109 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
110 format='HG10', **kwargs):
110 format='HG10', **kwargs):
111 cg = exchange.getbundle(self._repo, source, heads=heads,
111 cg = exchange.getbundle(self._repo, source, heads=heads,
112 common=common, bundlecaps=bundlecaps, **kwargs)
112 common=common, bundlecaps=bundlecaps, **kwargs)
113 if bundlecaps is not None and 'HG2Y' in bundlecaps:
113 if bundlecaps is not None and 'HG2Y' in bundlecaps:
114 # When requesting a bundle2, getbundle returns a stream to make the
114 # When requesting a bundle2, getbundle returns a stream to make the
115 # wire level function happier. We need to build a proper object
115 # wire level function happier. We need to build a proper object
116 # from it in local peer.
116 # from it in local peer.
117 cg = bundle2.unbundle20(self.ui, cg)
117 cg = bundle2.unbundle20(self.ui, cg)
118 return cg
118 return cg
119
119
120 # TODO We might want to move the next two calls into legacypeer and add
120 # TODO We might want to move the next two calls into legacypeer and add
121 # unbundle instead.
121 # unbundle instead.
122
122
123 def unbundle(self, cg, heads, url):
123 def unbundle(self, cg, heads, url):
124 """apply a bundle on a repo
124 """apply a bundle on a repo
125
125
126 This function handles the repo locking itself."""
126 This function handles the repo locking itself."""
127 try:
127 try:
128 cg = exchange.readbundle(self.ui, cg, None)
128 cg = exchange.readbundle(self.ui, cg, None)
129 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
129 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
130 if util.safehasattr(ret, 'getchunks'):
130 if util.safehasattr(ret, 'getchunks'):
131 # This is a bundle20 object, turn it into an unbundler.
131 # This is a bundle20 object, turn it into an unbundler.
132 # This little dance should be dropped eventually when the API
132 # This little dance should be dropped eventually when the API
133 # is finally improved.
133 # is finally improved.
134 stream = util.chunkbuffer(ret.getchunks())
134 stream = util.chunkbuffer(ret.getchunks())
135 ret = bundle2.unbundle20(self.ui, stream)
135 ret = bundle2.unbundle20(self.ui, stream)
136 return ret
136 return ret
137 except error.PushRaced, exc:
137 except error.PushRaced, exc:
138 raise error.ResponseError(_('push failed:'), str(exc))
138 raise error.ResponseError(_('push failed:'), str(exc))
139
139
140 def lock(self):
140 def lock(self):
141 return self._repo.lock()
141 return self._repo.lock()
142
142
143 def addchangegroup(self, cg, source, url):
143 def addchangegroup(self, cg, source, url):
144 return changegroup.addchangegroup(self._repo, cg, source, url)
144 return changegroup.addchangegroup(self._repo, cg, source, url)
145
145
146 def pushkey(self, namespace, key, old, new):
146 def pushkey(self, namespace, key, old, new):
147 return self._repo.pushkey(namespace, key, old, new)
147 return self._repo.pushkey(namespace, key, old, new)
148
148
149 def listkeys(self, namespace):
149 def listkeys(self, namespace):
150 return self._repo.listkeys(namespace)
150 return self._repo.listkeys(namespace)
151
151
152 def debugwireargs(self, one, two, three=None, four=None, five=None):
152 def debugwireargs(self, one, two, three=None, four=None, five=None):
153 '''used to test argument passing over the wire'''
153 '''used to test argument passing over the wire'''
154 return "%s %s %s %s %s" % (one, two, three, four, five)
154 return "%s %s %s %s %s" % (one, two, three, four, five)
155
155
156 class locallegacypeer(localpeer):
156 class locallegacypeer(localpeer):
157 '''peer extension which implements legacy methods too; used for tests with
157 '''peer extension which implements legacy methods too; used for tests with
158 restricted capabilities'''
158 restricted capabilities'''
159
159
160 def __init__(self, repo):
160 def __init__(self, repo):
161 localpeer.__init__(self, repo, caps=legacycaps)
161 localpeer.__init__(self, repo, caps=legacycaps)
162
162
163 def branches(self, nodes):
163 def branches(self, nodes):
164 return self._repo.branches(nodes)
164 return self._repo.branches(nodes)
165
165
166 def between(self, pairs):
166 def between(self, pairs):
167 return self._repo.between(pairs)
167 return self._repo.between(pairs)
168
168
169 def changegroup(self, basenodes, source):
169 def changegroup(self, basenodes, source):
170 return changegroup.changegroup(self._repo, basenodes, source)
170 return changegroup.changegroup(self._repo, basenodes, source)
171
171
172 def changegroupsubset(self, bases, heads, source):
172 def changegroupsubset(self, bases, heads, source):
173 return changegroup.changegroupsubset(self._repo, bases, heads, source)
173 return changegroup.changegroupsubset(self._repo, bases, heads, source)
174
174
175 class localrepository(object):
175 class localrepository(object):
176
176
177 supportedformats = set(('revlogv1', 'generaldelta'))
177 supportedformats = set(('revlogv1', 'generaldelta'))
178 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
178 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
179 'dotencode'))
179 'dotencode'))
180 openerreqs = set(('revlogv1', 'generaldelta'))
180 openerreqs = set(('revlogv1', 'generaldelta'))
181 requirements = ['revlogv1']
181 requirements = ['revlogv1']
182 filtername = None
182 filtername = None
183
183
184 # a list of (ui, featureset) functions.
184 # a list of (ui, featureset) functions.
185 # only functions defined in module of enabled extensions are invoked
185 # only functions defined in module of enabled extensions are invoked
186 featuresetupfuncs = set()
186 featuresetupfuncs = set()
187
187
188 def _baserequirements(self, create):
188 def _baserequirements(self, create):
189 return self.requirements[:]
189 return self.requirements[:]
190
190
191 def __init__(self, baseui, path=None, create=False):
191 def __init__(self, baseui, path=None, create=False):
192 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
192 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
193 self.wopener = self.wvfs
193 self.wopener = self.wvfs
194 self.root = self.wvfs.base
194 self.root = self.wvfs.base
195 self.path = self.wvfs.join(".hg")
195 self.path = self.wvfs.join(".hg")
196 self.origroot = path
196 self.origroot = path
197 self.auditor = pathutil.pathauditor(self.root, self._checknested)
197 self.auditor = pathutil.pathauditor(self.root, self._checknested)
198 self.vfs = scmutil.vfs(self.path)
198 self.vfs = scmutil.vfs(self.path)
199 self.opener = self.vfs
199 self.opener = self.vfs
200 self.baseui = baseui
200 self.baseui = baseui
201 self.ui = baseui.copy()
201 self.ui = baseui.copy()
202 self.ui.copy = baseui.copy # prevent copying repo configuration
202 self.ui.copy = baseui.copy # prevent copying repo configuration
203 # A list of callback to shape the phase if no data were found.
203 # A list of callback to shape the phase if no data were found.
204 # Callback are in the form: func(repo, roots) --> processed root.
204 # Callback are in the form: func(repo, roots) --> processed root.
205 # This list it to be filled by extension during repo setup
205 # This list it to be filled by extension during repo setup
206 self._phasedefaults = []
206 self._phasedefaults = []
207 try:
207 try:
208 self.ui.readconfig(self.join("hgrc"), self.root)
208 self.ui.readconfig(self.join("hgrc"), self.root)
209 extensions.loadall(self.ui)
209 extensions.loadall(self.ui)
210 except IOError:
210 except IOError:
211 pass
211 pass
212
212
213 if self.featuresetupfuncs:
213 if self.featuresetupfuncs:
214 self.supported = set(self._basesupported) # use private copy
214 self.supported = set(self._basesupported) # use private copy
215 extmods = set(m.__name__ for n, m
215 extmods = set(m.__name__ for n, m
216 in extensions.extensions(self.ui))
216 in extensions.extensions(self.ui))
217 for setupfunc in self.featuresetupfuncs:
217 for setupfunc in self.featuresetupfuncs:
218 if setupfunc.__module__ in extmods:
218 if setupfunc.__module__ in extmods:
219 setupfunc(self.ui, self.supported)
219 setupfunc(self.ui, self.supported)
220 else:
220 else:
221 self.supported = self._basesupported
221 self.supported = self._basesupported
222
222
223 if not self.vfs.isdir():
223 if not self.vfs.isdir():
224 if create:
224 if create:
225 if not self.wvfs.exists():
225 if not self.wvfs.exists():
226 self.wvfs.makedirs()
226 self.wvfs.makedirs()
227 self.vfs.makedir(notindexed=True)
227 self.vfs.makedir(notindexed=True)
228 requirements = self._baserequirements(create)
228 requirements = self._baserequirements(create)
229 if self.ui.configbool('format', 'usestore', True):
229 if self.ui.configbool('format', 'usestore', True):
230 self.vfs.mkdir("store")
230 self.vfs.mkdir("store")
231 requirements.append("store")
231 requirements.append("store")
232 if self.ui.configbool('format', 'usefncache', True):
232 if self.ui.configbool('format', 'usefncache', True):
233 requirements.append("fncache")
233 requirements.append("fncache")
234 if self.ui.configbool('format', 'dotencode', True):
234 if self.ui.configbool('format', 'dotencode', True):
235 requirements.append('dotencode')
235 requirements.append('dotencode')
236 # create an invalid changelog
236 # create an invalid changelog
237 self.vfs.append(
237 self.vfs.append(
238 "00changelog.i",
238 "00changelog.i",
239 '\0\0\0\2' # represents revlogv2
239 '\0\0\0\2' # represents revlogv2
240 ' dummy changelog to prevent using the old repo layout'
240 ' dummy changelog to prevent using the old repo layout'
241 )
241 )
242 if self.ui.configbool('format', 'generaldelta', False):
242 if self.ui.configbool('format', 'generaldelta', False):
243 requirements.append("generaldelta")
243 requirements.append("generaldelta")
244 requirements = set(requirements)
244 requirements = set(requirements)
245 else:
245 else:
246 raise error.RepoError(_("repository %s not found") % path)
246 raise error.RepoError(_("repository %s not found") % path)
247 elif create:
247 elif create:
248 raise error.RepoError(_("repository %s already exists") % path)
248 raise error.RepoError(_("repository %s already exists") % path)
249 else:
249 else:
250 try:
250 try:
251 requirements = scmutil.readrequires(self.vfs, self.supported)
251 requirements = scmutil.readrequires(self.vfs, self.supported)
252 except IOError, inst:
252 except IOError, inst:
253 if inst.errno != errno.ENOENT:
253 if inst.errno != errno.ENOENT:
254 raise
254 raise
255 requirements = set()
255 requirements = set()
256
256
257 self.sharedpath = self.path
257 self.sharedpath = self.path
258 try:
258 try:
259 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
259 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
260 realpath=True)
260 realpath=True)
261 s = vfs.base
261 s = vfs.base
262 if not vfs.exists():
262 if not vfs.exists():
263 raise error.RepoError(
263 raise error.RepoError(
264 _('.hg/sharedpath points to nonexistent directory %s') % s)
264 _('.hg/sharedpath points to nonexistent directory %s') % s)
265 self.sharedpath = s
265 self.sharedpath = s
266 except IOError, inst:
266 except IOError, inst:
267 if inst.errno != errno.ENOENT:
267 if inst.errno != errno.ENOENT:
268 raise
268 raise
269
269
270 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
270 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
271 self.spath = self.store.path
271 self.spath = self.store.path
272 self.svfs = self.store.vfs
272 self.svfs = self.store.vfs
273 self.sopener = self.svfs
273 self.sopener = self.svfs
274 self.sjoin = self.store.join
274 self.sjoin = self.store.join
275 self.vfs.createmode = self.store.createmode
275 self.vfs.createmode = self.store.createmode
276 self._applyrequirements(requirements)
276 self._applyrequirements(requirements)
277 if create:
277 if create:
278 self._writerequirements()
278 self._writerequirements()
279
279
280
280
281 self._branchcaches = {}
281 self._branchcaches = {}
282 self.filterpats = {}
282 self.filterpats = {}
283 self._datafilters = {}
283 self._datafilters = {}
284 self._transref = self._lockref = self._wlockref = None
284 self._transref = self._lockref = self._wlockref = None
285
285
286 # A cache for various files under .hg/ that tracks file changes,
286 # A cache for various files under .hg/ that tracks file changes,
287 # (used by the filecache decorator)
287 # (used by the filecache decorator)
288 #
288 #
289 # Maps a property name to its util.filecacheentry
289 # Maps a property name to its util.filecacheentry
290 self._filecache = {}
290 self._filecache = {}
291
291
292 # hold sets of revision to be filtered
292 # hold sets of revision to be filtered
293 # should be cleared when something might have changed the filter value:
293 # should be cleared when something might have changed the filter value:
294 # - new changesets,
294 # - new changesets,
295 # - phase change,
295 # - phase change,
296 # - new obsolescence marker,
296 # - new obsolescence marker,
297 # - working directory parent change,
297 # - working directory parent change,
298 # - bookmark changes
298 # - bookmark changes
299 self.filteredrevcache = {}
299 self.filteredrevcache = {}
300
300
301 # generic mapping between names and nodes
301 # generic mapping between names and nodes
302 self.names = namespaces.namespaces(self)
302 self.names = namespaces.namespaces()
303
303
304 def close(self):
304 def close(self):
305 pass
305 pass
306
306
307 def _restrictcapabilities(self, caps):
307 def _restrictcapabilities(self, caps):
308 # bundle2 is not ready for prime time, drop it unless explicitly
308 # bundle2 is not ready for prime time, drop it unless explicitly
309 # required by the tests (or some brave tester)
309 # required by the tests (or some brave tester)
310 if self.ui.configbool('experimental', 'bundle2-exp', False):
310 if self.ui.configbool('experimental', 'bundle2-exp', False):
311 caps = set(caps)
311 caps = set(caps)
312 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
312 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
313 caps.add('bundle2-exp=' + urllib.quote(capsblob))
313 caps.add('bundle2-exp=' + urllib.quote(capsblob))
314 return caps
314 return caps
315
315
316 def _applyrequirements(self, requirements):
316 def _applyrequirements(self, requirements):
317 self.requirements = requirements
317 self.requirements = requirements
318 self.sopener.options = dict((r, 1) for r in requirements
318 self.sopener.options = dict((r, 1) for r in requirements
319 if r in self.openerreqs)
319 if r in self.openerreqs)
320 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
320 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
321 if chunkcachesize is not None:
321 if chunkcachesize is not None:
322 self.sopener.options['chunkcachesize'] = chunkcachesize
322 self.sopener.options['chunkcachesize'] = chunkcachesize
323 maxchainlen = self.ui.configint('format', 'maxchainlen')
323 maxchainlen = self.ui.configint('format', 'maxchainlen')
324 if maxchainlen is not None:
324 if maxchainlen is not None:
325 self.sopener.options['maxchainlen'] = maxchainlen
325 self.sopener.options['maxchainlen'] = maxchainlen
326
326
327 def _writerequirements(self):
327 def _writerequirements(self):
328 reqfile = self.opener("requires", "w")
328 reqfile = self.opener("requires", "w")
329 for r in sorted(self.requirements):
329 for r in sorted(self.requirements):
330 reqfile.write("%s\n" % r)
330 reqfile.write("%s\n" % r)
331 reqfile.close()
331 reqfile.close()
332
332
333 def _checknested(self, path):
333 def _checknested(self, path):
334 """Determine if path is a legal nested repository."""
334 """Determine if path is a legal nested repository."""
335 if not path.startswith(self.root):
335 if not path.startswith(self.root):
336 return False
336 return False
337 subpath = path[len(self.root) + 1:]
337 subpath = path[len(self.root) + 1:]
338 normsubpath = util.pconvert(subpath)
338 normsubpath = util.pconvert(subpath)
339
339
340 # XXX: Checking against the current working copy is wrong in
340 # XXX: Checking against the current working copy is wrong in
341 # the sense that it can reject things like
341 # the sense that it can reject things like
342 #
342 #
343 # $ hg cat -r 10 sub/x.txt
343 # $ hg cat -r 10 sub/x.txt
344 #
344 #
345 # if sub/ is no longer a subrepository in the working copy
345 # if sub/ is no longer a subrepository in the working copy
346 # parent revision.
346 # parent revision.
347 #
347 #
348 # However, it can of course also allow things that would have
348 # However, it can of course also allow things that would have
349 # been rejected before, such as the above cat command if sub/
349 # been rejected before, such as the above cat command if sub/
350 # is a subrepository now, but was a normal directory before.
350 # is a subrepository now, but was a normal directory before.
351 # The old path auditor would have rejected by mistake since it
351 # The old path auditor would have rejected by mistake since it
352 # panics when it sees sub/.hg/.
352 # panics when it sees sub/.hg/.
353 #
353 #
354 # All in all, checking against the working copy seems sensible
354 # All in all, checking against the working copy seems sensible
355 # since we want to prevent access to nested repositories on
355 # since we want to prevent access to nested repositories on
356 # the filesystem *now*.
356 # the filesystem *now*.
357 ctx = self[None]
357 ctx = self[None]
358 parts = util.splitpath(subpath)
358 parts = util.splitpath(subpath)
359 while parts:
359 while parts:
360 prefix = '/'.join(parts)
360 prefix = '/'.join(parts)
361 if prefix in ctx.substate:
361 if prefix in ctx.substate:
362 if prefix == normsubpath:
362 if prefix == normsubpath:
363 return True
363 return True
364 else:
364 else:
365 sub = ctx.sub(prefix)
365 sub = ctx.sub(prefix)
366 return sub.checknested(subpath[len(prefix) + 1:])
366 return sub.checknested(subpath[len(prefix) + 1:])
367 else:
367 else:
368 parts.pop()
368 parts.pop()
369 return False
369 return False
370
370
371 def peer(self):
371 def peer(self):
372 return localpeer(self) # not cached to avoid reference cycle
372 return localpeer(self) # not cached to avoid reference cycle
373
373
374 def unfiltered(self):
374 def unfiltered(self):
375 """Return unfiltered version of the repository
375 """Return unfiltered version of the repository
376
376
377 Intended to be overwritten by filtered repo."""
377 Intended to be overwritten by filtered repo."""
378 return self
378 return self
379
379
380 def filtered(self, name):
380 def filtered(self, name):
381 """Return a filtered version of a repository"""
381 """Return a filtered version of a repository"""
382 # build a new class with the mixin and the current class
382 # build a new class with the mixin and the current class
383 # (possibly subclass of the repo)
383 # (possibly subclass of the repo)
384 class proxycls(repoview.repoview, self.unfiltered().__class__):
384 class proxycls(repoview.repoview, self.unfiltered().__class__):
385 pass
385 pass
386 return proxycls(self, name)
386 return proxycls(self, name)
387
387
388 @repofilecache('bookmarks')
388 @repofilecache('bookmarks')
389 def _bookmarks(self):
389 def _bookmarks(self):
390 return bookmarks.bmstore(self)
390 return bookmarks.bmstore(self)
391
391
392 @repofilecache('bookmarks.current')
392 @repofilecache('bookmarks.current')
393 def _bookmarkcurrent(self):
393 def _bookmarkcurrent(self):
394 return bookmarks.readcurrent(self)
394 return bookmarks.readcurrent(self)
395
395
396 def bookmarkheads(self, bookmark):
396 def bookmarkheads(self, bookmark):
397 name = bookmark.split('@', 1)[0]
397 name = bookmark.split('@', 1)[0]
398 heads = []
398 heads = []
399 for mark, n in self._bookmarks.iteritems():
399 for mark, n in self._bookmarks.iteritems():
400 if mark.split('@', 1)[0] == name:
400 if mark.split('@', 1)[0] == name:
401 heads.append(n)
401 heads.append(n)
402 return heads
402 return heads
403
403
404 @storecache('phaseroots')
404 @storecache('phaseroots')
405 def _phasecache(self):
405 def _phasecache(self):
406 return phases.phasecache(self, self._phasedefaults)
406 return phases.phasecache(self, self._phasedefaults)
407
407
408 @storecache('obsstore')
408 @storecache('obsstore')
409 def obsstore(self):
409 def obsstore(self):
410 # read default format for new obsstore.
410 # read default format for new obsstore.
411 defaultformat = self.ui.configint('format', 'obsstore-version', None)
411 defaultformat = self.ui.configint('format', 'obsstore-version', None)
412 # rely on obsstore class default when possible.
412 # rely on obsstore class default when possible.
413 kwargs = {}
413 kwargs = {}
414 if defaultformat is not None:
414 if defaultformat is not None:
415 kwargs['defaultformat'] = defaultformat
415 kwargs['defaultformat'] = defaultformat
416 readonly = not obsolete.isenabled(self, obsolete.createmarkersopt)
416 readonly = not obsolete.isenabled(self, obsolete.createmarkersopt)
417 store = obsolete.obsstore(self.sopener, readonly=readonly,
417 store = obsolete.obsstore(self.sopener, readonly=readonly,
418 **kwargs)
418 **kwargs)
419 if store and readonly:
419 if store and readonly:
420 # message is rare enough to not be translated
420 # message is rare enough to not be translated
421 msg = 'obsolete feature not enabled but %i markers found!\n'
421 msg = 'obsolete feature not enabled but %i markers found!\n'
422 self.ui.warn(msg % len(list(store)))
422 self.ui.warn(msg % len(list(store)))
423 return store
423 return store
424
424
425 @storecache('00changelog.i')
425 @storecache('00changelog.i')
426 def changelog(self):
426 def changelog(self):
427 c = changelog.changelog(self.sopener)
427 c = changelog.changelog(self.sopener)
428 if 'HG_PENDING' in os.environ:
428 if 'HG_PENDING' in os.environ:
429 p = os.environ['HG_PENDING']
429 p = os.environ['HG_PENDING']
430 if p.startswith(self.root):
430 if p.startswith(self.root):
431 c.readpending('00changelog.i.a')
431 c.readpending('00changelog.i.a')
432 return c
432 return c
433
433
434 @storecache('00manifest.i')
434 @storecache('00manifest.i')
435 def manifest(self):
435 def manifest(self):
436 return manifest.manifest(self.sopener)
436 return manifest.manifest(self.sopener)
437
437
438 @repofilecache('dirstate')
438 @repofilecache('dirstate')
439 def dirstate(self):
439 def dirstate(self):
440 warned = [0]
440 warned = [0]
441 def validate(node):
441 def validate(node):
442 try:
442 try:
443 self.changelog.rev(node)
443 self.changelog.rev(node)
444 return node
444 return node
445 except error.LookupError:
445 except error.LookupError:
446 if not warned[0]:
446 if not warned[0]:
447 warned[0] = True
447 warned[0] = True
448 self.ui.warn(_("warning: ignoring unknown"
448 self.ui.warn(_("warning: ignoring unknown"
449 " working parent %s!\n") % short(node))
449 " working parent %s!\n") % short(node))
450 return nullid
450 return nullid
451
451
452 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
452 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
453
453
454 def __getitem__(self, changeid):
454 def __getitem__(self, changeid):
455 if changeid is None:
455 if changeid is None:
456 return context.workingctx(self)
456 return context.workingctx(self)
457 return context.changectx(self, changeid)
457 return context.changectx(self, changeid)
458
458
459 def __contains__(self, changeid):
459 def __contains__(self, changeid):
460 try:
460 try:
461 return bool(self.lookup(changeid))
461 return bool(self.lookup(changeid))
462 except error.RepoLookupError:
462 except error.RepoLookupError:
463 return False
463 return False
464
464
465 def __nonzero__(self):
465 def __nonzero__(self):
466 return True
466 return True
467
467
468 def __len__(self):
468 def __len__(self):
469 return len(self.changelog)
469 return len(self.changelog)
470
470
471 def __iter__(self):
471 def __iter__(self):
472 return iter(self.changelog)
472 return iter(self.changelog)
473
473
474 def revs(self, expr, *args):
474 def revs(self, expr, *args):
475 '''Return a list of revisions matching the given revset'''
475 '''Return a list of revisions matching the given revset'''
476 expr = revset.formatspec(expr, *args)
476 expr = revset.formatspec(expr, *args)
477 m = revset.match(None, expr)
477 m = revset.match(None, expr)
478 return m(self, revset.spanset(self))
478 return m(self, revset.spanset(self))
479
479
480 def set(self, expr, *args):
480 def set(self, expr, *args):
481 '''
481 '''
482 Yield a context for each matching revision, after doing arg
482 Yield a context for each matching revision, after doing arg
483 replacement via revset.formatspec
483 replacement via revset.formatspec
484 '''
484 '''
485 for r in self.revs(expr, *args):
485 for r in self.revs(expr, *args):
486 yield self[r]
486 yield self[r]
487
487
488 def url(self):
488 def url(self):
489 return 'file:' + self.root
489 return 'file:' + self.root
490
490
491 def hook(self, name, throw=False, **args):
491 def hook(self, name, throw=False, **args):
492 """Call a hook, passing this repo instance.
492 """Call a hook, passing this repo instance.
493
493
494 This a convenience method to aid invoking hooks. Extensions likely
494 This a convenience method to aid invoking hooks. Extensions likely
495 won't call this unless they have registered a custom hook or are
495 won't call this unless they have registered a custom hook or are
496 replacing code that is expected to call a hook.
496 replacing code that is expected to call a hook.
497 """
497 """
498 return hook.hook(self.ui, self, name, throw, **args)
498 return hook.hook(self.ui, self, name, throw, **args)
499
499
500 @unfilteredmethod
500 @unfilteredmethod
501 def _tag(self, names, node, message, local, user, date, extra={},
501 def _tag(self, names, node, message, local, user, date, extra={},
502 editor=False):
502 editor=False):
503 if isinstance(names, str):
503 if isinstance(names, str):
504 names = (names,)
504 names = (names,)
505
505
506 branches = self.branchmap()
506 branches = self.branchmap()
507 for name in names:
507 for name in names:
508 self.hook('pretag', throw=True, node=hex(node), tag=name,
508 self.hook('pretag', throw=True, node=hex(node), tag=name,
509 local=local)
509 local=local)
510 if name in branches:
510 if name in branches:
511 self.ui.warn(_("warning: tag %s conflicts with existing"
511 self.ui.warn(_("warning: tag %s conflicts with existing"
512 " branch name\n") % name)
512 " branch name\n") % name)
513
513
514 def writetags(fp, names, munge, prevtags):
514 def writetags(fp, names, munge, prevtags):
515 fp.seek(0, 2)
515 fp.seek(0, 2)
516 if prevtags and prevtags[-1] != '\n':
516 if prevtags and prevtags[-1] != '\n':
517 fp.write('\n')
517 fp.write('\n')
518 for name in names:
518 for name in names:
519 m = munge and munge(name) or name
519 m = munge and munge(name) or name
520 if (self._tagscache.tagtypes and
520 if (self._tagscache.tagtypes and
521 name in self._tagscache.tagtypes):
521 name in self._tagscache.tagtypes):
522 old = self.tags().get(name, nullid)
522 old = self.tags().get(name, nullid)
523 fp.write('%s %s\n' % (hex(old), m))
523 fp.write('%s %s\n' % (hex(old), m))
524 fp.write('%s %s\n' % (hex(node), m))
524 fp.write('%s %s\n' % (hex(node), m))
525 fp.close()
525 fp.close()
526
526
527 prevtags = ''
527 prevtags = ''
528 if local:
528 if local:
529 try:
529 try:
530 fp = self.opener('localtags', 'r+')
530 fp = self.opener('localtags', 'r+')
531 except IOError:
531 except IOError:
532 fp = self.opener('localtags', 'a')
532 fp = self.opener('localtags', 'a')
533 else:
533 else:
534 prevtags = fp.read()
534 prevtags = fp.read()
535
535
536 # local tags are stored in the current charset
536 # local tags are stored in the current charset
537 writetags(fp, names, None, prevtags)
537 writetags(fp, names, None, prevtags)
538 for name in names:
538 for name in names:
539 self.hook('tag', node=hex(node), tag=name, local=local)
539 self.hook('tag', node=hex(node), tag=name, local=local)
540 return
540 return
541
541
542 try:
542 try:
543 fp = self.wfile('.hgtags', 'rb+')
543 fp = self.wfile('.hgtags', 'rb+')
544 except IOError, e:
544 except IOError, e:
545 if e.errno != errno.ENOENT:
545 if e.errno != errno.ENOENT:
546 raise
546 raise
547 fp = self.wfile('.hgtags', 'ab')
547 fp = self.wfile('.hgtags', 'ab')
548 else:
548 else:
549 prevtags = fp.read()
549 prevtags = fp.read()
550
550
551 # committed tags are stored in UTF-8
551 # committed tags are stored in UTF-8
552 writetags(fp, names, encoding.fromlocal, prevtags)
552 writetags(fp, names, encoding.fromlocal, prevtags)
553
553
554 fp.close()
554 fp.close()
555
555
556 self.invalidatecaches()
556 self.invalidatecaches()
557
557
558 if '.hgtags' not in self.dirstate:
558 if '.hgtags' not in self.dirstate:
559 self[None].add(['.hgtags'])
559 self[None].add(['.hgtags'])
560
560
561 m = matchmod.exact(self.root, '', ['.hgtags'])
561 m = matchmod.exact(self.root, '', ['.hgtags'])
562 tagnode = self.commit(message, user, date, extra=extra, match=m,
562 tagnode = self.commit(message, user, date, extra=extra, match=m,
563 editor=editor)
563 editor=editor)
564
564
565 for name in names:
565 for name in names:
566 self.hook('tag', node=hex(node), tag=name, local=local)
566 self.hook('tag', node=hex(node), tag=name, local=local)
567
567
568 return tagnode
568 return tagnode
569
569
570 def tag(self, names, node, message, local, user, date, editor=False):
570 def tag(self, names, node, message, local, user, date, editor=False):
571 '''tag a revision with one or more symbolic names.
571 '''tag a revision with one or more symbolic names.
572
572
573 names is a list of strings or, when adding a single tag, names may be a
573 names is a list of strings or, when adding a single tag, names may be a
574 string.
574 string.
575
575
576 if local is True, the tags are stored in a per-repository file.
576 if local is True, the tags are stored in a per-repository file.
577 otherwise, they are stored in the .hgtags file, and a new
577 otherwise, they are stored in the .hgtags file, and a new
578 changeset is committed with the change.
578 changeset is committed with the change.
579
579
580 keyword arguments:
580 keyword arguments:
581
581
582 local: whether to store tags in non-version-controlled file
582 local: whether to store tags in non-version-controlled file
583 (default False)
583 (default False)
584
584
585 message: commit message to use if committing
585 message: commit message to use if committing
586
586
587 user: name of user to use if committing
587 user: name of user to use if committing
588
588
589 date: date tuple to use if committing'''
589 date: date tuple to use if committing'''
590
590
591 if not local:
591 if not local:
592 m = matchmod.exact(self.root, '', ['.hgtags'])
592 m = matchmod.exact(self.root, '', ['.hgtags'])
593 if util.any(self.status(match=m, unknown=True, ignored=True)):
593 if util.any(self.status(match=m, unknown=True, ignored=True)):
594 raise util.Abort(_('working copy of .hgtags is changed'),
594 raise util.Abort(_('working copy of .hgtags is changed'),
595 hint=_('please commit .hgtags manually'))
595 hint=_('please commit .hgtags manually'))
596
596
597 self.tags() # instantiate the cache
597 self.tags() # instantiate the cache
598 self._tag(names, node, message, local, user, date, editor=editor)
598 self._tag(names, node, message, local, user, date, editor=editor)
599
599
600 @filteredpropertycache
600 @filteredpropertycache
601 def _tagscache(self):
601 def _tagscache(self):
602 '''Returns a tagscache object that contains various tags related
602 '''Returns a tagscache object that contains various tags related
603 caches.'''
603 caches.'''
604
604
605 # This simplifies its cache management by having one decorated
605 # This simplifies its cache management by having one decorated
606 # function (this one) and the rest simply fetch things from it.
606 # function (this one) and the rest simply fetch things from it.
607 class tagscache(object):
607 class tagscache(object):
608 def __init__(self):
608 def __init__(self):
609 # These two define the set of tags for this repository. tags
609 # These two define the set of tags for this repository. tags
610 # maps tag name to node; tagtypes maps tag name to 'global' or
610 # maps tag name to node; tagtypes maps tag name to 'global' or
611 # 'local'. (Global tags are defined by .hgtags across all
611 # 'local'. (Global tags are defined by .hgtags across all
612 # heads, and local tags are defined in .hg/localtags.)
612 # heads, and local tags are defined in .hg/localtags.)
613 # They constitute the in-memory cache of tags.
613 # They constitute the in-memory cache of tags.
614 self.tags = self.tagtypes = None
614 self.tags = self.tagtypes = None
615
615
616 self.nodetagscache = self.tagslist = None
616 self.nodetagscache = self.tagslist = None
617
617
618 cache = tagscache()
618 cache = tagscache()
619 cache.tags, cache.tagtypes = self._findtags()
619 cache.tags, cache.tagtypes = self._findtags()
620
620
621 return cache
621 return cache
622
622
623 def tags(self):
623 def tags(self):
624 '''return a mapping of tag to node'''
624 '''return a mapping of tag to node'''
625 t = {}
625 t = {}
626 if self.changelog.filteredrevs:
626 if self.changelog.filteredrevs:
627 tags, tt = self._findtags()
627 tags, tt = self._findtags()
628 else:
628 else:
629 tags = self._tagscache.tags
629 tags = self._tagscache.tags
630 for k, v in tags.iteritems():
630 for k, v in tags.iteritems():
631 try:
631 try:
632 # ignore tags to unknown nodes
632 # ignore tags to unknown nodes
633 self.changelog.rev(v)
633 self.changelog.rev(v)
634 t[k] = v
634 t[k] = v
635 except (error.LookupError, ValueError):
635 except (error.LookupError, ValueError):
636 pass
636 pass
637 return t
637 return t
638
638
639 def _findtags(self):
639 def _findtags(self):
640 '''Do the hard work of finding tags. Return a pair of dicts
640 '''Do the hard work of finding tags. Return a pair of dicts
641 (tags, tagtypes) where tags maps tag name to node, and tagtypes
641 (tags, tagtypes) where tags maps tag name to node, and tagtypes
642 maps tag name to a string like \'global\' or \'local\'.
642 maps tag name to a string like \'global\' or \'local\'.
643 Subclasses or extensions are free to add their own tags, but
643 Subclasses or extensions are free to add their own tags, but
644 should be aware that the returned dicts will be retained for the
644 should be aware that the returned dicts will be retained for the
645 duration of the localrepo object.'''
645 duration of the localrepo object.'''
646
646
647 # XXX what tagtype should subclasses/extensions use? Currently
647 # XXX what tagtype should subclasses/extensions use? Currently
648 # mq and bookmarks add tags, but do not set the tagtype at all.
648 # mq and bookmarks add tags, but do not set the tagtype at all.
649 # Should each extension invent its own tag type? Should there
649 # Should each extension invent its own tag type? Should there
650 # be one tagtype for all such "virtual" tags? Or is the status
650 # be one tagtype for all such "virtual" tags? Or is the status
651 # quo fine?
651 # quo fine?
652
652
653 alltags = {} # map tag name to (node, hist)
653 alltags = {} # map tag name to (node, hist)
654 tagtypes = {}
654 tagtypes = {}
655
655
656 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
656 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
657 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
657 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
658
658
659 # Build the return dicts. Have to re-encode tag names because
659 # Build the return dicts. Have to re-encode tag names because
660 # the tags module always uses UTF-8 (in order not to lose info
660 # the tags module always uses UTF-8 (in order not to lose info
661 # writing to the cache), but the rest of Mercurial wants them in
661 # writing to the cache), but the rest of Mercurial wants them in
662 # local encoding.
662 # local encoding.
663 tags = {}
663 tags = {}
664 for (name, (node, hist)) in alltags.iteritems():
664 for (name, (node, hist)) in alltags.iteritems():
665 if node != nullid:
665 if node != nullid:
666 tags[encoding.tolocal(name)] = node
666 tags[encoding.tolocal(name)] = node
667 tags['tip'] = self.changelog.tip()
667 tags['tip'] = self.changelog.tip()
668 tagtypes = dict([(encoding.tolocal(name), value)
668 tagtypes = dict([(encoding.tolocal(name), value)
669 for (name, value) in tagtypes.iteritems()])
669 for (name, value) in tagtypes.iteritems()])
670 return (tags, tagtypes)
670 return (tags, tagtypes)
671
671
672 def tagtype(self, tagname):
672 def tagtype(self, tagname):
673 '''
673 '''
674 return the type of the given tag. result can be:
674 return the type of the given tag. result can be:
675
675
676 'local' : a local tag
676 'local' : a local tag
677 'global' : a global tag
677 'global' : a global tag
678 None : tag does not exist
678 None : tag does not exist
679 '''
679 '''
680
680
681 return self._tagscache.tagtypes.get(tagname)
681 return self._tagscache.tagtypes.get(tagname)
682
682
683 def tagslist(self):
683 def tagslist(self):
684 '''return a list of tags ordered by revision'''
684 '''return a list of tags ordered by revision'''
685 if not self._tagscache.tagslist:
685 if not self._tagscache.tagslist:
686 l = []
686 l = []
687 for t, n in self.tags().iteritems():
687 for t, n in self.tags().iteritems():
688 l.append((self.changelog.rev(n), t, n))
688 l.append((self.changelog.rev(n), t, n))
689 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
689 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
690
690
691 return self._tagscache.tagslist
691 return self._tagscache.tagslist
692
692
693 def nodetags(self, node):
693 def nodetags(self, node):
694 '''return the tags associated with a node'''
694 '''return the tags associated with a node'''
695 if not self._tagscache.nodetagscache:
695 if not self._tagscache.nodetagscache:
696 nodetagscache = {}
696 nodetagscache = {}
697 for t, n in self._tagscache.tags.iteritems():
697 for t, n in self._tagscache.tags.iteritems():
698 nodetagscache.setdefault(n, []).append(t)
698 nodetagscache.setdefault(n, []).append(t)
699 for tags in nodetagscache.itervalues():
699 for tags in nodetagscache.itervalues():
700 tags.sort()
700 tags.sort()
701 self._tagscache.nodetagscache = nodetagscache
701 self._tagscache.nodetagscache = nodetagscache
702 return self._tagscache.nodetagscache.get(node, [])
702 return self._tagscache.nodetagscache.get(node, [])
703
703
704 def nodebookmarks(self, node):
704 def nodebookmarks(self, node):
705 marks = []
705 marks = []
706 for bookmark, n in self._bookmarks.iteritems():
706 for bookmark, n in self._bookmarks.iteritems():
707 if n == node:
707 if n == node:
708 marks.append(bookmark)
708 marks.append(bookmark)
709 return sorted(marks)
709 return sorted(marks)
710
710
711 def branchmap(self):
711 def branchmap(self):
712 '''returns a dictionary {branch: [branchheads]} with branchheads
712 '''returns a dictionary {branch: [branchheads]} with branchheads
713 ordered by increasing revision number'''
713 ordered by increasing revision number'''
714 branchmap.updatecache(self)
714 branchmap.updatecache(self)
715 return self._branchcaches[self.filtername]
715 return self._branchcaches[self.filtername]
716
716
717 def branchtip(self, branch):
717 def branchtip(self, branch):
718 '''return the tip node for a given branch'''
718 '''return the tip node for a given branch'''
719 try:
719 try:
720 return self.branchmap().branchtip(branch)
720 return self.branchmap().branchtip(branch)
721 except KeyError:
721 except KeyError:
722 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
722 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
723
723
724 def lookup(self, key):
724 def lookup(self, key):
725 return self[key].node()
725 return self[key].node()
726
726
727 def lookupbranch(self, key, remote=None):
727 def lookupbranch(self, key, remote=None):
728 repo = remote or self
728 repo = remote or self
729 if key in repo.branchmap():
729 if key in repo.branchmap():
730 return key
730 return key
731
731
732 repo = (remote and remote.local()) and remote or self
732 repo = (remote and remote.local()) and remote or self
733 return repo[key].branch()
733 return repo[key].branch()
734
734
735 def known(self, nodes):
735 def known(self, nodes):
736 nm = self.changelog.nodemap
736 nm = self.changelog.nodemap
737 pc = self._phasecache
737 pc = self._phasecache
738 result = []
738 result = []
739 for n in nodes:
739 for n in nodes:
740 r = nm.get(n)
740 r = nm.get(n)
741 resp = not (r is None or pc.phase(self, r) >= phases.secret)
741 resp = not (r is None or pc.phase(self, r) >= phases.secret)
742 result.append(resp)
742 result.append(resp)
743 return result
743 return result
744
744
745 def local(self):
745 def local(self):
746 return self
746 return self
747
747
748 def cancopy(self):
748 def cancopy(self):
749 # so statichttprepo's override of local() works
749 # so statichttprepo's override of local() works
750 if not self.local():
750 if not self.local():
751 return False
751 return False
752 if not self.ui.configbool('phases', 'publish', True):
752 if not self.ui.configbool('phases', 'publish', True):
753 return True
753 return True
754 # if publishing we can't copy if there is filtered content
754 # if publishing we can't copy if there is filtered content
755 return not self.filtered('visible').changelog.filteredrevs
755 return not self.filtered('visible').changelog.filteredrevs
756
756
757 def join(self, f, *insidef):
757 def join(self, f, *insidef):
758 return os.path.join(self.path, f, *insidef)
758 return os.path.join(self.path, f, *insidef)
759
759
760 def wjoin(self, f, *insidef):
760 def wjoin(self, f, *insidef):
761 return os.path.join(self.root, f, *insidef)
761 return os.path.join(self.root, f, *insidef)
762
762
763 def file(self, f):
763 def file(self, f):
764 if f[0] == '/':
764 if f[0] == '/':
765 f = f[1:]
765 f = f[1:]
766 return filelog.filelog(self.sopener, f)
766 return filelog.filelog(self.sopener, f)
767
767
768 def changectx(self, changeid):
768 def changectx(self, changeid):
769 return self[changeid]
769 return self[changeid]
770
770
771 def parents(self, changeid=None):
771 def parents(self, changeid=None):
772 '''get list of changectxs for parents of changeid'''
772 '''get list of changectxs for parents of changeid'''
773 return self[changeid].parents()
773 return self[changeid].parents()
774
774
775 def setparents(self, p1, p2=nullid):
775 def setparents(self, p1, p2=nullid):
776 self.dirstate.beginparentchange()
776 self.dirstate.beginparentchange()
777 copies = self.dirstate.setparents(p1, p2)
777 copies = self.dirstate.setparents(p1, p2)
778 pctx = self[p1]
778 pctx = self[p1]
779 if copies:
779 if copies:
780 # Adjust copy records, the dirstate cannot do it, it
780 # Adjust copy records, the dirstate cannot do it, it
781 # requires access to parents manifests. Preserve them
781 # requires access to parents manifests. Preserve them
782 # only for entries added to first parent.
782 # only for entries added to first parent.
783 for f in copies:
783 for f in copies:
784 if f not in pctx and copies[f] in pctx:
784 if f not in pctx and copies[f] in pctx:
785 self.dirstate.copy(copies[f], f)
785 self.dirstate.copy(copies[f], f)
786 if p2 == nullid:
786 if p2 == nullid:
787 for f, s in sorted(self.dirstate.copies().items()):
787 for f, s in sorted(self.dirstate.copies().items()):
788 if f not in pctx and s not in pctx:
788 if f not in pctx and s not in pctx:
789 self.dirstate.copy(None, f)
789 self.dirstate.copy(None, f)
790 self.dirstate.endparentchange()
790 self.dirstate.endparentchange()
791
791
792 def filectx(self, path, changeid=None, fileid=None):
792 def filectx(self, path, changeid=None, fileid=None):
793 """changeid can be a changeset revision, node, or tag.
793 """changeid can be a changeset revision, node, or tag.
794 fileid can be a file revision or node."""
794 fileid can be a file revision or node."""
795 return context.filectx(self, path, changeid, fileid)
795 return context.filectx(self, path, changeid, fileid)
796
796
797 def getcwd(self):
797 def getcwd(self):
798 return self.dirstate.getcwd()
798 return self.dirstate.getcwd()
799
799
800 def pathto(self, f, cwd=None):
800 def pathto(self, f, cwd=None):
801 return self.dirstate.pathto(f, cwd)
801 return self.dirstate.pathto(f, cwd)
802
802
803 def wfile(self, f, mode='r'):
803 def wfile(self, f, mode='r'):
804 return self.wopener(f, mode)
804 return self.wopener(f, mode)
805
805
806 def _link(self, f):
806 def _link(self, f):
807 return self.wvfs.islink(f)
807 return self.wvfs.islink(f)
808
808
809 def _loadfilter(self, filter):
809 def _loadfilter(self, filter):
810 if filter not in self.filterpats:
810 if filter not in self.filterpats:
811 l = []
811 l = []
812 for pat, cmd in self.ui.configitems(filter):
812 for pat, cmd in self.ui.configitems(filter):
813 if cmd == '!':
813 if cmd == '!':
814 continue
814 continue
815 mf = matchmod.match(self.root, '', [pat])
815 mf = matchmod.match(self.root, '', [pat])
816 fn = None
816 fn = None
817 params = cmd
817 params = cmd
818 for name, filterfn in self._datafilters.iteritems():
818 for name, filterfn in self._datafilters.iteritems():
819 if cmd.startswith(name):
819 if cmd.startswith(name):
820 fn = filterfn
820 fn = filterfn
821 params = cmd[len(name):].lstrip()
821 params = cmd[len(name):].lstrip()
822 break
822 break
823 if not fn:
823 if not fn:
824 fn = lambda s, c, **kwargs: util.filter(s, c)
824 fn = lambda s, c, **kwargs: util.filter(s, c)
825 # Wrap old filters not supporting keyword arguments
825 # Wrap old filters not supporting keyword arguments
826 if not inspect.getargspec(fn)[2]:
826 if not inspect.getargspec(fn)[2]:
827 oldfn = fn
827 oldfn = fn
828 fn = lambda s, c, **kwargs: oldfn(s, c)
828 fn = lambda s, c, **kwargs: oldfn(s, c)
829 l.append((mf, fn, params))
829 l.append((mf, fn, params))
830 self.filterpats[filter] = l
830 self.filterpats[filter] = l
831 return self.filterpats[filter]
831 return self.filterpats[filter]
832
832
833 def _filter(self, filterpats, filename, data):
833 def _filter(self, filterpats, filename, data):
834 for mf, fn, cmd in filterpats:
834 for mf, fn, cmd in filterpats:
835 if mf(filename):
835 if mf(filename):
836 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
836 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
837 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
837 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
838 break
838 break
839
839
840 return data
840 return data
841
841
842 @unfilteredpropertycache
842 @unfilteredpropertycache
843 def _encodefilterpats(self):
843 def _encodefilterpats(self):
844 return self._loadfilter('encode')
844 return self._loadfilter('encode')
845
845
846 @unfilteredpropertycache
846 @unfilteredpropertycache
847 def _decodefilterpats(self):
847 def _decodefilterpats(self):
848 return self._loadfilter('decode')
848 return self._loadfilter('decode')
849
849
850 def adddatafilter(self, name, filter):
850 def adddatafilter(self, name, filter):
851 self._datafilters[name] = filter
851 self._datafilters[name] = filter
852
852
853 def wread(self, filename):
853 def wread(self, filename):
854 if self._link(filename):
854 if self._link(filename):
855 data = self.wvfs.readlink(filename)
855 data = self.wvfs.readlink(filename)
856 else:
856 else:
857 data = self.wopener.read(filename)
857 data = self.wopener.read(filename)
858 return self._filter(self._encodefilterpats, filename, data)
858 return self._filter(self._encodefilterpats, filename, data)
859
859
860 def wwrite(self, filename, data, flags):
860 def wwrite(self, filename, data, flags):
861 data = self._filter(self._decodefilterpats, filename, data)
861 data = self._filter(self._decodefilterpats, filename, data)
862 if 'l' in flags:
862 if 'l' in flags:
863 self.wopener.symlink(data, filename)
863 self.wopener.symlink(data, filename)
864 else:
864 else:
865 self.wopener.write(filename, data)
865 self.wopener.write(filename, data)
866 if 'x' in flags:
866 if 'x' in flags:
867 self.wvfs.setflags(filename, False, True)
867 self.wvfs.setflags(filename, False, True)
868
868
869 def wwritedata(self, filename, data):
869 def wwritedata(self, filename, data):
870 return self._filter(self._decodefilterpats, filename, data)
870 return self._filter(self._decodefilterpats, filename, data)
871
871
872 def currenttransaction(self):
872 def currenttransaction(self):
873 """return the current transaction or None if non exists"""
873 """return the current transaction or None if non exists"""
874 tr = self._transref and self._transref() or None
874 tr = self._transref and self._transref() or None
875 if tr and tr.running():
875 if tr and tr.running():
876 return tr
876 return tr
877 return None
877 return None
878
878
879 def transaction(self, desc, report=None):
879 def transaction(self, desc, report=None):
880 tr = self.currenttransaction()
880 tr = self.currenttransaction()
881 if tr is not None:
881 if tr is not None:
882 return tr.nest()
882 return tr.nest()
883
883
884 # abort here if the journal already exists
884 # abort here if the journal already exists
885 if self.svfs.exists("journal"):
885 if self.svfs.exists("journal"):
886 raise error.RepoError(
886 raise error.RepoError(
887 _("abandoned transaction found"),
887 _("abandoned transaction found"),
888 hint=_("run 'hg recover' to clean up transaction"))
888 hint=_("run 'hg recover' to clean up transaction"))
889
889
890 self._writejournal(desc)
890 self._writejournal(desc)
891 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
891 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
892 rp = report and report or self.ui.warn
892 rp = report and report or self.ui.warn
893 vfsmap = {'plain': self.opener} # root of .hg/
893 vfsmap = {'plain': self.opener} # root of .hg/
894 tr = transaction.transaction(rp, self.sopener, vfsmap,
894 tr = transaction.transaction(rp, self.sopener, vfsmap,
895 "journal",
895 "journal",
896 aftertrans(renames),
896 aftertrans(renames),
897 self.store.createmode)
897 self.store.createmode)
898 # note: writing the fncache only during finalize mean that the file is
898 # note: writing the fncache only during finalize mean that the file is
899 # outdated when running hooks. As fncache is used for streaming clone,
899 # outdated when running hooks. As fncache is used for streaming clone,
900 # this is not expected to break anything that happen during the hooks.
900 # this is not expected to break anything that happen during the hooks.
901 tr.addfinalize('flush-fncache', self.store.write)
901 tr.addfinalize('flush-fncache', self.store.write)
902 self._transref = weakref.ref(tr)
902 self._transref = weakref.ref(tr)
903 return tr
903 return tr
904
904
905 def _journalfiles(self):
905 def _journalfiles(self):
906 return ((self.svfs, 'journal'),
906 return ((self.svfs, 'journal'),
907 (self.vfs, 'journal.dirstate'),
907 (self.vfs, 'journal.dirstate'),
908 (self.vfs, 'journal.branch'),
908 (self.vfs, 'journal.branch'),
909 (self.vfs, 'journal.desc'),
909 (self.vfs, 'journal.desc'),
910 (self.vfs, 'journal.bookmarks'),
910 (self.vfs, 'journal.bookmarks'),
911 (self.svfs, 'journal.phaseroots'))
911 (self.svfs, 'journal.phaseroots'))
912
912
913 def undofiles(self):
913 def undofiles(self):
914 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
914 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
915
915
916 def _writejournal(self, desc):
916 def _writejournal(self, desc):
917 self.opener.write("journal.dirstate",
917 self.opener.write("journal.dirstate",
918 self.opener.tryread("dirstate"))
918 self.opener.tryread("dirstate"))
919 self.opener.write("journal.branch",
919 self.opener.write("journal.branch",
920 encoding.fromlocal(self.dirstate.branch()))
920 encoding.fromlocal(self.dirstate.branch()))
921 self.opener.write("journal.desc",
921 self.opener.write("journal.desc",
922 "%d\n%s\n" % (len(self), desc))
922 "%d\n%s\n" % (len(self), desc))
923 self.opener.write("journal.bookmarks",
923 self.opener.write("journal.bookmarks",
924 self.opener.tryread("bookmarks"))
924 self.opener.tryread("bookmarks"))
925 self.sopener.write("journal.phaseroots",
925 self.sopener.write("journal.phaseroots",
926 self.sopener.tryread("phaseroots"))
926 self.sopener.tryread("phaseroots"))
927
927
928 def recover(self):
928 def recover(self):
929 lock = self.lock()
929 lock = self.lock()
930 try:
930 try:
931 if self.svfs.exists("journal"):
931 if self.svfs.exists("journal"):
932 self.ui.status(_("rolling back interrupted transaction\n"))
932 self.ui.status(_("rolling back interrupted transaction\n"))
933 vfsmap = {'': self.sopener,
933 vfsmap = {'': self.sopener,
934 'plain': self.opener,}
934 'plain': self.opener,}
935 transaction.rollback(self.sopener, vfsmap, "journal",
935 transaction.rollback(self.sopener, vfsmap, "journal",
936 self.ui.warn)
936 self.ui.warn)
937 self.invalidate()
937 self.invalidate()
938 return True
938 return True
939 else:
939 else:
940 self.ui.warn(_("no interrupted transaction available\n"))
940 self.ui.warn(_("no interrupted transaction available\n"))
941 return False
941 return False
942 finally:
942 finally:
943 lock.release()
943 lock.release()
944
944
945 def rollback(self, dryrun=False, force=False):
945 def rollback(self, dryrun=False, force=False):
946 wlock = lock = None
946 wlock = lock = None
947 try:
947 try:
948 wlock = self.wlock()
948 wlock = self.wlock()
949 lock = self.lock()
949 lock = self.lock()
950 if self.svfs.exists("undo"):
950 if self.svfs.exists("undo"):
951 return self._rollback(dryrun, force)
951 return self._rollback(dryrun, force)
952 else:
952 else:
953 self.ui.warn(_("no rollback information available\n"))
953 self.ui.warn(_("no rollback information available\n"))
954 return 1
954 return 1
955 finally:
955 finally:
956 release(lock, wlock)
956 release(lock, wlock)
957
957
958 @unfilteredmethod # Until we get smarter cache management
958 @unfilteredmethod # Until we get smarter cache management
959 def _rollback(self, dryrun, force):
959 def _rollback(self, dryrun, force):
960 ui = self.ui
960 ui = self.ui
961 try:
961 try:
962 args = self.opener.read('undo.desc').splitlines()
962 args = self.opener.read('undo.desc').splitlines()
963 (oldlen, desc, detail) = (int(args[0]), args[1], None)
963 (oldlen, desc, detail) = (int(args[0]), args[1], None)
964 if len(args) >= 3:
964 if len(args) >= 3:
965 detail = args[2]
965 detail = args[2]
966 oldtip = oldlen - 1
966 oldtip = oldlen - 1
967
967
968 if detail and ui.verbose:
968 if detail and ui.verbose:
969 msg = (_('repository tip rolled back to revision %s'
969 msg = (_('repository tip rolled back to revision %s'
970 ' (undo %s: %s)\n')
970 ' (undo %s: %s)\n')
971 % (oldtip, desc, detail))
971 % (oldtip, desc, detail))
972 else:
972 else:
973 msg = (_('repository tip rolled back to revision %s'
973 msg = (_('repository tip rolled back to revision %s'
974 ' (undo %s)\n')
974 ' (undo %s)\n')
975 % (oldtip, desc))
975 % (oldtip, desc))
976 except IOError:
976 except IOError:
977 msg = _('rolling back unknown transaction\n')
977 msg = _('rolling back unknown transaction\n')
978 desc = None
978 desc = None
979
979
980 if not force and self['.'] != self['tip'] and desc == 'commit':
980 if not force and self['.'] != self['tip'] and desc == 'commit':
981 raise util.Abort(
981 raise util.Abort(
982 _('rollback of last commit while not checked out '
982 _('rollback of last commit while not checked out '
983 'may lose data'), hint=_('use -f to force'))
983 'may lose data'), hint=_('use -f to force'))
984
984
985 ui.status(msg)
985 ui.status(msg)
986 if dryrun:
986 if dryrun:
987 return 0
987 return 0
988
988
989 parents = self.dirstate.parents()
989 parents = self.dirstate.parents()
990 self.destroying()
990 self.destroying()
991 vfsmap = {'plain': self.opener}
991 vfsmap = {'plain': self.opener}
992 transaction.rollback(self.sopener, vfsmap, 'undo', ui.warn)
992 transaction.rollback(self.sopener, vfsmap, 'undo', ui.warn)
993 if self.vfs.exists('undo.bookmarks'):
993 if self.vfs.exists('undo.bookmarks'):
994 self.vfs.rename('undo.bookmarks', 'bookmarks')
994 self.vfs.rename('undo.bookmarks', 'bookmarks')
995 if self.svfs.exists('undo.phaseroots'):
995 if self.svfs.exists('undo.phaseroots'):
996 self.svfs.rename('undo.phaseroots', 'phaseroots')
996 self.svfs.rename('undo.phaseroots', 'phaseroots')
997 self.invalidate()
997 self.invalidate()
998
998
999 parentgone = (parents[0] not in self.changelog.nodemap or
999 parentgone = (parents[0] not in self.changelog.nodemap or
1000 parents[1] not in self.changelog.nodemap)
1000 parents[1] not in self.changelog.nodemap)
1001 if parentgone:
1001 if parentgone:
1002 self.vfs.rename('undo.dirstate', 'dirstate')
1002 self.vfs.rename('undo.dirstate', 'dirstate')
1003 try:
1003 try:
1004 branch = self.opener.read('undo.branch')
1004 branch = self.opener.read('undo.branch')
1005 self.dirstate.setbranch(encoding.tolocal(branch))
1005 self.dirstate.setbranch(encoding.tolocal(branch))
1006 except IOError:
1006 except IOError:
1007 ui.warn(_('named branch could not be reset: '
1007 ui.warn(_('named branch could not be reset: '
1008 'current branch is still \'%s\'\n')
1008 'current branch is still \'%s\'\n')
1009 % self.dirstate.branch())
1009 % self.dirstate.branch())
1010
1010
1011 self.dirstate.invalidate()
1011 self.dirstate.invalidate()
1012 parents = tuple([p.rev() for p in self.parents()])
1012 parents = tuple([p.rev() for p in self.parents()])
1013 if len(parents) > 1:
1013 if len(parents) > 1:
1014 ui.status(_('working directory now based on '
1014 ui.status(_('working directory now based on '
1015 'revisions %d and %d\n') % parents)
1015 'revisions %d and %d\n') % parents)
1016 else:
1016 else:
1017 ui.status(_('working directory now based on '
1017 ui.status(_('working directory now based on '
1018 'revision %d\n') % parents)
1018 'revision %d\n') % parents)
1019 # TODO: if we know which new heads may result from this rollback, pass
1019 # TODO: if we know which new heads may result from this rollback, pass
1020 # them to destroy(), which will prevent the branchhead cache from being
1020 # them to destroy(), which will prevent the branchhead cache from being
1021 # invalidated.
1021 # invalidated.
1022 self.destroyed()
1022 self.destroyed()
1023 return 0
1023 return 0
1024
1024
1025 def invalidatecaches(self):
1025 def invalidatecaches(self):
1026
1026
1027 if '_tagscache' in vars(self):
1027 if '_tagscache' in vars(self):
1028 # can't use delattr on proxy
1028 # can't use delattr on proxy
1029 del self.__dict__['_tagscache']
1029 del self.__dict__['_tagscache']
1030
1030
1031 self.unfiltered()._branchcaches.clear()
1031 self.unfiltered()._branchcaches.clear()
1032 self.invalidatevolatilesets()
1032 self.invalidatevolatilesets()
1033
1033
1034 def invalidatevolatilesets(self):
1034 def invalidatevolatilesets(self):
1035 self.filteredrevcache.clear()
1035 self.filteredrevcache.clear()
1036 obsolete.clearobscaches(self)
1036 obsolete.clearobscaches(self)
1037
1037
1038 def invalidatedirstate(self):
1038 def invalidatedirstate(self):
1039 '''Invalidates the dirstate, causing the next call to dirstate
1039 '''Invalidates the dirstate, causing the next call to dirstate
1040 to check if it was modified since the last time it was read,
1040 to check if it was modified since the last time it was read,
1041 rereading it if it has.
1041 rereading it if it has.
1042
1042
1043 This is different to dirstate.invalidate() that it doesn't always
1043 This is different to dirstate.invalidate() that it doesn't always
1044 rereads the dirstate. Use dirstate.invalidate() if you want to
1044 rereads the dirstate. Use dirstate.invalidate() if you want to
1045 explicitly read the dirstate again (i.e. restoring it to a previous
1045 explicitly read the dirstate again (i.e. restoring it to a previous
1046 known good state).'''
1046 known good state).'''
1047 if hasunfilteredcache(self, 'dirstate'):
1047 if hasunfilteredcache(self, 'dirstate'):
1048 for k in self.dirstate._filecache:
1048 for k in self.dirstate._filecache:
1049 try:
1049 try:
1050 delattr(self.dirstate, k)
1050 delattr(self.dirstate, k)
1051 except AttributeError:
1051 except AttributeError:
1052 pass
1052 pass
1053 delattr(self.unfiltered(), 'dirstate')
1053 delattr(self.unfiltered(), 'dirstate')
1054
1054
1055 def invalidate(self):
1055 def invalidate(self):
1056 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1056 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1057 for k in self._filecache:
1057 for k in self._filecache:
1058 # dirstate is invalidated separately in invalidatedirstate()
1058 # dirstate is invalidated separately in invalidatedirstate()
1059 if k == 'dirstate':
1059 if k == 'dirstate':
1060 continue
1060 continue
1061
1061
1062 try:
1062 try:
1063 delattr(unfiltered, k)
1063 delattr(unfiltered, k)
1064 except AttributeError:
1064 except AttributeError:
1065 pass
1065 pass
1066 self.invalidatecaches()
1066 self.invalidatecaches()
1067 self.store.invalidatecaches()
1067 self.store.invalidatecaches()
1068
1068
1069 def invalidateall(self):
1069 def invalidateall(self):
1070 '''Fully invalidates both store and non-store parts, causing the
1070 '''Fully invalidates both store and non-store parts, causing the
1071 subsequent operation to reread any outside changes.'''
1071 subsequent operation to reread any outside changes.'''
1072 # extension should hook this to invalidate its caches
1072 # extension should hook this to invalidate its caches
1073 self.invalidate()
1073 self.invalidate()
1074 self.invalidatedirstate()
1074 self.invalidatedirstate()
1075
1075
1076 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1076 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1077 try:
1077 try:
1078 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1078 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1079 except error.LockHeld, inst:
1079 except error.LockHeld, inst:
1080 if not wait:
1080 if not wait:
1081 raise
1081 raise
1082 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1082 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1083 (desc, inst.locker))
1083 (desc, inst.locker))
1084 # default to 600 seconds timeout
1084 # default to 600 seconds timeout
1085 l = lockmod.lock(vfs, lockname,
1085 l = lockmod.lock(vfs, lockname,
1086 int(self.ui.config("ui", "timeout", "600")),
1086 int(self.ui.config("ui", "timeout", "600")),
1087 releasefn, desc=desc)
1087 releasefn, desc=desc)
1088 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1088 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1089 if acquirefn:
1089 if acquirefn:
1090 acquirefn()
1090 acquirefn()
1091 return l
1091 return l
1092
1092
1093 def _afterlock(self, callback):
1093 def _afterlock(self, callback):
1094 """add a callback to the current repository lock.
1094 """add a callback to the current repository lock.
1095
1095
1096 The callback will be executed on lock release."""
1096 The callback will be executed on lock release."""
1097 l = self._lockref and self._lockref()
1097 l = self._lockref and self._lockref()
1098 if l:
1098 if l:
1099 l.postrelease.append(callback)
1099 l.postrelease.append(callback)
1100 else:
1100 else:
1101 callback()
1101 callback()
1102
1102
1103 def lock(self, wait=True):
1103 def lock(self, wait=True):
1104 '''Lock the repository store (.hg/store) and return a weak reference
1104 '''Lock the repository store (.hg/store) and return a weak reference
1105 to the lock. Use this before modifying the store (e.g. committing or
1105 to the lock. Use this before modifying the store (e.g. committing or
1106 stripping). If you are opening a transaction, get a lock as well.)'''
1106 stripping). If you are opening a transaction, get a lock as well.)'''
1107 l = self._lockref and self._lockref()
1107 l = self._lockref and self._lockref()
1108 if l is not None and l.held:
1108 if l is not None and l.held:
1109 l.lock()
1109 l.lock()
1110 return l
1110 return l
1111
1111
1112 def unlock():
1112 def unlock():
1113 for k, ce in self._filecache.items():
1113 for k, ce in self._filecache.items():
1114 if k == 'dirstate' or k not in self.__dict__:
1114 if k == 'dirstate' or k not in self.__dict__:
1115 continue
1115 continue
1116 ce.refresh()
1116 ce.refresh()
1117
1117
1118 l = self._lock(self.svfs, "lock", wait, unlock,
1118 l = self._lock(self.svfs, "lock", wait, unlock,
1119 self.invalidate, _('repository %s') % self.origroot)
1119 self.invalidate, _('repository %s') % self.origroot)
1120 self._lockref = weakref.ref(l)
1120 self._lockref = weakref.ref(l)
1121 return l
1121 return l
1122
1122
1123 def wlock(self, wait=True):
1123 def wlock(self, wait=True):
1124 '''Lock the non-store parts of the repository (everything under
1124 '''Lock the non-store parts of the repository (everything under
1125 .hg except .hg/store) and return a weak reference to the lock.
1125 .hg except .hg/store) and return a weak reference to the lock.
1126 Use this before modifying files in .hg.'''
1126 Use this before modifying files in .hg.'''
1127 l = self._wlockref and self._wlockref()
1127 l = self._wlockref and self._wlockref()
1128 if l is not None and l.held:
1128 if l is not None and l.held:
1129 l.lock()
1129 l.lock()
1130 return l
1130 return l
1131
1131
1132 def unlock():
1132 def unlock():
1133 if self.dirstate.pendingparentchange():
1133 if self.dirstate.pendingparentchange():
1134 self.dirstate.invalidate()
1134 self.dirstate.invalidate()
1135 else:
1135 else:
1136 self.dirstate.write()
1136 self.dirstate.write()
1137
1137
1138 self._filecache['dirstate'].refresh()
1138 self._filecache['dirstate'].refresh()
1139
1139
1140 l = self._lock(self.vfs, "wlock", wait, unlock,
1140 l = self._lock(self.vfs, "wlock", wait, unlock,
1141 self.invalidatedirstate, _('working directory of %s') %
1141 self.invalidatedirstate, _('working directory of %s') %
1142 self.origroot)
1142 self.origroot)
1143 self._wlockref = weakref.ref(l)
1143 self._wlockref = weakref.ref(l)
1144 return l
1144 return l
1145
1145
1146 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1146 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1147 """
1147 """
1148 commit an individual file as part of a larger transaction
1148 commit an individual file as part of a larger transaction
1149 """
1149 """
1150
1150
1151 fname = fctx.path()
1151 fname = fctx.path()
1152 text = fctx.data()
1152 text = fctx.data()
1153 flog = self.file(fname)
1153 flog = self.file(fname)
1154 fparent1 = manifest1.get(fname, nullid)
1154 fparent1 = manifest1.get(fname, nullid)
1155 fparent2 = manifest2.get(fname, nullid)
1155 fparent2 = manifest2.get(fname, nullid)
1156
1156
1157 meta = {}
1157 meta = {}
1158 copy = fctx.renamed()
1158 copy = fctx.renamed()
1159 if copy and copy[0] != fname:
1159 if copy and copy[0] != fname:
1160 # Mark the new revision of this file as a copy of another
1160 # Mark the new revision of this file as a copy of another
1161 # file. This copy data will effectively act as a parent
1161 # file. This copy data will effectively act as a parent
1162 # of this new revision. If this is a merge, the first
1162 # of this new revision. If this is a merge, the first
1163 # parent will be the nullid (meaning "look up the copy data")
1163 # parent will be the nullid (meaning "look up the copy data")
1164 # and the second one will be the other parent. For example:
1164 # and the second one will be the other parent. For example:
1165 #
1165 #
1166 # 0 --- 1 --- 3 rev1 changes file foo
1166 # 0 --- 1 --- 3 rev1 changes file foo
1167 # \ / rev2 renames foo to bar and changes it
1167 # \ / rev2 renames foo to bar and changes it
1168 # \- 2 -/ rev3 should have bar with all changes and
1168 # \- 2 -/ rev3 should have bar with all changes and
1169 # should record that bar descends from
1169 # should record that bar descends from
1170 # bar in rev2 and foo in rev1
1170 # bar in rev2 and foo in rev1
1171 #
1171 #
1172 # this allows this merge to succeed:
1172 # this allows this merge to succeed:
1173 #
1173 #
1174 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1174 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1175 # \ / merging rev3 and rev4 should use bar@rev2
1175 # \ / merging rev3 and rev4 should use bar@rev2
1176 # \- 2 --- 4 as the merge base
1176 # \- 2 --- 4 as the merge base
1177 #
1177 #
1178
1178
1179 cfname = copy[0]
1179 cfname = copy[0]
1180 crev = manifest1.get(cfname)
1180 crev = manifest1.get(cfname)
1181 newfparent = fparent2
1181 newfparent = fparent2
1182
1182
1183 if manifest2: # branch merge
1183 if manifest2: # branch merge
1184 if fparent2 == nullid or crev is None: # copied on remote side
1184 if fparent2 == nullid or crev is None: # copied on remote side
1185 if cfname in manifest2:
1185 if cfname in manifest2:
1186 crev = manifest2[cfname]
1186 crev = manifest2[cfname]
1187 newfparent = fparent1
1187 newfparent = fparent1
1188
1188
1189 # find source in nearest ancestor if we've lost track
1189 # find source in nearest ancestor if we've lost track
1190 if not crev:
1190 if not crev:
1191 self.ui.debug(" %s: searching for copy revision for %s\n" %
1191 self.ui.debug(" %s: searching for copy revision for %s\n" %
1192 (fname, cfname))
1192 (fname, cfname))
1193 for ancestor in self[None].ancestors():
1193 for ancestor in self[None].ancestors():
1194 if cfname in ancestor:
1194 if cfname in ancestor:
1195 crev = ancestor[cfname].filenode()
1195 crev = ancestor[cfname].filenode()
1196 break
1196 break
1197
1197
1198 if crev:
1198 if crev:
1199 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1199 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1200 meta["copy"] = cfname
1200 meta["copy"] = cfname
1201 meta["copyrev"] = hex(crev)
1201 meta["copyrev"] = hex(crev)
1202 fparent1, fparent2 = nullid, newfparent
1202 fparent1, fparent2 = nullid, newfparent
1203 else:
1203 else:
1204 self.ui.warn(_("warning: can't find ancestor for '%s' "
1204 self.ui.warn(_("warning: can't find ancestor for '%s' "
1205 "copied from '%s'!\n") % (fname, cfname))
1205 "copied from '%s'!\n") % (fname, cfname))
1206
1206
1207 elif fparent1 == nullid:
1207 elif fparent1 == nullid:
1208 fparent1, fparent2 = fparent2, nullid
1208 fparent1, fparent2 = fparent2, nullid
1209 elif fparent2 != nullid:
1209 elif fparent2 != nullid:
1210 # is one parent an ancestor of the other?
1210 # is one parent an ancestor of the other?
1211 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1211 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1212 if fparent1 in fparentancestors:
1212 if fparent1 in fparentancestors:
1213 fparent1, fparent2 = fparent2, nullid
1213 fparent1, fparent2 = fparent2, nullid
1214 elif fparent2 in fparentancestors:
1214 elif fparent2 in fparentancestors:
1215 fparent2 = nullid
1215 fparent2 = nullid
1216
1216
1217 # is the file changed?
1217 # is the file changed?
1218 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1218 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1219 changelist.append(fname)
1219 changelist.append(fname)
1220 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1220 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1221 # are just the flags changed during merge?
1221 # are just the flags changed during merge?
1222 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1222 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1223 changelist.append(fname)
1223 changelist.append(fname)
1224
1224
1225 return fparent1
1225 return fparent1
1226
1226
1227 @unfilteredmethod
1227 @unfilteredmethod
1228 def commit(self, text="", user=None, date=None, match=None, force=False,
1228 def commit(self, text="", user=None, date=None, match=None, force=False,
1229 editor=False, extra={}):
1229 editor=False, extra={}):
1230 """Add a new revision to current repository.
1230 """Add a new revision to current repository.
1231
1231
1232 Revision information is gathered from the working directory,
1232 Revision information is gathered from the working directory,
1233 match can be used to filter the committed files. If editor is
1233 match can be used to filter the committed files. If editor is
1234 supplied, it is called to get a commit message.
1234 supplied, it is called to get a commit message.
1235 """
1235 """
1236
1236
1237 def fail(f, msg):
1237 def fail(f, msg):
1238 raise util.Abort('%s: %s' % (f, msg))
1238 raise util.Abort('%s: %s' % (f, msg))
1239
1239
1240 if not match:
1240 if not match:
1241 match = matchmod.always(self.root, '')
1241 match = matchmod.always(self.root, '')
1242
1242
1243 if not force:
1243 if not force:
1244 vdirs = []
1244 vdirs = []
1245 match.explicitdir = vdirs.append
1245 match.explicitdir = vdirs.append
1246 match.bad = fail
1246 match.bad = fail
1247
1247
1248 wlock = self.wlock()
1248 wlock = self.wlock()
1249 try:
1249 try:
1250 wctx = self[None]
1250 wctx = self[None]
1251 merge = len(wctx.parents()) > 1
1251 merge = len(wctx.parents()) > 1
1252
1252
1253 if (not force and merge and match and
1253 if (not force and merge and match and
1254 (match.files() or match.anypats())):
1254 (match.files() or match.anypats())):
1255 raise util.Abort(_('cannot partially commit a merge '
1255 raise util.Abort(_('cannot partially commit a merge '
1256 '(do not specify files or patterns)'))
1256 '(do not specify files or patterns)'))
1257
1257
1258 status = self.status(match=match, clean=force)
1258 status = self.status(match=match, clean=force)
1259 if force:
1259 if force:
1260 status.modified.extend(status.clean) # mq may commit clean files
1260 status.modified.extend(status.clean) # mq may commit clean files
1261
1261
1262 # check subrepos
1262 # check subrepos
1263 subs = []
1263 subs = []
1264 commitsubs = set()
1264 commitsubs = set()
1265 newstate = wctx.substate.copy()
1265 newstate = wctx.substate.copy()
1266 # only manage subrepos and .hgsubstate if .hgsub is present
1266 # only manage subrepos and .hgsubstate if .hgsub is present
1267 if '.hgsub' in wctx:
1267 if '.hgsub' in wctx:
1268 # we'll decide whether to track this ourselves, thanks
1268 # we'll decide whether to track this ourselves, thanks
1269 for c in status.modified, status.added, status.removed:
1269 for c in status.modified, status.added, status.removed:
1270 if '.hgsubstate' in c:
1270 if '.hgsubstate' in c:
1271 c.remove('.hgsubstate')
1271 c.remove('.hgsubstate')
1272
1272
1273 # compare current state to last committed state
1273 # compare current state to last committed state
1274 # build new substate based on last committed state
1274 # build new substate based on last committed state
1275 oldstate = wctx.p1().substate
1275 oldstate = wctx.p1().substate
1276 for s in sorted(newstate.keys()):
1276 for s in sorted(newstate.keys()):
1277 if not match(s):
1277 if not match(s):
1278 # ignore working copy, use old state if present
1278 # ignore working copy, use old state if present
1279 if s in oldstate:
1279 if s in oldstate:
1280 newstate[s] = oldstate[s]
1280 newstate[s] = oldstate[s]
1281 continue
1281 continue
1282 if not force:
1282 if not force:
1283 raise util.Abort(
1283 raise util.Abort(
1284 _("commit with new subrepo %s excluded") % s)
1284 _("commit with new subrepo %s excluded") % s)
1285 if wctx.sub(s).dirty(True):
1285 if wctx.sub(s).dirty(True):
1286 if not self.ui.configbool('ui', 'commitsubrepos'):
1286 if not self.ui.configbool('ui', 'commitsubrepos'):
1287 raise util.Abort(
1287 raise util.Abort(
1288 _("uncommitted changes in subrepo %s") % s,
1288 _("uncommitted changes in subrepo %s") % s,
1289 hint=_("use --subrepos for recursive commit"))
1289 hint=_("use --subrepos for recursive commit"))
1290 subs.append(s)
1290 subs.append(s)
1291 commitsubs.add(s)
1291 commitsubs.add(s)
1292 else:
1292 else:
1293 bs = wctx.sub(s).basestate()
1293 bs = wctx.sub(s).basestate()
1294 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1294 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1295 if oldstate.get(s, (None, None, None))[1] != bs:
1295 if oldstate.get(s, (None, None, None))[1] != bs:
1296 subs.append(s)
1296 subs.append(s)
1297
1297
1298 # check for removed subrepos
1298 # check for removed subrepos
1299 for p in wctx.parents():
1299 for p in wctx.parents():
1300 r = [s for s in p.substate if s not in newstate]
1300 r = [s for s in p.substate if s not in newstate]
1301 subs += [s for s in r if match(s)]
1301 subs += [s for s in r if match(s)]
1302 if subs:
1302 if subs:
1303 if (not match('.hgsub') and
1303 if (not match('.hgsub') and
1304 '.hgsub' in (wctx.modified() + wctx.added())):
1304 '.hgsub' in (wctx.modified() + wctx.added())):
1305 raise util.Abort(
1305 raise util.Abort(
1306 _("can't commit subrepos without .hgsub"))
1306 _("can't commit subrepos without .hgsub"))
1307 status.modified.insert(0, '.hgsubstate')
1307 status.modified.insert(0, '.hgsubstate')
1308
1308
1309 elif '.hgsub' in status.removed:
1309 elif '.hgsub' in status.removed:
1310 # clean up .hgsubstate when .hgsub is removed
1310 # clean up .hgsubstate when .hgsub is removed
1311 if ('.hgsubstate' in wctx and
1311 if ('.hgsubstate' in wctx and
1312 '.hgsubstate' not in (status.modified + status.added +
1312 '.hgsubstate' not in (status.modified + status.added +
1313 status.removed)):
1313 status.removed)):
1314 status.removed.insert(0, '.hgsubstate')
1314 status.removed.insert(0, '.hgsubstate')
1315
1315
1316 # make sure all explicit patterns are matched
1316 # make sure all explicit patterns are matched
1317 if not force and match.files():
1317 if not force and match.files():
1318 matched = set(status.modified + status.added + status.removed)
1318 matched = set(status.modified + status.added + status.removed)
1319
1319
1320 for f in match.files():
1320 for f in match.files():
1321 f = self.dirstate.normalize(f)
1321 f = self.dirstate.normalize(f)
1322 if f == '.' or f in matched or f in wctx.substate:
1322 if f == '.' or f in matched or f in wctx.substate:
1323 continue
1323 continue
1324 if f in status.deleted:
1324 if f in status.deleted:
1325 fail(f, _('file not found!'))
1325 fail(f, _('file not found!'))
1326 if f in vdirs: # visited directory
1326 if f in vdirs: # visited directory
1327 d = f + '/'
1327 d = f + '/'
1328 for mf in matched:
1328 for mf in matched:
1329 if mf.startswith(d):
1329 if mf.startswith(d):
1330 break
1330 break
1331 else:
1331 else:
1332 fail(f, _("no match under directory!"))
1332 fail(f, _("no match under directory!"))
1333 elif f not in self.dirstate:
1333 elif f not in self.dirstate:
1334 fail(f, _("file not tracked!"))
1334 fail(f, _("file not tracked!"))
1335
1335
1336 cctx = context.workingctx(self, text, user, date, extra, status)
1336 cctx = context.workingctx(self, text, user, date, extra, status)
1337
1337
1338 if (not force and not extra.get("close") and not merge
1338 if (not force and not extra.get("close") and not merge
1339 and not cctx.files()
1339 and not cctx.files()
1340 and wctx.branch() == wctx.p1().branch()):
1340 and wctx.branch() == wctx.p1().branch()):
1341 return None
1341 return None
1342
1342
1343 if merge and cctx.deleted():
1343 if merge and cctx.deleted():
1344 raise util.Abort(_("cannot commit merge with missing files"))
1344 raise util.Abort(_("cannot commit merge with missing files"))
1345
1345
1346 ms = mergemod.mergestate(self)
1346 ms = mergemod.mergestate(self)
1347 for f in status.modified:
1347 for f in status.modified:
1348 if f in ms and ms[f] == 'u':
1348 if f in ms and ms[f] == 'u':
1349 raise util.Abort(_("unresolved merge conflicts "
1349 raise util.Abort(_("unresolved merge conflicts "
1350 "(see hg help resolve)"))
1350 "(see hg help resolve)"))
1351
1351
1352 if editor:
1352 if editor:
1353 cctx._text = editor(self, cctx, subs)
1353 cctx._text = editor(self, cctx, subs)
1354 edited = (text != cctx._text)
1354 edited = (text != cctx._text)
1355
1355
1356 # Save commit message in case this transaction gets rolled back
1356 # Save commit message in case this transaction gets rolled back
1357 # (e.g. by a pretxncommit hook). Leave the content alone on
1357 # (e.g. by a pretxncommit hook). Leave the content alone on
1358 # the assumption that the user will use the same editor again.
1358 # the assumption that the user will use the same editor again.
1359 msgfn = self.savecommitmessage(cctx._text)
1359 msgfn = self.savecommitmessage(cctx._text)
1360
1360
1361 # commit subs and write new state
1361 # commit subs and write new state
1362 if subs:
1362 if subs:
1363 for s in sorted(commitsubs):
1363 for s in sorted(commitsubs):
1364 sub = wctx.sub(s)
1364 sub = wctx.sub(s)
1365 self.ui.status(_('committing subrepository %s\n') %
1365 self.ui.status(_('committing subrepository %s\n') %
1366 subrepo.subrelpath(sub))
1366 subrepo.subrelpath(sub))
1367 sr = sub.commit(cctx._text, user, date)
1367 sr = sub.commit(cctx._text, user, date)
1368 newstate[s] = (newstate[s][0], sr)
1368 newstate[s] = (newstate[s][0], sr)
1369 subrepo.writestate(self, newstate)
1369 subrepo.writestate(self, newstate)
1370
1370
1371 p1, p2 = self.dirstate.parents()
1371 p1, p2 = self.dirstate.parents()
1372 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1372 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1373 try:
1373 try:
1374 self.hook("precommit", throw=True, parent1=hookp1,
1374 self.hook("precommit", throw=True, parent1=hookp1,
1375 parent2=hookp2)
1375 parent2=hookp2)
1376 ret = self.commitctx(cctx, True)
1376 ret = self.commitctx(cctx, True)
1377 except: # re-raises
1377 except: # re-raises
1378 if edited:
1378 if edited:
1379 self.ui.write(
1379 self.ui.write(
1380 _('note: commit message saved in %s\n') % msgfn)
1380 _('note: commit message saved in %s\n') % msgfn)
1381 raise
1381 raise
1382
1382
1383 # update bookmarks, dirstate and mergestate
1383 # update bookmarks, dirstate and mergestate
1384 bookmarks.update(self, [p1, p2], ret)
1384 bookmarks.update(self, [p1, p2], ret)
1385 cctx.markcommitted(ret)
1385 cctx.markcommitted(ret)
1386 ms.reset()
1386 ms.reset()
1387 finally:
1387 finally:
1388 wlock.release()
1388 wlock.release()
1389
1389
1390 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1390 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1391 # hack for command that use a temporary commit (eg: histedit)
1391 # hack for command that use a temporary commit (eg: histedit)
1392 # temporary commit got stripped before hook release
1392 # temporary commit got stripped before hook release
1393 if node in self:
1393 if node in self:
1394 self.hook("commit", node=node, parent1=parent1,
1394 self.hook("commit", node=node, parent1=parent1,
1395 parent2=parent2)
1395 parent2=parent2)
1396 self._afterlock(commithook)
1396 self._afterlock(commithook)
1397 return ret
1397 return ret
1398
1398
1399 @unfilteredmethod
1399 @unfilteredmethod
1400 def commitctx(self, ctx, error=False):
1400 def commitctx(self, ctx, error=False):
1401 """Add a new revision to current repository.
1401 """Add a new revision to current repository.
1402 Revision information is passed via the context argument.
1402 Revision information is passed via the context argument.
1403 """
1403 """
1404
1404
1405 tr = None
1405 tr = None
1406 p1, p2 = ctx.p1(), ctx.p2()
1406 p1, p2 = ctx.p1(), ctx.p2()
1407 user = ctx.user()
1407 user = ctx.user()
1408
1408
1409 lock = self.lock()
1409 lock = self.lock()
1410 try:
1410 try:
1411 tr = self.transaction("commit")
1411 tr = self.transaction("commit")
1412 trp = weakref.proxy(tr)
1412 trp = weakref.proxy(tr)
1413
1413
1414 if ctx.files():
1414 if ctx.files():
1415 m1 = p1.manifest()
1415 m1 = p1.manifest()
1416 m2 = p2.manifest()
1416 m2 = p2.manifest()
1417 m = m1.copy()
1417 m = m1.copy()
1418
1418
1419 # check in files
1419 # check in files
1420 added = []
1420 added = []
1421 changed = []
1421 changed = []
1422 removed = list(ctx.removed())
1422 removed = list(ctx.removed())
1423 linkrev = len(self)
1423 linkrev = len(self)
1424 for f in sorted(ctx.modified() + ctx.added()):
1424 for f in sorted(ctx.modified() + ctx.added()):
1425 self.ui.note(f + "\n")
1425 self.ui.note(f + "\n")
1426 try:
1426 try:
1427 fctx = ctx[f]
1427 fctx = ctx[f]
1428 if fctx is None:
1428 if fctx is None:
1429 removed.append(f)
1429 removed.append(f)
1430 else:
1430 else:
1431 added.append(f)
1431 added.append(f)
1432 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1432 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1433 trp, changed)
1433 trp, changed)
1434 m.setflag(f, fctx.flags())
1434 m.setflag(f, fctx.flags())
1435 except OSError, inst:
1435 except OSError, inst:
1436 self.ui.warn(_("trouble committing %s!\n") % f)
1436 self.ui.warn(_("trouble committing %s!\n") % f)
1437 raise
1437 raise
1438 except IOError, inst:
1438 except IOError, inst:
1439 errcode = getattr(inst, 'errno', errno.ENOENT)
1439 errcode = getattr(inst, 'errno', errno.ENOENT)
1440 if error or errcode and errcode != errno.ENOENT:
1440 if error or errcode and errcode != errno.ENOENT:
1441 self.ui.warn(_("trouble committing %s!\n") % f)
1441 self.ui.warn(_("trouble committing %s!\n") % f)
1442 raise
1442 raise
1443
1443
1444 # update manifest
1444 # update manifest
1445 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1445 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1446 drop = [f for f in removed if f in m]
1446 drop = [f for f in removed if f in m]
1447 for f in drop:
1447 for f in drop:
1448 del m[f]
1448 del m[f]
1449 mn = self.manifest.add(m, trp, linkrev,
1449 mn = self.manifest.add(m, trp, linkrev,
1450 p1.manifestnode(), p2.manifestnode(),
1450 p1.manifestnode(), p2.manifestnode(),
1451 added, drop)
1451 added, drop)
1452 files = changed + removed
1452 files = changed + removed
1453 else:
1453 else:
1454 mn = p1.manifestnode()
1454 mn = p1.manifestnode()
1455 files = []
1455 files = []
1456
1456
1457 # update changelog
1457 # update changelog
1458 self.changelog.delayupdate(tr)
1458 self.changelog.delayupdate(tr)
1459 n = self.changelog.add(mn, files, ctx.description(),
1459 n = self.changelog.add(mn, files, ctx.description(),
1460 trp, p1.node(), p2.node(),
1460 trp, p1.node(), p2.node(),
1461 user, ctx.date(), ctx.extra().copy())
1461 user, ctx.date(), ctx.extra().copy())
1462 p = lambda: tr.writepending() and self.root or ""
1462 p = lambda: tr.writepending() and self.root or ""
1463 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1463 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1464 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1464 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1465 parent2=xp2, pending=p)
1465 parent2=xp2, pending=p)
1466 # set the new commit is proper phase
1466 # set the new commit is proper phase
1467 targetphase = subrepo.newcommitphase(self.ui, ctx)
1467 targetphase = subrepo.newcommitphase(self.ui, ctx)
1468 if targetphase:
1468 if targetphase:
1469 # retract boundary do not alter parent changeset.
1469 # retract boundary do not alter parent changeset.
1470 # if a parent have higher the resulting phase will
1470 # if a parent have higher the resulting phase will
1471 # be compliant anyway
1471 # be compliant anyway
1472 #
1472 #
1473 # if minimal phase was 0 we don't need to retract anything
1473 # if minimal phase was 0 we don't need to retract anything
1474 phases.retractboundary(self, tr, targetphase, [n])
1474 phases.retractboundary(self, tr, targetphase, [n])
1475 tr.close()
1475 tr.close()
1476 branchmap.updatecache(self.filtered('served'))
1476 branchmap.updatecache(self.filtered('served'))
1477 return n
1477 return n
1478 finally:
1478 finally:
1479 if tr:
1479 if tr:
1480 tr.release()
1480 tr.release()
1481 lock.release()
1481 lock.release()
1482
1482
1483 @unfilteredmethod
1483 @unfilteredmethod
1484 def destroying(self):
1484 def destroying(self):
1485 '''Inform the repository that nodes are about to be destroyed.
1485 '''Inform the repository that nodes are about to be destroyed.
1486 Intended for use by strip and rollback, so there's a common
1486 Intended for use by strip and rollback, so there's a common
1487 place for anything that has to be done before destroying history.
1487 place for anything that has to be done before destroying history.
1488
1488
1489 This is mostly useful for saving state that is in memory and waiting
1489 This is mostly useful for saving state that is in memory and waiting
1490 to be flushed when the current lock is released. Because a call to
1490 to be flushed when the current lock is released. Because a call to
1491 destroyed is imminent, the repo will be invalidated causing those
1491 destroyed is imminent, the repo will be invalidated causing those
1492 changes to stay in memory (waiting for the next unlock), or vanish
1492 changes to stay in memory (waiting for the next unlock), or vanish
1493 completely.
1493 completely.
1494 '''
1494 '''
1495 # When using the same lock to commit and strip, the phasecache is left
1495 # When using the same lock to commit and strip, the phasecache is left
1496 # dirty after committing. Then when we strip, the repo is invalidated,
1496 # dirty after committing. Then when we strip, the repo is invalidated,
1497 # causing those changes to disappear.
1497 # causing those changes to disappear.
1498 if '_phasecache' in vars(self):
1498 if '_phasecache' in vars(self):
1499 self._phasecache.write()
1499 self._phasecache.write()
1500
1500
1501 @unfilteredmethod
1501 @unfilteredmethod
1502 def destroyed(self):
1502 def destroyed(self):
1503 '''Inform the repository that nodes have been destroyed.
1503 '''Inform the repository that nodes have been destroyed.
1504 Intended for use by strip and rollback, so there's a common
1504 Intended for use by strip and rollback, so there's a common
1505 place for anything that has to be done after destroying history.
1505 place for anything that has to be done after destroying history.
1506 '''
1506 '''
1507 # When one tries to:
1507 # When one tries to:
1508 # 1) destroy nodes thus calling this method (e.g. strip)
1508 # 1) destroy nodes thus calling this method (e.g. strip)
1509 # 2) use phasecache somewhere (e.g. commit)
1509 # 2) use phasecache somewhere (e.g. commit)
1510 #
1510 #
1511 # then 2) will fail because the phasecache contains nodes that were
1511 # then 2) will fail because the phasecache contains nodes that were
1512 # removed. We can either remove phasecache from the filecache,
1512 # removed. We can either remove phasecache from the filecache,
1513 # causing it to reload next time it is accessed, or simply filter
1513 # causing it to reload next time it is accessed, or simply filter
1514 # the removed nodes now and write the updated cache.
1514 # the removed nodes now and write the updated cache.
1515 self._phasecache.filterunknown(self)
1515 self._phasecache.filterunknown(self)
1516 self._phasecache.write()
1516 self._phasecache.write()
1517
1517
1518 # update the 'served' branch cache to help read only server process
1518 # update the 'served' branch cache to help read only server process
1519 # Thanks to branchcache collaboration this is done from the nearest
1519 # Thanks to branchcache collaboration this is done from the nearest
1520 # filtered subset and it is expected to be fast.
1520 # filtered subset and it is expected to be fast.
1521 branchmap.updatecache(self.filtered('served'))
1521 branchmap.updatecache(self.filtered('served'))
1522
1522
1523 # Ensure the persistent tag cache is updated. Doing it now
1523 # Ensure the persistent tag cache is updated. Doing it now
1524 # means that the tag cache only has to worry about destroyed
1524 # means that the tag cache only has to worry about destroyed
1525 # heads immediately after a strip/rollback. That in turn
1525 # heads immediately after a strip/rollback. That in turn
1526 # guarantees that "cachetip == currenttip" (comparing both rev
1526 # guarantees that "cachetip == currenttip" (comparing both rev
1527 # and node) always means no nodes have been added or destroyed.
1527 # and node) always means no nodes have been added or destroyed.
1528
1528
1529 # XXX this is suboptimal when qrefresh'ing: we strip the current
1529 # XXX this is suboptimal when qrefresh'ing: we strip the current
1530 # head, refresh the tag cache, then immediately add a new head.
1530 # head, refresh the tag cache, then immediately add a new head.
1531 # But I think doing it this way is necessary for the "instant
1531 # But I think doing it this way is necessary for the "instant
1532 # tag cache retrieval" case to work.
1532 # tag cache retrieval" case to work.
1533 self.invalidate()
1533 self.invalidate()
1534
1534
1535 def walk(self, match, node=None):
1535 def walk(self, match, node=None):
1536 '''
1536 '''
1537 walk recursively through the directory tree or a given
1537 walk recursively through the directory tree or a given
1538 changeset, finding all files matched by the match
1538 changeset, finding all files matched by the match
1539 function
1539 function
1540 '''
1540 '''
1541 return self[node].walk(match)
1541 return self[node].walk(match)
1542
1542
1543 def status(self, node1='.', node2=None, match=None,
1543 def status(self, node1='.', node2=None, match=None,
1544 ignored=False, clean=False, unknown=False,
1544 ignored=False, clean=False, unknown=False,
1545 listsubrepos=False):
1545 listsubrepos=False):
1546 '''a convenience method that calls node1.status(node2)'''
1546 '''a convenience method that calls node1.status(node2)'''
1547 return self[node1].status(node2, match, ignored, clean, unknown,
1547 return self[node1].status(node2, match, ignored, clean, unknown,
1548 listsubrepos)
1548 listsubrepos)
1549
1549
1550 def heads(self, start=None):
1550 def heads(self, start=None):
1551 heads = self.changelog.heads(start)
1551 heads = self.changelog.heads(start)
1552 # sort the output in rev descending order
1552 # sort the output in rev descending order
1553 return sorted(heads, key=self.changelog.rev, reverse=True)
1553 return sorted(heads, key=self.changelog.rev, reverse=True)
1554
1554
1555 def branchheads(self, branch=None, start=None, closed=False):
1555 def branchheads(self, branch=None, start=None, closed=False):
1556 '''return a (possibly filtered) list of heads for the given branch
1556 '''return a (possibly filtered) list of heads for the given branch
1557
1557
1558 Heads are returned in topological order, from newest to oldest.
1558 Heads are returned in topological order, from newest to oldest.
1559 If branch is None, use the dirstate branch.
1559 If branch is None, use the dirstate branch.
1560 If start is not None, return only heads reachable from start.
1560 If start is not None, return only heads reachable from start.
1561 If closed is True, return heads that are marked as closed as well.
1561 If closed is True, return heads that are marked as closed as well.
1562 '''
1562 '''
1563 if branch is None:
1563 if branch is None:
1564 branch = self[None].branch()
1564 branch = self[None].branch()
1565 branches = self.branchmap()
1565 branches = self.branchmap()
1566 if branch not in branches:
1566 if branch not in branches:
1567 return []
1567 return []
1568 # the cache returns heads ordered lowest to highest
1568 # the cache returns heads ordered lowest to highest
1569 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1569 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1570 if start is not None:
1570 if start is not None:
1571 # filter out the heads that cannot be reached from startrev
1571 # filter out the heads that cannot be reached from startrev
1572 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1572 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1573 bheads = [h for h in bheads if h in fbheads]
1573 bheads = [h for h in bheads if h in fbheads]
1574 return bheads
1574 return bheads
1575
1575
1576 def branches(self, nodes):
1576 def branches(self, nodes):
1577 if not nodes:
1577 if not nodes:
1578 nodes = [self.changelog.tip()]
1578 nodes = [self.changelog.tip()]
1579 b = []
1579 b = []
1580 for n in nodes:
1580 for n in nodes:
1581 t = n
1581 t = n
1582 while True:
1582 while True:
1583 p = self.changelog.parents(n)
1583 p = self.changelog.parents(n)
1584 if p[1] != nullid or p[0] == nullid:
1584 if p[1] != nullid or p[0] == nullid:
1585 b.append((t, n, p[0], p[1]))
1585 b.append((t, n, p[0], p[1]))
1586 break
1586 break
1587 n = p[0]
1587 n = p[0]
1588 return b
1588 return b
1589
1589
1590 def between(self, pairs):
1590 def between(self, pairs):
1591 r = []
1591 r = []
1592
1592
1593 for top, bottom in pairs:
1593 for top, bottom in pairs:
1594 n, l, i = top, [], 0
1594 n, l, i = top, [], 0
1595 f = 1
1595 f = 1
1596
1596
1597 while n != bottom and n != nullid:
1597 while n != bottom and n != nullid:
1598 p = self.changelog.parents(n)[0]
1598 p = self.changelog.parents(n)[0]
1599 if i == f:
1599 if i == f:
1600 l.append(n)
1600 l.append(n)
1601 f = f * 2
1601 f = f * 2
1602 n = p
1602 n = p
1603 i += 1
1603 i += 1
1604
1604
1605 r.append(l)
1605 r.append(l)
1606
1606
1607 return r
1607 return r
1608
1608
1609 def checkpush(self, pushop):
1609 def checkpush(self, pushop):
1610 """Extensions can override this function if additional checks have
1610 """Extensions can override this function if additional checks have
1611 to be performed before pushing, or call it if they override push
1611 to be performed before pushing, or call it if they override push
1612 command.
1612 command.
1613 """
1613 """
1614 pass
1614 pass
1615
1615
1616 @unfilteredpropertycache
1616 @unfilteredpropertycache
1617 def prepushoutgoinghooks(self):
1617 def prepushoutgoinghooks(self):
1618 """Return util.hooks consists of "(repo, remote, outgoing)"
1618 """Return util.hooks consists of "(repo, remote, outgoing)"
1619 functions, which are called before pushing changesets.
1619 functions, which are called before pushing changesets.
1620 """
1620 """
1621 return util.hooks()
1621 return util.hooks()
1622
1622
1623 def stream_in(self, remote, requirements):
1623 def stream_in(self, remote, requirements):
1624 lock = self.lock()
1624 lock = self.lock()
1625 try:
1625 try:
1626 # Save remote branchmap. We will use it later
1626 # Save remote branchmap. We will use it later
1627 # to speed up branchcache creation
1627 # to speed up branchcache creation
1628 rbranchmap = None
1628 rbranchmap = None
1629 if remote.capable("branchmap"):
1629 if remote.capable("branchmap"):
1630 rbranchmap = remote.branchmap()
1630 rbranchmap = remote.branchmap()
1631
1631
1632 fp = remote.stream_out()
1632 fp = remote.stream_out()
1633 l = fp.readline()
1633 l = fp.readline()
1634 try:
1634 try:
1635 resp = int(l)
1635 resp = int(l)
1636 except ValueError:
1636 except ValueError:
1637 raise error.ResponseError(
1637 raise error.ResponseError(
1638 _('unexpected response from remote server:'), l)
1638 _('unexpected response from remote server:'), l)
1639 if resp == 1:
1639 if resp == 1:
1640 raise util.Abort(_('operation forbidden by server'))
1640 raise util.Abort(_('operation forbidden by server'))
1641 elif resp == 2:
1641 elif resp == 2:
1642 raise util.Abort(_('locking the remote repository failed'))
1642 raise util.Abort(_('locking the remote repository failed'))
1643 elif resp != 0:
1643 elif resp != 0:
1644 raise util.Abort(_('the server sent an unknown error code'))
1644 raise util.Abort(_('the server sent an unknown error code'))
1645 self.ui.status(_('streaming all changes\n'))
1645 self.ui.status(_('streaming all changes\n'))
1646 l = fp.readline()
1646 l = fp.readline()
1647 try:
1647 try:
1648 total_files, total_bytes = map(int, l.split(' ', 1))
1648 total_files, total_bytes = map(int, l.split(' ', 1))
1649 except (ValueError, TypeError):
1649 except (ValueError, TypeError):
1650 raise error.ResponseError(
1650 raise error.ResponseError(
1651 _('unexpected response from remote server:'), l)
1651 _('unexpected response from remote server:'), l)
1652 self.ui.status(_('%d files to transfer, %s of data\n') %
1652 self.ui.status(_('%d files to transfer, %s of data\n') %
1653 (total_files, util.bytecount(total_bytes)))
1653 (total_files, util.bytecount(total_bytes)))
1654 handled_bytes = 0
1654 handled_bytes = 0
1655 self.ui.progress(_('clone'), 0, total=total_bytes)
1655 self.ui.progress(_('clone'), 0, total=total_bytes)
1656 start = time.time()
1656 start = time.time()
1657
1657
1658 tr = self.transaction(_('clone'))
1658 tr = self.transaction(_('clone'))
1659 try:
1659 try:
1660 for i in xrange(total_files):
1660 for i in xrange(total_files):
1661 # XXX doesn't support '\n' or '\r' in filenames
1661 # XXX doesn't support '\n' or '\r' in filenames
1662 l = fp.readline()
1662 l = fp.readline()
1663 try:
1663 try:
1664 name, size = l.split('\0', 1)
1664 name, size = l.split('\0', 1)
1665 size = int(size)
1665 size = int(size)
1666 except (ValueError, TypeError):
1666 except (ValueError, TypeError):
1667 raise error.ResponseError(
1667 raise error.ResponseError(
1668 _('unexpected response from remote server:'), l)
1668 _('unexpected response from remote server:'), l)
1669 if self.ui.debugflag:
1669 if self.ui.debugflag:
1670 self.ui.debug('adding %s (%s)\n' %
1670 self.ui.debug('adding %s (%s)\n' %
1671 (name, util.bytecount(size)))
1671 (name, util.bytecount(size)))
1672 # for backwards compat, name was partially encoded
1672 # for backwards compat, name was partially encoded
1673 ofp = self.sopener(store.decodedir(name), 'w')
1673 ofp = self.sopener(store.decodedir(name), 'w')
1674 for chunk in util.filechunkiter(fp, limit=size):
1674 for chunk in util.filechunkiter(fp, limit=size):
1675 handled_bytes += len(chunk)
1675 handled_bytes += len(chunk)
1676 self.ui.progress(_('clone'), handled_bytes,
1676 self.ui.progress(_('clone'), handled_bytes,
1677 total=total_bytes)
1677 total=total_bytes)
1678 ofp.write(chunk)
1678 ofp.write(chunk)
1679 ofp.close()
1679 ofp.close()
1680 tr.close()
1680 tr.close()
1681 finally:
1681 finally:
1682 tr.release()
1682 tr.release()
1683
1683
1684 # Writing straight to files circumvented the inmemory caches
1684 # Writing straight to files circumvented the inmemory caches
1685 self.invalidate()
1685 self.invalidate()
1686
1686
1687 elapsed = time.time() - start
1687 elapsed = time.time() - start
1688 if elapsed <= 0:
1688 if elapsed <= 0:
1689 elapsed = 0.001
1689 elapsed = 0.001
1690 self.ui.progress(_('clone'), None)
1690 self.ui.progress(_('clone'), None)
1691 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1691 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1692 (util.bytecount(total_bytes), elapsed,
1692 (util.bytecount(total_bytes), elapsed,
1693 util.bytecount(total_bytes / elapsed)))
1693 util.bytecount(total_bytes / elapsed)))
1694
1694
1695 # new requirements = old non-format requirements +
1695 # new requirements = old non-format requirements +
1696 # new format-related
1696 # new format-related
1697 # requirements from the streamed-in repository
1697 # requirements from the streamed-in repository
1698 requirements.update(set(self.requirements) - self.supportedformats)
1698 requirements.update(set(self.requirements) - self.supportedformats)
1699 self._applyrequirements(requirements)
1699 self._applyrequirements(requirements)
1700 self._writerequirements()
1700 self._writerequirements()
1701
1701
1702 if rbranchmap:
1702 if rbranchmap:
1703 rbheads = []
1703 rbheads = []
1704 closed = []
1704 closed = []
1705 for bheads in rbranchmap.itervalues():
1705 for bheads in rbranchmap.itervalues():
1706 rbheads.extend(bheads)
1706 rbheads.extend(bheads)
1707 for h in bheads:
1707 for h in bheads:
1708 r = self.changelog.rev(h)
1708 r = self.changelog.rev(h)
1709 b, c = self.changelog.branchinfo(r)
1709 b, c = self.changelog.branchinfo(r)
1710 if c:
1710 if c:
1711 closed.append(h)
1711 closed.append(h)
1712
1712
1713 if rbheads:
1713 if rbheads:
1714 rtiprev = max((int(self.changelog.rev(node))
1714 rtiprev = max((int(self.changelog.rev(node))
1715 for node in rbheads))
1715 for node in rbheads))
1716 cache = branchmap.branchcache(rbranchmap,
1716 cache = branchmap.branchcache(rbranchmap,
1717 self[rtiprev].node(),
1717 self[rtiprev].node(),
1718 rtiprev,
1718 rtiprev,
1719 closednodes=closed)
1719 closednodes=closed)
1720 # Try to stick it as low as possible
1720 # Try to stick it as low as possible
1721 # filter above served are unlikely to be fetch from a clone
1721 # filter above served are unlikely to be fetch from a clone
1722 for candidate in ('base', 'immutable', 'served'):
1722 for candidate in ('base', 'immutable', 'served'):
1723 rview = self.filtered(candidate)
1723 rview = self.filtered(candidate)
1724 if cache.validfor(rview):
1724 if cache.validfor(rview):
1725 self._branchcaches[candidate] = cache
1725 self._branchcaches[candidate] = cache
1726 cache.write(rview)
1726 cache.write(rview)
1727 break
1727 break
1728 self.invalidate()
1728 self.invalidate()
1729 return len(self.heads()) + 1
1729 return len(self.heads()) + 1
1730 finally:
1730 finally:
1731 lock.release()
1731 lock.release()
1732
1732
1733 def clone(self, remote, heads=[], stream=None):
1733 def clone(self, remote, heads=[], stream=None):
1734 '''clone remote repository.
1734 '''clone remote repository.
1735
1735
1736 keyword arguments:
1736 keyword arguments:
1737 heads: list of revs to clone (forces use of pull)
1737 heads: list of revs to clone (forces use of pull)
1738 stream: use streaming clone if possible'''
1738 stream: use streaming clone if possible'''
1739
1739
1740 # now, all clients that can request uncompressed clones can
1740 # now, all clients that can request uncompressed clones can
1741 # read repo formats supported by all servers that can serve
1741 # read repo formats supported by all servers that can serve
1742 # them.
1742 # them.
1743
1743
1744 # if revlog format changes, client will have to check version
1744 # if revlog format changes, client will have to check version
1745 # and format flags on "stream" capability, and use
1745 # and format flags on "stream" capability, and use
1746 # uncompressed only if compatible.
1746 # uncompressed only if compatible.
1747
1747
1748 if stream is None:
1748 if stream is None:
1749 # if the server explicitly prefers to stream (for fast LANs)
1749 # if the server explicitly prefers to stream (for fast LANs)
1750 stream = remote.capable('stream-preferred')
1750 stream = remote.capable('stream-preferred')
1751
1751
1752 if stream and not heads:
1752 if stream and not heads:
1753 # 'stream' means remote revlog format is revlogv1 only
1753 # 'stream' means remote revlog format is revlogv1 only
1754 if remote.capable('stream'):
1754 if remote.capable('stream'):
1755 self.stream_in(remote, set(('revlogv1',)))
1755 self.stream_in(remote, set(('revlogv1',)))
1756 else:
1756 else:
1757 # otherwise, 'streamreqs' contains the remote revlog format
1757 # otherwise, 'streamreqs' contains the remote revlog format
1758 streamreqs = remote.capable('streamreqs')
1758 streamreqs = remote.capable('streamreqs')
1759 if streamreqs:
1759 if streamreqs:
1760 streamreqs = set(streamreqs.split(','))
1760 streamreqs = set(streamreqs.split(','))
1761 # if we support it, stream in and adjust our requirements
1761 # if we support it, stream in and adjust our requirements
1762 if not streamreqs - self.supportedformats:
1762 if not streamreqs - self.supportedformats:
1763 self.stream_in(remote, streamreqs)
1763 self.stream_in(remote, streamreqs)
1764
1764
1765 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1765 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1766 try:
1766 try:
1767 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1767 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1768 ret = exchange.pull(self, remote, heads).cgresult
1768 ret = exchange.pull(self, remote, heads).cgresult
1769 finally:
1769 finally:
1770 self.ui.restoreconfig(quiet)
1770 self.ui.restoreconfig(quiet)
1771 return ret
1771 return ret
1772
1772
1773 def pushkey(self, namespace, key, old, new):
1773 def pushkey(self, namespace, key, old, new):
1774 try:
1774 try:
1775 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1775 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1776 old=old, new=new)
1776 old=old, new=new)
1777 except error.HookAbort, exc:
1777 except error.HookAbort, exc:
1778 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1778 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1779 if exc.hint:
1779 if exc.hint:
1780 self.ui.write_err(_("(%s)\n") % exc.hint)
1780 self.ui.write_err(_("(%s)\n") % exc.hint)
1781 return False
1781 return False
1782 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1782 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1783 ret = pushkey.push(self, namespace, key, old, new)
1783 ret = pushkey.push(self, namespace, key, old, new)
1784 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1784 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1785 ret=ret)
1785 ret=ret)
1786 return ret
1786 return ret
1787
1787
1788 def listkeys(self, namespace):
1788 def listkeys(self, namespace):
1789 self.hook('prelistkeys', throw=True, namespace=namespace)
1789 self.hook('prelistkeys', throw=True, namespace=namespace)
1790 self.ui.debug('listing keys for "%s"\n' % namespace)
1790 self.ui.debug('listing keys for "%s"\n' % namespace)
1791 values = pushkey.list(self, namespace)
1791 values = pushkey.list(self, namespace)
1792 self.hook('listkeys', namespace=namespace, values=values)
1792 self.hook('listkeys', namespace=namespace, values=values)
1793 return values
1793 return values
1794
1794
1795 def debugwireargs(self, one, two, three=None, four=None, five=None):
1795 def debugwireargs(self, one, two, three=None, four=None, five=None):
1796 '''used to test argument passing over the wire'''
1796 '''used to test argument passing over the wire'''
1797 return "%s %s %s %s %s" % (one, two, three, four, five)
1797 return "%s %s %s %s %s" % (one, two, three, four, five)
1798
1798
1799 def savecommitmessage(self, text):
1799 def savecommitmessage(self, text):
1800 fp = self.opener('last-message.txt', 'wb')
1800 fp = self.opener('last-message.txt', 'wb')
1801 try:
1801 try:
1802 fp.write(text)
1802 fp.write(text)
1803 finally:
1803 finally:
1804 fp.close()
1804 fp.close()
1805 return self.pathto(fp.name[len(self.root) + 1:])
1805 return self.pathto(fp.name[len(self.root) + 1:])
1806
1806
1807 # used to avoid circular references so destructors work
1807 # used to avoid circular references so destructors work
1808 def aftertrans(files):
1808 def aftertrans(files):
1809 renamefiles = [tuple(t) for t in files]
1809 renamefiles = [tuple(t) for t in files]
1810 def a():
1810 def a():
1811 for vfs, src, dest in renamefiles:
1811 for vfs, src, dest in renamefiles:
1812 try:
1812 try:
1813 vfs.rename(src, dest)
1813 vfs.rename(src, dest)
1814 except OSError: # journal file does not yet exist
1814 except OSError: # journal file does not yet exist
1815 pass
1815 pass
1816 return a
1816 return a
1817
1817
1818 def undoname(fn):
1818 def undoname(fn):
1819 base, name = os.path.split(fn)
1819 base, name = os.path.split(fn)
1820 assert name.startswith('journal')
1820 assert name.startswith('journal')
1821 return os.path.join(base, name.replace('journal', 'undo', 1))
1821 return os.path.join(base, name.replace('journal', 'undo', 1))
1822
1822
1823 def instance(ui, path, create):
1823 def instance(ui, path, create):
1824 return localrepository(ui, util.urllocalpath(path), create)
1824 return localrepository(ui, util.urllocalpath(path), create)
1825
1825
1826 def islocal(path):
1826 def islocal(path):
1827 return True
1827 return True
@@ -1,80 +1,74 b''
1 from i18n import _
1 from i18n import _
2 from mercurial import util
2 from mercurial import util
3 import weakref
4
3
5 def tolist(val):
4 def tolist(val):
6 """
5 """
7 a convenience method to return an empty list instead of None
6 a convenience method to return an empty list instead of None
8 """
7 """
9 if val is None:
8 if val is None:
10 return []
9 return []
11 else:
10 else:
12 return [val]
11 return [val]
13
12
14 class namespaces(object):
13 class namespaces(object):
15 """
14 """
16 provides an interface to register a generic many-to-many mapping between
15 provides an interface to register a generic many-to-many mapping between
17 some (namespaced) names and nodes. The goal here is to control the
16 some (namespaced) names and nodes. The goal here is to control the
18 pollution of jamming things into tags or bookmarks (in extension-land) and
17 pollution of jamming things into tags or bookmarks (in extension-land) and
19 to simplify internal bits of mercurial: log output, tab completion, etc.
18 to simplify internal bits of mercurial: log output, tab completion, etc.
20
19
21 More precisely, we define a list of names (the namespace) and a mapping of
20 More precisely, we define a list of names (the namespace) and a mapping of
22 names to nodes. This name mapping returns a list of nodes.
21 names to nodes. This name mapping returns a list of nodes.
23
22
24 Furthermore, each name mapping will be passed a name to lookup which might
23 Furthermore, each name mapping will be passed a name to lookup which might
25 not be in its domain. In this case, each method should return an empty list
24 not be in its domain. In this case, each method should return an empty list
26 and not raise an error.
25 and not raise an error.
27
26
28 We'll have a dictionary '_names' where each key is a namespace and
27 We'll have a dictionary '_names' where each key is a namespace and
29 its value is a dictionary of functions:
28 its value is a dictionary of functions:
30 'namemap': function that takes a name and returns a list of nodes
29 'namemap': function that takes a name and returns a list of nodes
31 """
30 """
32
31
33 _names_version = 0
32 _names_version = 0
34
33
35 def __init__(self, repo):
34 def __init__(self):
36 self._names = util.sortdict()
35 self._names = util.sortdict()
37 self._repo = weakref.ref(repo)
38
36
39 # we need current mercurial named objects (bookmarks, tags, and
37 # we need current mercurial named objects (bookmarks, tags, and
40 # branches) to be initialized somewhere, so that place is here
38 # branches) to be initialized somewhere, so that place is here
41 self.addnamespace("bookmarks",
39 self.addnamespace("bookmarks",
42 lambda repo, name: tolist(repo._bookmarks.get(name)))
40 lambda repo, name: tolist(repo._bookmarks.get(name)))
43
41
44 @property
45 def repo(self):
46 return self._repo()
47
48 def addnamespace(self, namespace, namemap, order=None):
42 def addnamespace(self, namespace, namemap, order=None):
49 """
43 """
50 register a namespace
44 register a namespace
51
45
52 namespace: the name to be registered (in plural form)
46 namespace: the name to be registered (in plural form)
53 namemap: function that inputs a node, output name(s)
47 namemap: function that inputs a node, output name(s)
54 order: optional argument to specify the order of namespaces
48 order: optional argument to specify the order of namespaces
55 (e.g. 'branches' should be listed before 'bookmarks')
49 (e.g. 'branches' should be listed before 'bookmarks')
56 """
50 """
57 val = {'namemap': namemap}
51 val = {'namemap': namemap}
58 if order is not None:
52 if order is not None:
59 self._names.insert(order, namespace, val)
53 self._names.insert(order, namespace, val)
60 else:
54 else:
61 self._names[namespace] = val
55 self._names[namespace] = val
62
56
63 def singlenode(self, name):
57 def singlenode(self, repo, name):
64 """
58 """
65 Return the 'best' node for the given name. Best means the first node
59 Return the 'best' node for the given name. Best means the first node
66 in the first nonempty list returned by a name-to-nodes mapping function
60 in the first nonempty list returned by a name-to-nodes mapping function
67 in the defined precedence order.
61 in the defined precedence order.
68
62
69 Raises a KeyError if there is no such node.
63 Raises a KeyError if there is no such node.
70 """
64 """
71 for ns, v in self._names.iteritems():
65 for ns, v in self._names.iteritems():
72 n = v['namemap'](self.repo, name)
66 n = v['namemap'](repo, name)
73 if n:
67 if n:
74 # return max revision number
68 # return max revision number
75 if len(n) > 1:
69 if len(n) > 1:
76 cl = self.repo.changelog
70 cl = repo.changelog
77 maxrev = max(cl.rev(node) for node in n)
71 maxrev = max(cl.rev(node) for node in n)
78 return cl.node(maxrev)
72 return cl.node(maxrev)
79 return n[0]
73 return n[0]
80 raise KeyError(_('no such name: %s') % name)
74 raise KeyError(_('no such name: %s') % name)
@@ -1,166 +1,166 b''
1 # statichttprepo.py - simple http repository class for mercurial
1 # statichttprepo.py - simple http repository class for mercurial
2 #
2 #
3 # This provides read-only repo access to repositories exported via static http
3 # This provides read-only repo access to repositories exported via static http
4 #
4 #
5 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 from i18n import _
10 from i18n import _
11 import changelog, byterange, url, error, namespaces
11 import changelog, byterange, url, error, namespaces
12 import localrepo, manifest, util, scmutil, store
12 import localrepo, manifest, util, scmutil, store
13 import urllib, urllib2, errno, os
13 import urllib, urllib2, errno, os
14
14
15 class httprangereader(object):
15 class httprangereader(object):
16 def __init__(self, url, opener):
16 def __init__(self, url, opener):
17 # we assume opener has HTTPRangeHandler
17 # we assume opener has HTTPRangeHandler
18 self.url = url
18 self.url = url
19 self.pos = 0
19 self.pos = 0
20 self.opener = opener
20 self.opener = opener
21 self.name = url
21 self.name = url
22 def seek(self, pos):
22 def seek(self, pos):
23 self.pos = pos
23 self.pos = pos
24 def read(self, bytes=None):
24 def read(self, bytes=None):
25 req = urllib2.Request(self.url)
25 req = urllib2.Request(self.url)
26 end = ''
26 end = ''
27 if bytes:
27 if bytes:
28 end = self.pos + bytes - 1
28 end = self.pos + bytes - 1
29 if self.pos or end:
29 if self.pos or end:
30 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
30 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
31
31
32 try:
32 try:
33 f = self.opener.open(req)
33 f = self.opener.open(req)
34 data = f.read()
34 data = f.read()
35 # Python 2.6+ defines a getcode() function, and 2.4 and
35 # Python 2.6+ defines a getcode() function, and 2.4 and
36 # 2.5 appear to always have an undocumented code attribute
36 # 2.5 appear to always have an undocumented code attribute
37 # set. If we can't read either of those, fall back to 206
37 # set. If we can't read either of those, fall back to 206
38 # and hope for the best.
38 # and hope for the best.
39 code = getattr(f, 'getcode', lambda : getattr(f, 'code', 206))()
39 code = getattr(f, 'getcode', lambda : getattr(f, 'code', 206))()
40 except urllib2.HTTPError, inst:
40 except urllib2.HTTPError, inst:
41 num = inst.code == 404 and errno.ENOENT or None
41 num = inst.code == 404 and errno.ENOENT or None
42 raise IOError(num, inst)
42 raise IOError(num, inst)
43 except urllib2.URLError, inst:
43 except urllib2.URLError, inst:
44 raise IOError(None, inst.reason[1])
44 raise IOError(None, inst.reason[1])
45
45
46 if code == 200:
46 if code == 200:
47 # HTTPRangeHandler does nothing if remote does not support
47 # HTTPRangeHandler does nothing if remote does not support
48 # Range headers and returns the full entity. Let's slice it.
48 # Range headers and returns the full entity. Let's slice it.
49 if bytes:
49 if bytes:
50 data = data[self.pos:self.pos + bytes]
50 data = data[self.pos:self.pos + bytes]
51 else:
51 else:
52 data = data[self.pos:]
52 data = data[self.pos:]
53 elif bytes:
53 elif bytes:
54 data = data[:bytes]
54 data = data[:bytes]
55 self.pos += len(data)
55 self.pos += len(data)
56 return data
56 return data
57 def readlines(self):
57 def readlines(self):
58 return self.read().splitlines(True)
58 return self.read().splitlines(True)
59 def __iter__(self):
59 def __iter__(self):
60 return iter(self.readlines())
60 return iter(self.readlines())
61 def close(self):
61 def close(self):
62 pass
62 pass
63
63
64 def build_opener(ui, authinfo):
64 def build_opener(ui, authinfo):
65 # urllib cannot handle URLs with embedded user or passwd
65 # urllib cannot handle URLs with embedded user or passwd
66 urlopener = url.opener(ui, authinfo)
66 urlopener = url.opener(ui, authinfo)
67 urlopener.add_handler(byterange.HTTPRangeHandler())
67 urlopener.add_handler(byterange.HTTPRangeHandler())
68
68
69 class statichttpvfs(scmutil.abstractvfs):
69 class statichttpvfs(scmutil.abstractvfs):
70 def __init__(self, base):
70 def __init__(self, base):
71 self.base = base
71 self.base = base
72
72
73 def __call__(self, path, mode='r', *args, **kw):
73 def __call__(self, path, mode='r', *args, **kw):
74 if mode not in ('r', 'rb'):
74 if mode not in ('r', 'rb'):
75 raise IOError('Permission denied')
75 raise IOError('Permission denied')
76 f = "/".join((self.base, urllib.quote(path)))
76 f = "/".join((self.base, urllib.quote(path)))
77 return httprangereader(f, urlopener)
77 return httprangereader(f, urlopener)
78
78
79 def join(self, path):
79 def join(self, path):
80 if path:
80 if path:
81 return os.path.join(self.base, path)
81 return os.path.join(self.base, path)
82 else:
82 else:
83 return self.base
83 return self.base
84
84
85 return statichttpvfs
85 return statichttpvfs
86
86
87 class statichttppeer(localrepo.localpeer):
87 class statichttppeer(localrepo.localpeer):
88 def local(self):
88 def local(self):
89 return None
89 return None
90 def canpush(self):
90 def canpush(self):
91 return False
91 return False
92
92
93 class statichttprepository(localrepo.localrepository):
93 class statichttprepository(localrepo.localrepository):
94 supported = localrepo.localrepository._basesupported
94 supported = localrepo.localrepository._basesupported
95
95
96 def __init__(self, ui, path):
96 def __init__(self, ui, path):
97 self._url = path
97 self._url = path
98 self.ui = ui
98 self.ui = ui
99
99
100 self.root = path
100 self.root = path
101 u = util.url(path.rstrip('/') + "/.hg")
101 u = util.url(path.rstrip('/') + "/.hg")
102 self.path, authinfo = u.authinfo()
102 self.path, authinfo = u.authinfo()
103
103
104 opener = build_opener(ui, authinfo)
104 opener = build_opener(ui, authinfo)
105 self.opener = opener(self.path)
105 self.opener = opener(self.path)
106 self.vfs = self.opener
106 self.vfs = self.opener
107 self._phasedefaults = []
107 self._phasedefaults = []
108
108
109 self.names = namespaces.namespaces(self)
109 self.names = namespaces.namespaces()
110
110
111 try:
111 try:
112 requirements = scmutil.readrequires(self.opener, self.supported)
112 requirements = scmutil.readrequires(self.opener, self.supported)
113 except IOError, inst:
113 except IOError, inst:
114 if inst.errno != errno.ENOENT:
114 if inst.errno != errno.ENOENT:
115 raise
115 raise
116 requirements = set()
116 requirements = set()
117
117
118 # check if it is a non-empty old-style repository
118 # check if it is a non-empty old-style repository
119 try:
119 try:
120 fp = self.opener("00changelog.i")
120 fp = self.opener("00changelog.i")
121 fp.read(1)
121 fp.read(1)
122 fp.close()
122 fp.close()
123 except IOError, inst:
123 except IOError, inst:
124 if inst.errno != errno.ENOENT:
124 if inst.errno != errno.ENOENT:
125 raise
125 raise
126 # we do not care about empty old-style repositories here
126 # we do not care about empty old-style repositories here
127 msg = _("'%s' does not appear to be an hg repository") % path
127 msg = _("'%s' does not appear to be an hg repository") % path
128 raise error.RepoError(msg)
128 raise error.RepoError(msg)
129
129
130 # setup store
130 # setup store
131 self.store = store.store(requirements, self.path, opener)
131 self.store = store.store(requirements, self.path, opener)
132 self.spath = self.store.path
132 self.spath = self.store.path
133 self.sopener = self.store.opener
133 self.sopener = self.store.opener
134 self.svfs = self.sopener
134 self.svfs = self.sopener
135 self.sjoin = self.store.join
135 self.sjoin = self.store.join
136 self._filecache = {}
136 self._filecache = {}
137 self.requirements = requirements
137 self.requirements = requirements
138
138
139 self.manifest = manifest.manifest(self.sopener)
139 self.manifest = manifest.manifest(self.sopener)
140 self.changelog = changelog.changelog(self.sopener)
140 self.changelog = changelog.changelog(self.sopener)
141 self._tags = None
141 self._tags = None
142 self.nodetagscache = None
142 self.nodetagscache = None
143 self._branchcaches = {}
143 self._branchcaches = {}
144 self.encodepats = None
144 self.encodepats = None
145 self.decodepats = None
145 self.decodepats = None
146
146
147 def _restrictcapabilities(self, caps):
147 def _restrictcapabilities(self, caps):
148 caps = super(statichttprepository, self)._restrictcapabilities(caps)
148 caps = super(statichttprepository, self)._restrictcapabilities(caps)
149 return caps.difference(["pushkey"])
149 return caps.difference(["pushkey"])
150
150
151 def url(self):
151 def url(self):
152 return self._url
152 return self._url
153
153
154 def local(self):
154 def local(self):
155 return False
155 return False
156
156
157 def peer(self):
157 def peer(self):
158 return statichttppeer(self)
158 return statichttppeer(self)
159
159
160 def lock(self, wait=True):
160 def lock(self, wait=True):
161 raise util.Abort(_('cannot lock static-http repository'))
161 raise util.Abort(_('cannot lock static-http repository'))
162
162
163 def instance(ui, path, create):
163 def instance(ui, path, create):
164 if create:
164 if create:
165 raise util.Abort(_('cannot create new static-http repository'))
165 raise util.Abort(_('cannot create new static-http repository'))
166 return statichttprepository(ui, path[7:])
166 return statichttprepository(ui, path[7:])
General Comments 0
You need to be logged in to leave comments. Login now