##// END OF EJS Templates
transaction: pass the name of the "undo" journal to the transaction...
Pierre-Yves David -
r23903:426607be default
parent child Browse files
Show More
@@ -1,1852 +1,1853 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()
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.svfs.options = dict((r, 1) for r in requirements
318 self.svfs.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.svfs.options['chunkcachesize'] = chunkcachesize
322 self.svfs.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.svfs.options['maxchainlen'] = maxchainlen
325 self.svfs.options['maxchainlen'] = maxchainlen
326
326
327 def _writerequirements(self):
327 def _writerequirements(self):
328 reqfile = self.vfs("requires", "w")
328 reqfile = self.vfs("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.svfs, readonly=readonly,
417 store = obsolete.obsstore(self.svfs, 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.svfs)
427 c = changelog.changelog(self.svfs)
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.svfs)
436 return manifest.manifest(self.svfs)
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.vfs, self.ui, self.root, validate)
452 return dirstate.dirstate(self.vfs, 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 if isinstance(changeid, slice):
457 if isinstance(changeid, slice):
458 return [context.changectx(self, i)
458 return [context.changectx(self, i)
459 for i in xrange(*changeid.indices(len(self)))
459 for i in xrange(*changeid.indices(len(self)))
460 if i not in self.changelog.filteredrevs]
460 if i not in self.changelog.filteredrevs]
461 return context.changectx(self, changeid)
461 return context.changectx(self, changeid)
462
462
463 def __contains__(self, changeid):
463 def __contains__(self, changeid):
464 try:
464 try:
465 return bool(self.lookup(changeid))
465 return bool(self.lookup(changeid))
466 except error.RepoLookupError:
466 except error.RepoLookupError:
467 return False
467 return False
468
468
469 def __nonzero__(self):
469 def __nonzero__(self):
470 return True
470 return True
471
471
472 def __len__(self):
472 def __len__(self):
473 return len(self.changelog)
473 return len(self.changelog)
474
474
475 def __iter__(self):
475 def __iter__(self):
476 return iter(self.changelog)
476 return iter(self.changelog)
477
477
478 def revs(self, expr, *args):
478 def revs(self, expr, *args):
479 '''Return a list of revisions matching the given revset'''
479 '''Return a list of revisions matching the given revset'''
480 expr = revset.formatspec(expr, *args)
480 expr = revset.formatspec(expr, *args)
481 m = revset.match(None, expr)
481 m = revset.match(None, expr)
482 return m(self, revset.spanset(self))
482 return m(self, revset.spanset(self))
483
483
484 def set(self, expr, *args):
484 def set(self, expr, *args):
485 '''
485 '''
486 Yield a context for each matching revision, after doing arg
486 Yield a context for each matching revision, after doing arg
487 replacement via revset.formatspec
487 replacement via revset.formatspec
488 '''
488 '''
489 for r in self.revs(expr, *args):
489 for r in self.revs(expr, *args):
490 yield self[r]
490 yield self[r]
491
491
492 def url(self):
492 def url(self):
493 return 'file:' + self.root
493 return 'file:' + self.root
494
494
495 def hook(self, name, throw=False, **args):
495 def hook(self, name, throw=False, **args):
496 """Call a hook, passing this repo instance.
496 """Call a hook, passing this repo instance.
497
497
498 This a convenience method to aid invoking hooks. Extensions likely
498 This a convenience method to aid invoking hooks. Extensions likely
499 won't call this unless they have registered a custom hook or are
499 won't call this unless they have registered a custom hook or are
500 replacing code that is expected to call a hook.
500 replacing code that is expected to call a hook.
501 """
501 """
502 return hook.hook(self.ui, self, name, throw, **args)
502 return hook.hook(self.ui, self, name, throw, **args)
503
503
504 @unfilteredmethod
504 @unfilteredmethod
505 def _tag(self, names, node, message, local, user, date, extra={},
505 def _tag(self, names, node, message, local, user, date, extra={},
506 editor=False):
506 editor=False):
507 if isinstance(names, str):
507 if isinstance(names, str):
508 names = (names,)
508 names = (names,)
509
509
510 branches = self.branchmap()
510 branches = self.branchmap()
511 for name in names:
511 for name in names:
512 self.hook('pretag', throw=True, node=hex(node), tag=name,
512 self.hook('pretag', throw=True, node=hex(node), tag=name,
513 local=local)
513 local=local)
514 if name in branches:
514 if name in branches:
515 self.ui.warn(_("warning: tag %s conflicts with existing"
515 self.ui.warn(_("warning: tag %s conflicts with existing"
516 " branch name\n") % name)
516 " branch name\n") % name)
517
517
518 def writetags(fp, names, munge, prevtags):
518 def writetags(fp, names, munge, prevtags):
519 fp.seek(0, 2)
519 fp.seek(0, 2)
520 if prevtags and prevtags[-1] != '\n':
520 if prevtags and prevtags[-1] != '\n':
521 fp.write('\n')
521 fp.write('\n')
522 for name in names:
522 for name in names:
523 m = munge and munge(name) or name
523 m = munge and munge(name) or name
524 if (self._tagscache.tagtypes and
524 if (self._tagscache.tagtypes and
525 name in self._tagscache.tagtypes):
525 name in self._tagscache.tagtypes):
526 old = self.tags().get(name, nullid)
526 old = self.tags().get(name, nullid)
527 fp.write('%s %s\n' % (hex(old), m))
527 fp.write('%s %s\n' % (hex(old), m))
528 fp.write('%s %s\n' % (hex(node), m))
528 fp.write('%s %s\n' % (hex(node), m))
529 fp.close()
529 fp.close()
530
530
531 prevtags = ''
531 prevtags = ''
532 if local:
532 if local:
533 try:
533 try:
534 fp = self.vfs('localtags', 'r+')
534 fp = self.vfs('localtags', 'r+')
535 except IOError:
535 except IOError:
536 fp = self.vfs('localtags', 'a')
536 fp = self.vfs('localtags', 'a')
537 else:
537 else:
538 prevtags = fp.read()
538 prevtags = fp.read()
539
539
540 # local tags are stored in the current charset
540 # local tags are stored in the current charset
541 writetags(fp, names, None, prevtags)
541 writetags(fp, names, None, prevtags)
542 for name in names:
542 for name in names:
543 self.hook('tag', node=hex(node), tag=name, local=local)
543 self.hook('tag', node=hex(node), tag=name, local=local)
544 return
544 return
545
545
546 try:
546 try:
547 fp = self.wfile('.hgtags', 'rb+')
547 fp = self.wfile('.hgtags', 'rb+')
548 except IOError, e:
548 except IOError, e:
549 if e.errno != errno.ENOENT:
549 if e.errno != errno.ENOENT:
550 raise
550 raise
551 fp = self.wfile('.hgtags', 'ab')
551 fp = self.wfile('.hgtags', 'ab')
552 else:
552 else:
553 prevtags = fp.read()
553 prevtags = fp.read()
554
554
555 # committed tags are stored in UTF-8
555 # committed tags are stored in UTF-8
556 writetags(fp, names, encoding.fromlocal, prevtags)
556 writetags(fp, names, encoding.fromlocal, prevtags)
557
557
558 fp.close()
558 fp.close()
559
559
560 self.invalidatecaches()
560 self.invalidatecaches()
561
561
562 if '.hgtags' not in self.dirstate:
562 if '.hgtags' not in self.dirstate:
563 self[None].add(['.hgtags'])
563 self[None].add(['.hgtags'])
564
564
565 m = matchmod.exact(self.root, '', ['.hgtags'])
565 m = matchmod.exact(self.root, '', ['.hgtags'])
566 tagnode = self.commit(message, user, date, extra=extra, match=m,
566 tagnode = self.commit(message, user, date, extra=extra, match=m,
567 editor=editor)
567 editor=editor)
568
568
569 for name in names:
569 for name in names:
570 self.hook('tag', node=hex(node), tag=name, local=local)
570 self.hook('tag', node=hex(node), tag=name, local=local)
571
571
572 return tagnode
572 return tagnode
573
573
574 def tag(self, names, node, message, local, user, date, editor=False):
574 def tag(self, names, node, message, local, user, date, editor=False):
575 '''tag a revision with one or more symbolic names.
575 '''tag a revision with one or more symbolic names.
576
576
577 names is a list of strings or, when adding a single tag, names may be a
577 names is a list of strings or, when adding a single tag, names may be a
578 string.
578 string.
579
579
580 if local is True, the tags are stored in a per-repository file.
580 if local is True, the tags are stored in a per-repository file.
581 otherwise, they are stored in the .hgtags file, and a new
581 otherwise, they are stored in the .hgtags file, and a new
582 changeset is committed with the change.
582 changeset is committed with the change.
583
583
584 keyword arguments:
584 keyword arguments:
585
585
586 local: whether to store tags in non-version-controlled file
586 local: whether to store tags in non-version-controlled file
587 (default False)
587 (default False)
588
588
589 message: commit message to use if committing
589 message: commit message to use if committing
590
590
591 user: name of user to use if committing
591 user: name of user to use if committing
592
592
593 date: date tuple to use if committing'''
593 date: date tuple to use if committing'''
594
594
595 if not local:
595 if not local:
596 m = matchmod.exact(self.root, '', ['.hgtags'])
596 m = matchmod.exact(self.root, '', ['.hgtags'])
597 if util.any(self.status(match=m, unknown=True, ignored=True)):
597 if util.any(self.status(match=m, unknown=True, ignored=True)):
598 raise util.Abort(_('working copy of .hgtags is changed'),
598 raise util.Abort(_('working copy of .hgtags is changed'),
599 hint=_('please commit .hgtags manually'))
599 hint=_('please commit .hgtags manually'))
600
600
601 self.tags() # instantiate the cache
601 self.tags() # instantiate the cache
602 self._tag(names, node, message, local, user, date, editor=editor)
602 self._tag(names, node, message, local, user, date, editor=editor)
603
603
604 @filteredpropertycache
604 @filteredpropertycache
605 def _tagscache(self):
605 def _tagscache(self):
606 '''Returns a tagscache object that contains various tags related
606 '''Returns a tagscache object that contains various tags related
607 caches.'''
607 caches.'''
608
608
609 # This simplifies its cache management by having one decorated
609 # This simplifies its cache management by having one decorated
610 # function (this one) and the rest simply fetch things from it.
610 # function (this one) and the rest simply fetch things from it.
611 class tagscache(object):
611 class tagscache(object):
612 def __init__(self):
612 def __init__(self):
613 # These two define the set of tags for this repository. tags
613 # These two define the set of tags for this repository. tags
614 # maps tag name to node; tagtypes maps tag name to 'global' or
614 # maps tag name to node; tagtypes maps tag name to 'global' or
615 # 'local'. (Global tags are defined by .hgtags across all
615 # 'local'. (Global tags are defined by .hgtags across all
616 # heads, and local tags are defined in .hg/localtags.)
616 # heads, and local tags are defined in .hg/localtags.)
617 # They constitute the in-memory cache of tags.
617 # They constitute the in-memory cache of tags.
618 self.tags = self.tagtypes = None
618 self.tags = self.tagtypes = None
619
619
620 self.nodetagscache = self.tagslist = None
620 self.nodetagscache = self.tagslist = None
621
621
622 cache = tagscache()
622 cache = tagscache()
623 cache.tags, cache.tagtypes = self._findtags()
623 cache.tags, cache.tagtypes = self._findtags()
624
624
625 return cache
625 return cache
626
626
627 def tags(self):
627 def tags(self):
628 '''return a mapping of tag to node'''
628 '''return a mapping of tag to node'''
629 t = {}
629 t = {}
630 if self.changelog.filteredrevs:
630 if self.changelog.filteredrevs:
631 tags, tt = self._findtags()
631 tags, tt = self._findtags()
632 else:
632 else:
633 tags = self._tagscache.tags
633 tags = self._tagscache.tags
634 for k, v in tags.iteritems():
634 for k, v in tags.iteritems():
635 try:
635 try:
636 # ignore tags to unknown nodes
636 # ignore tags to unknown nodes
637 self.changelog.rev(v)
637 self.changelog.rev(v)
638 t[k] = v
638 t[k] = v
639 except (error.LookupError, ValueError):
639 except (error.LookupError, ValueError):
640 pass
640 pass
641 return t
641 return t
642
642
643 def _findtags(self):
643 def _findtags(self):
644 '''Do the hard work of finding tags. Return a pair of dicts
644 '''Do the hard work of finding tags. Return a pair of dicts
645 (tags, tagtypes) where tags maps tag name to node, and tagtypes
645 (tags, tagtypes) where tags maps tag name to node, and tagtypes
646 maps tag name to a string like \'global\' or \'local\'.
646 maps tag name to a string like \'global\' or \'local\'.
647 Subclasses or extensions are free to add their own tags, but
647 Subclasses or extensions are free to add their own tags, but
648 should be aware that the returned dicts will be retained for the
648 should be aware that the returned dicts will be retained for the
649 duration of the localrepo object.'''
649 duration of the localrepo object.'''
650
650
651 # XXX what tagtype should subclasses/extensions use? Currently
651 # XXX what tagtype should subclasses/extensions use? Currently
652 # mq and bookmarks add tags, but do not set the tagtype at all.
652 # mq and bookmarks add tags, but do not set the tagtype at all.
653 # Should each extension invent its own tag type? Should there
653 # Should each extension invent its own tag type? Should there
654 # be one tagtype for all such "virtual" tags? Or is the status
654 # be one tagtype for all such "virtual" tags? Or is the status
655 # quo fine?
655 # quo fine?
656
656
657 alltags = {} # map tag name to (node, hist)
657 alltags = {} # map tag name to (node, hist)
658 tagtypes = {}
658 tagtypes = {}
659
659
660 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
660 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
661 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
661 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
662
662
663 # Build the return dicts. Have to re-encode tag names because
663 # Build the return dicts. Have to re-encode tag names because
664 # the tags module always uses UTF-8 (in order not to lose info
664 # the tags module always uses UTF-8 (in order not to lose info
665 # writing to the cache), but the rest of Mercurial wants them in
665 # writing to the cache), but the rest of Mercurial wants them in
666 # local encoding.
666 # local encoding.
667 tags = {}
667 tags = {}
668 for (name, (node, hist)) in alltags.iteritems():
668 for (name, (node, hist)) in alltags.iteritems():
669 if node != nullid:
669 if node != nullid:
670 tags[encoding.tolocal(name)] = node
670 tags[encoding.tolocal(name)] = node
671 tags['tip'] = self.changelog.tip()
671 tags['tip'] = self.changelog.tip()
672 tagtypes = dict([(encoding.tolocal(name), value)
672 tagtypes = dict([(encoding.tolocal(name), value)
673 for (name, value) in tagtypes.iteritems()])
673 for (name, value) in tagtypes.iteritems()])
674 return (tags, tagtypes)
674 return (tags, tagtypes)
675
675
676 def tagtype(self, tagname):
676 def tagtype(self, tagname):
677 '''
677 '''
678 return the type of the given tag. result can be:
678 return the type of the given tag. result can be:
679
679
680 'local' : a local tag
680 'local' : a local tag
681 'global' : a global tag
681 'global' : a global tag
682 None : tag does not exist
682 None : tag does not exist
683 '''
683 '''
684
684
685 return self._tagscache.tagtypes.get(tagname)
685 return self._tagscache.tagtypes.get(tagname)
686
686
687 def tagslist(self):
687 def tagslist(self):
688 '''return a list of tags ordered by revision'''
688 '''return a list of tags ordered by revision'''
689 if not self._tagscache.tagslist:
689 if not self._tagscache.tagslist:
690 l = []
690 l = []
691 for t, n in self.tags().iteritems():
691 for t, n in self.tags().iteritems():
692 l.append((self.changelog.rev(n), t, n))
692 l.append((self.changelog.rev(n), t, n))
693 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
693 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
694
694
695 return self._tagscache.tagslist
695 return self._tagscache.tagslist
696
696
697 def nodetags(self, node):
697 def nodetags(self, node):
698 '''return the tags associated with a node'''
698 '''return the tags associated with a node'''
699 if not self._tagscache.nodetagscache:
699 if not self._tagscache.nodetagscache:
700 nodetagscache = {}
700 nodetagscache = {}
701 for t, n in self._tagscache.tags.iteritems():
701 for t, n in self._tagscache.tags.iteritems():
702 nodetagscache.setdefault(n, []).append(t)
702 nodetagscache.setdefault(n, []).append(t)
703 for tags in nodetagscache.itervalues():
703 for tags in nodetagscache.itervalues():
704 tags.sort()
704 tags.sort()
705 self._tagscache.nodetagscache = nodetagscache
705 self._tagscache.nodetagscache = nodetagscache
706 return self._tagscache.nodetagscache.get(node, [])
706 return self._tagscache.nodetagscache.get(node, [])
707
707
708 def nodebookmarks(self, node):
708 def nodebookmarks(self, node):
709 marks = []
709 marks = []
710 for bookmark, n in self._bookmarks.iteritems():
710 for bookmark, n in self._bookmarks.iteritems():
711 if n == node:
711 if n == node:
712 marks.append(bookmark)
712 marks.append(bookmark)
713 return sorted(marks)
713 return sorted(marks)
714
714
715 def branchmap(self):
715 def branchmap(self):
716 '''returns a dictionary {branch: [branchheads]} with branchheads
716 '''returns a dictionary {branch: [branchheads]} with branchheads
717 ordered by increasing revision number'''
717 ordered by increasing revision number'''
718 branchmap.updatecache(self)
718 branchmap.updatecache(self)
719 return self._branchcaches[self.filtername]
719 return self._branchcaches[self.filtername]
720
720
721 def branchtip(self, branch, ignoremissing=False):
721 def branchtip(self, branch, ignoremissing=False):
722 '''return the tip node for a given branch
722 '''return the tip node for a given branch
723
723
724 If ignoremissing is True, then this method will not raise an error.
724 If ignoremissing is True, then this method will not raise an error.
725 This is helpful for callers that only expect None for a missing branch
725 This is helpful for callers that only expect None for a missing branch
726 (e.g. namespace).
726 (e.g. namespace).
727
727
728 '''
728 '''
729 try:
729 try:
730 return self.branchmap().branchtip(branch)
730 return self.branchmap().branchtip(branch)
731 except KeyError:
731 except KeyError:
732 if not ignoremissing:
732 if not ignoremissing:
733 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
733 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
734 else:
734 else:
735 pass
735 pass
736
736
737 def lookup(self, key):
737 def lookup(self, key):
738 return self[key].node()
738 return self[key].node()
739
739
740 def lookupbranch(self, key, remote=None):
740 def lookupbranch(self, key, remote=None):
741 repo = remote or self
741 repo = remote or self
742 if key in repo.branchmap():
742 if key in repo.branchmap():
743 return key
743 return key
744
744
745 repo = (remote and remote.local()) and remote or self
745 repo = (remote and remote.local()) and remote or self
746 return repo[key].branch()
746 return repo[key].branch()
747
747
748 def known(self, nodes):
748 def known(self, nodes):
749 nm = self.changelog.nodemap
749 nm = self.changelog.nodemap
750 pc = self._phasecache
750 pc = self._phasecache
751 result = []
751 result = []
752 for n in nodes:
752 for n in nodes:
753 r = nm.get(n)
753 r = nm.get(n)
754 resp = not (r is None or pc.phase(self, r) >= phases.secret)
754 resp = not (r is None or pc.phase(self, r) >= phases.secret)
755 result.append(resp)
755 result.append(resp)
756 return result
756 return result
757
757
758 def local(self):
758 def local(self):
759 return self
759 return self
760
760
761 def cancopy(self):
761 def cancopy(self):
762 # so statichttprepo's override of local() works
762 # so statichttprepo's override of local() works
763 if not self.local():
763 if not self.local():
764 return False
764 return False
765 if not self.ui.configbool('phases', 'publish', True):
765 if not self.ui.configbool('phases', 'publish', True):
766 return True
766 return True
767 # if publishing we can't copy if there is filtered content
767 # if publishing we can't copy if there is filtered content
768 return not self.filtered('visible').changelog.filteredrevs
768 return not self.filtered('visible').changelog.filteredrevs
769
769
770 def shared(self):
770 def shared(self):
771 '''the type of shared repository (None if not shared)'''
771 '''the type of shared repository (None if not shared)'''
772 if self.sharedpath != self.path:
772 if self.sharedpath != self.path:
773 return 'store'
773 return 'store'
774 return None
774 return None
775
775
776 def join(self, f, *insidef):
776 def join(self, f, *insidef):
777 return self.vfs.join(os.path.join(f, *insidef))
777 return self.vfs.join(os.path.join(f, *insidef))
778
778
779 def wjoin(self, f, *insidef):
779 def wjoin(self, f, *insidef):
780 return self.vfs.reljoin(self.root, f, *insidef)
780 return self.vfs.reljoin(self.root, f, *insidef)
781
781
782 def file(self, f):
782 def file(self, f):
783 if f[0] == '/':
783 if f[0] == '/':
784 f = f[1:]
784 f = f[1:]
785 return filelog.filelog(self.svfs, f)
785 return filelog.filelog(self.svfs, f)
786
786
787 def changectx(self, changeid):
787 def changectx(self, changeid):
788 return self[changeid]
788 return self[changeid]
789
789
790 def parents(self, changeid=None):
790 def parents(self, changeid=None):
791 '''get list of changectxs for parents of changeid'''
791 '''get list of changectxs for parents of changeid'''
792 return self[changeid].parents()
792 return self[changeid].parents()
793
793
794 def setparents(self, p1, p2=nullid):
794 def setparents(self, p1, p2=nullid):
795 self.dirstate.beginparentchange()
795 self.dirstate.beginparentchange()
796 copies = self.dirstate.setparents(p1, p2)
796 copies = self.dirstate.setparents(p1, p2)
797 pctx = self[p1]
797 pctx = self[p1]
798 if copies:
798 if copies:
799 # Adjust copy records, the dirstate cannot do it, it
799 # Adjust copy records, the dirstate cannot do it, it
800 # requires access to parents manifests. Preserve them
800 # requires access to parents manifests. Preserve them
801 # only for entries added to first parent.
801 # only for entries added to first parent.
802 for f in copies:
802 for f in copies:
803 if f not in pctx and copies[f] in pctx:
803 if f not in pctx and copies[f] in pctx:
804 self.dirstate.copy(copies[f], f)
804 self.dirstate.copy(copies[f], f)
805 if p2 == nullid:
805 if p2 == nullid:
806 for f, s in sorted(self.dirstate.copies().items()):
806 for f, s in sorted(self.dirstate.copies().items()):
807 if f not in pctx and s not in pctx:
807 if f not in pctx and s not in pctx:
808 self.dirstate.copy(None, f)
808 self.dirstate.copy(None, f)
809 self.dirstate.endparentchange()
809 self.dirstate.endparentchange()
810
810
811 def filectx(self, path, changeid=None, fileid=None):
811 def filectx(self, path, changeid=None, fileid=None):
812 """changeid can be a changeset revision, node, or tag.
812 """changeid can be a changeset revision, node, or tag.
813 fileid can be a file revision or node."""
813 fileid can be a file revision or node."""
814 return context.filectx(self, path, changeid, fileid)
814 return context.filectx(self, path, changeid, fileid)
815
815
816 def getcwd(self):
816 def getcwd(self):
817 return self.dirstate.getcwd()
817 return self.dirstate.getcwd()
818
818
819 def pathto(self, f, cwd=None):
819 def pathto(self, f, cwd=None):
820 return self.dirstate.pathto(f, cwd)
820 return self.dirstate.pathto(f, cwd)
821
821
822 def wfile(self, f, mode='r'):
822 def wfile(self, f, mode='r'):
823 return self.wvfs(f, mode)
823 return self.wvfs(f, mode)
824
824
825 def _link(self, f):
825 def _link(self, f):
826 return self.wvfs.islink(f)
826 return self.wvfs.islink(f)
827
827
828 def _loadfilter(self, filter):
828 def _loadfilter(self, filter):
829 if filter not in self.filterpats:
829 if filter not in self.filterpats:
830 l = []
830 l = []
831 for pat, cmd in self.ui.configitems(filter):
831 for pat, cmd in self.ui.configitems(filter):
832 if cmd == '!':
832 if cmd == '!':
833 continue
833 continue
834 mf = matchmod.match(self.root, '', [pat])
834 mf = matchmod.match(self.root, '', [pat])
835 fn = None
835 fn = None
836 params = cmd
836 params = cmd
837 for name, filterfn in self._datafilters.iteritems():
837 for name, filterfn in self._datafilters.iteritems():
838 if cmd.startswith(name):
838 if cmd.startswith(name):
839 fn = filterfn
839 fn = filterfn
840 params = cmd[len(name):].lstrip()
840 params = cmd[len(name):].lstrip()
841 break
841 break
842 if not fn:
842 if not fn:
843 fn = lambda s, c, **kwargs: util.filter(s, c)
843 fn = lambda s, c, **kwargs: util.filter(s, c)
844 # Wrap old filters not supporting keyword arguments
844 # Wrap old filters not supporting keyword arguments
845 if not inspect.getargspec(fn)[2]:
845 if not inspect.getargspec(fn)[2]:
846 oldfn = fn
846 oldfn = fn
847 fn = lambda s, c, **kwargs: oldfn(s, c)
847 fn = lambda s, c, **kwargs: oldfn(s, c)
848 l.append((mf, fn, params))
848 l.append((mf, fn, params))
849 self.filterpats[filter] = l
849 self.filterpats[filter] = l
850 return self.filterpats[filter]
850 return self.filterpats[filter]
851
851
852 def _filter(self, filterpats, filename, data):
852 def _filter(self, filterpats, filename, data):
853 for mf, fn, cmd in filterpats:
853 for mf, fn, cmd in filterpats:
854 if mf(filename):
854 if mf(filename):
855 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
855 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
856 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
856 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
857 break
857 break
858
858
859 return data
859 return data
860
860
861 @unfilteredpropertycache
861 @unfilteredpropertycache
862 def _encodefilterpats(self):
862 def _encodefilterpats(self):
863 return self._loadfilter('encode')
863 return self._loadfilter('encode')
864
864
865 @unfilteredpropertycache
865 @unfilteredpropertycache
866 def _decodefilterpats(self):
866 def _decodefilterpats(self):
867 return self._loadfilter('decode')
867 return self._loadfilter('decode')
868
868
869 def adddatafilter(self, name, filter):
869 def adddatafilter(self, name, filter):
870 self._datafilters[name] = filter
870 self._datafilters[name] = filter
871
871
872 def wread(self, filename):
872 def wread(self, filename):
873 if self._link(filename):
873 if self._link(filename):
874 data = self.wvfs.readlink(filename)
874 data = self.wvfs.readlink(filename)
875 else:
875 else:
876 data = self.wvfs.read(filename)
876 data = self.wvfs.read(filename)
877 return self._filter(self._encodefilterpats, filename, data)
877 return self._filter(self._encodefilterpats, filename, data)
878
878
879 def wwrite(self, filename, data, flags):
879 def wwrite(self, filename, data, flags):
880 data = self._filter(self._decodefilterpats, filename, data)
880 data = self._filter(self._decodefilterpats, filename, data)
881 if 'l' in flags:
881 if 'l' in flags:
882 self.wvfs.symlink(data, filename)
882 self.wvfs.symlink(data, filename)
883 else:
883 else:
884 self.wvfs.write(filename, data)
884 self.wvfs.write(filename, data)
885 if 'x' in flags:
885 if 'x' in flags:
886 self.wvfs.setflags(filename, False, True)
886 self.wvfs.setflags(filename, False, True)
887
887
888 def wwritedata(self, filename, data):
888 def wwritedata(self, filename, data):
889 return self._filter(self._decodefilterpats, filename, data)
889 return self._filter(self._decodefilterpats, filename, data)
890
890
891 def currenttransaction(self):
891 def currenttransaction(self):
892 """return the current transaction or None if non exists"""
892 """return the current transaction or None if non exists"""
893 tr = self._transref and self._transref() or None
893 tr = self._transref and self._transref() or None
894 if tr and tr.running():
894 if tr and tr.running():
895 return tr
895 return tr
896 return None
896 return None
897
897
898 def transaction(self, desc, report=None):
898 def transaction(self, desc, report=None):
899 tr = self.currenttransaction()
899 tr = self.currenttransaction()
900 if tr is not None:
900 if tr is not None:
901 return tr.nest()
901 return tr.nest()
902
902
903 # abort here if the journal already exists
903 # abort here if the journal already exists
904 if self.svfs.exists("journal"):
904 if self.svfs.exists("journal"):
905 raise error.RepoError(
905 raise error.RepoError(
906 _("abandoned transaction found"),
906 _("abandoned transaction found"),
907 hint=_("run 'hg recover' to clean up transaction"))
907 hint=_("run 'hg recover' to clean up transaction"))
908
908
909 self._writejournal(desc)
909 self._writejournal(desc)
910 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
910 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
911 rp = report and report or self.ui.warn
911 rp = report and report or self.ui.warn
912 vfsmap = {'plain': self.vfs} # root of .hg/
912 vfsmap = {'plain': self.vfs} # root of .hg/
913 tr = transaction.transaction(rp, self.svfs, vfsmap,
913 tr = transaction.transaction(rp, self.svfs, vfsmap,
914 "journal",
914 "journal",
915 "undo",
915 aftertrans(renames),
916 aftertrans(renames),
916 self.store.createmode)
917 self.store.createmode)
917 # note: writing the fncache only during finalize mean that the file is
918 # note: writing the fncache only during finalize mean that the file is
918 # outdated when running hooks. As fncache is used for streaming clone,
919 # outdated when running hooks. As fncache is used for streaming clone,
919 # this is not expected to break anything that happen during the hooks.
920 # this is not expected to break anything that happen during the hooks.
920 tr.addfinalize('flush-fncache', self.store.write)
921 tr.addfinalize('flush-fncache', self.store.write)
921 self._transref = weakref.ref(tr)
922 self._transref = weakref.ref(tr)
922 return tr
923 return tr
923
924
924 def _journalfiles(self):
925 def _journalfiles(self):
925 return ((self.svfs, 'journal'),
926 return ((self.svfs, 'journal'),
926 (self.vfs, 'journal.dirstate'),
927 (self.vfs, 'journal.dirstate'),
927 (self.vfs, 'journal.branch'),
928 (self.vfs, 'journal.branch'),
928 (self.vfs, 'journal.desc'),
929 (self.vfs, 'journal.desc'),
929 (self.vfs, 'journal.bookmarks'),
930 (self.vfs, 'journal.bookmarks'),
930 (self.svfs, 'journal.phaseroots'))
931 (self.svfs, 'journal.phaseroots'))
931
932
932 def undofiles(self):
933 def undofiles(self):
933 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
934 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
934
935
935 def _writejournal(self, desc):
936 def _writejournal(self, desc):
936 self.vfs.write("journal.dirstate",
937 self.vfs.write("journal.dirstate",
937 self.vfs.tryread("dirstate"))
938 self.vfs.tryread("dirstate"))
938 self.vfs.write("journal.branch",
939 self.vfs.write("journal.branch",
939 encoding.fromlocal(self.dirstate.branch()))
940 encoding.fromlocal(self.dirstate.branch()))
940 self.vfs.write("journal.desc",
941 self.vfs.write("journal.desc",
941 "%d\n%s\n" % (len(self), desc))
942 "%d\n%s\n" % (len(self), desc))
942 self.vfs.write("journal.bookmarks",
943 self.vfs.write("journal.bookmarks",
943 self.vfs.tryread("bookmarks"))
944 self.vfs.tryread("bookmarks"))
944 self.svfs.write("journal.phaseroots",
945 self.svfs.write("journal.phaseroots",
945 self.svfs.tryread("phaseroots"))
946 self.svfs.tryread("phaseroots"))
946
947
947 def recover(self):
948 def recover(self):
948 lock = self.lock()
949 lock = self.lock()
949 try:
950 try:
950 if self.svfs.exists("journal"):
951 if self.svfs.exists("journal"):
951 self.ui.status(_("rolling back interrupted transaction\n"))
952 self.ui.status(_("rolling back interrupted transaction\n"))
952 vfsmap = {'': self.svfs,
953 vfsmap = {'': self.svfs,
953 'plain': self.vfs,}
954 'plain': self.vfs,}
954 transaction.rollback(self.svfs, vfsmap, "journal",
955 transaction.rollback(self.svfs, vfsmap, "journal",
955 self.ui.warn)
956 self.ui.warn)
956 self.invalidate()
957 self.invalidate()
957 return True
958 return True
958 else:
959 else:
959 self.ui.warn(_("no interrupted transaction available\n"))
960 self.ui.warn(_("no interrupted transaction available\n"))
960 return False
961 return False
961 finally:
962 finally:
962 lock.release()
963 lock.release()
963
964
964 def rollback(self, dryrun=False, force=False):
965 def rollback(self, dryrun=False, force=False):
965 wlock = lock = None
966 wlock = lock = None
966 try:
967 try:
967 wlock = self.wlock()
968 wlock = self.wlock()
968 lock = self.lock()
969 lock = self.lock()
969 if self.svfs.exists("undo"):
970 if self.svfs.exists("undo"):
970 return self._rollback(dryrun, force)
971 return self._rollback(dryrun, force)
971 else:
972 else:
972 self.ui.warn(_("no rollback information available\n"))
973 self.ui.warn(_("no rollback information available\n"))
973 return 1
974 return 1
974 finally:
975 finally:
975 release(lock, wlock)
976 release(lock, wlock)
976
977
977 @unfilteredmethod # Until we get smarter cache management
978 @unfilteredmethod # Until we get smarter cache management
978 def _rollback(self, dryrun, force):
979 def _rollback(self, dryrun, force):
979 ui = self.ui
980 ui = self.ui
980 try:
981 try:
981 args = self.vfs.read('undo.desc').splitlines()
982 args = self.vfs.read('undo.desc').splitlines()
982 (oldlen, desc, detail) = (int(args[0]), args[1], None)
983 (oldlen, desc, detail) = (int(args[0]), args[1], None)
983 if len(args) >= 3:
984 if len(args) >= 3:
984 detail = args[2]
985 detail = args[2]
985 oldtip = oldlen - 1
986 oldtip = oldlen - 1
986
987
987 if detail and ui.verbose:
988 if detail and ui.verbose:
988 msg = (_('repository tip rolled back to revision %s'
989 msg = (_('repository tip rolled back to revision %s'
989 ' (undo %s: %s)\n')
990 ' (undo %s: %s)\n')
990 % (oldtip, desc, detail))
991 % (oldtip, desc, detail))
991 else:
992 else:
992 msg = (_('repository tip rolled back to revision %s'
993 msg = (_('repository tip rolled back to revision %s'
993 ' (undo %s)\n')
994 ' (undo %s)\n')
994 % (oldtip, desc))
995 % (oldtip, desc))
995 except IOError:
996 except IOError:
996 msg = _('rolling back unknown transaction\n')
997 msg = _('rolling back unknown transaction\n')
997 desc = None
998 desc = None
998
999
999 if not force and self['.'] != self['tip'] and desc == 'commit':
1000 if not force and self['.'] != self['tip'] and desc == 'commit':
1000 raise util.Abort(
1001 raise util.Abort(
1001 _('rollback of last commit while not checked out '
1002 _('rollback of last commit while not checked out '
1002 'may lose data'), hint=_('use -f to force'))
1003 'may lose data'), hint=_('use -f to force'))
1003
1004
1004 ui.status(msg)
1005 ui.status(msg)
1005 if dryrun:
1006 if dryrun:
1006 return 0
1007 return 0
1007
1008
1008 parents = self.dirstate.parents()
1009 parents = self.dirstate.parents()
1009 self.destroying()
1010 self.destroying()
1010 vfsmap = {'plain': self.vfs, '': self.svfs}
1011 vfsmap = {'plain': self.vfs, '': self.svfs}
1011 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn)
1012 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn)
1012 if self.vfs.exists('undo.bookmarks'):
1013 if self.vfs.exists('undo.bookmarks'):
1013 self.vfs.rename('undo.bookmarks', 'bookmarks')
1014 self.vfs.rename('undo.bookmarks', 'bookmarks')
1014 if self.svfs.exists('undo.phaseroots'):
1015 if self.svfs.exists('undo.phaseroots'):
1015 self.svfs.rename('undo.phaseroots', 'phaseroots')
1016 self.svfs.rename('undo.phaseroots', 'phaseroots')
1016 self.invalidate()
1017 self.invalidate()
1017
1018
1018 parentgone = (parents[0] not in self.changelog.nodemap or
1019 parentgone = (parents[0] not in self.changelog.nodemap or
1019 parents[1] not in self.changelog.nodemap)
1020 parents[1] not in self.changelog.nodemap)
1020 if parentgone:
1021 if parentgone:
1021 self.vfs.rename('undo.dirstate', 'dirstate')
1022 self.vfs.rename('undo.dirstate', 'dirstate')
1022 try:
1023 try:
1023 branch = self.vfs.read('undo.branch')
1024 branch = self.vfs.read('undo.branch')
1024 self.dirstate.setbranch(encoding.tolocal(branch))
1025 self.dirstate.setbranch(encoding.tolocal(branch))
1025 except IOError:
1026 except IOError:
1026 ui.warn(_('named branch could not be reset: '
1027 ui.warn(_('named branch could not be reset: '
1027 'current branch is still \'%s\'\n')
1028 'current branch is still \'%s\'\n')
1028 % self.dirstate.branch())
1029 % self.dirstate.branch())
1029
1030
1030 self.dirstate.invalidate()
1031 self.dirstate.invalidate()
1031 parents = tuple([p.rev() for p in self.parents()])
1032 parents = tuple([p.rev() for p in self.parents()])
1032 if len(parents) > 1:
1033 if len(parents) > 1:
1033 ui.status(_('working directory now based on '
1034 ui.status(_('working directory now based on '
1034 'revisions %d and %d\n') % parents)
1035 'revisions %d and %d\n') % parents)
1035 else:
1036 else:
1036 ui.status(_('working directory now based on '
1037 ui.status(_('working directory now based on '
1037 'revision %d\n') % parents)
1038 'revision %d\n') % parents)
1038 # TODO: if we know which new heads may result from this rollback, pass
1039 # TODO: if we know which new heads may result from this rollback, pass
1039 # them to destroy(), which will prevent the branchhead cache from being
1040 # them to destroy(), which will prevent the branchhead cache from being
1040 # invalidated.
1041 # invalidated.
1041 self.destroyed()
1042 self.destroyed()
1042 return 0
1043 return 0
1043
1044
1044 def invalidatecaches(self):
1045 def invalidatecaches(self):
1045
1046
1046 if '_tagscache' in vars(self):
1047 if '_tagscache' in vars(self):
1047 # can't use delattr on proxy
1048 # can't use delattr on proxy
1048 del self.__dict__['_tagscache']
1049 del self.__dict__['_tagscache']
1049
1050
1050 self.unfiltered()._branchcaches.clear()
1051 self.unfiltered()._branchcaches.clear()
1051 self.invalidatevolatilesets()
1052 self.invalidatevolatilesets()
1052
1053
1053 def invalidatevolatilesets(self):
1054 def invalidatevolatilesets(self):
1054 self.filteredrevcache.clear()
1055 self.filteredrevcache.clear()
1055 obsolete.clearobscaches(self)
1056 obsolete.clearobscaches(self)
1056
1057
1057 def invalidatedirstate(self):
1058 def invalidatedirstate(self):
1058 '''Invalidates the dirstate, causing the next call to dirstate
1059 '''Invalidates the dirstate, causing the next call to dirstate
1059 to check if it was modified since the last time it was read,
1060 to check if it was modified since the last time it was read,
1060 rereading it if it has.
1061 rereading it if it has.
1061
1062
1062 This is different to dirstate.invalidate() that it doesn't always
1063 This is different to dirstate.invalidate() that it doesn't always
1063 rereads the dirstate. Use dirstate.invalidate() if you want to
1064 rereads the dirstate. Use dirstate.invalidate() if you want to
1064 explicitly read the dirstate again (i.e. restoring it to a previous
1065 explicitly read the dirstate again (i.e. restoring it to a previous
1065 known good state).'''
1066 known good state).'''
1066 if hasunfilteredcache(self, 'dirstate'):
1067 if hasunfilteredcache(self, 'dirstate'):
1067 for k in self.dirstate._filecache:
1068 for k in self.dirstate._filecache:
1068 try:
1069 try:
1069 delattr(self.dirstate, k)
1070 delattr(self.dirstate, k)
1070 except AttributeError:
1071 except AttributeError:
1071 pass
1072 pass
1072 delattr(self.unfiltered(), 'dirstate')
1073 delattr(self.unfiltered(), 'dirstate')
1073
1074
1074 def invalidate(self):
1075 def invalidate(self):
1075 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1076 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1076 for k in self._filecache:
1077 for k in self._filecache:
1077 # dirstate is invalidated separately in invalidatedirstate()
1078 # dirstate is invalidated separately in invalidatedirstate()
1078 if k == 'dirstate':
1079 if k == 'dirstate':
1079 continue
1080 continue
1080
1081
1081 try:
1082 try:
1082 delattr(unfiltered, k)
1083 delattr(unfiltered, k)
1083 except AttributeError:
1084 except AttributeError:
1084 pass
1085 pass
1085 self.invalidatecaches()
1086 self.invalidatecaches()
1086 self.store.invalidatecaches()
1087 self.store.invalidatecaches()
1087
1088
1088 def invalidateall(self):
1089 def invalidateall(self):
1089 '''Fully invalidates both store and non-store parts, causing the
1090 '''Fully invalidates both store and non-store parts, causing the
1090 subsequent operation to reread any outside changes.'''
1091 subsequent operation to reread any outside changes.'''
1091 # extension should hook this to invalidate its caches
1092 # extension should hook this to invalidate its caches
1092 self.invalidate()
1093 self.invalidate()
1093 self.invalidatedirstate()
1094 self.invalidatedirstate()
1094
1095
1095 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1096 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1096 try:
1097 try:
1097 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1098 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1098 except error.LockHeld, inst:
1099 except error.LockHeld, inst:
1099 if not wait:
1100 if not wait:
1100 raise
1101 raise
1101 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1102 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1102 (desc, inst.locker))
1103 (desc, inst.locker))
1103 # default to 600 seconds timeout
1104 # default to 600 seconds timeout
1104 l = lockmod.lock(vfs, lockname,
1105 l = lockmod.lock(vfs, lockname,
1105 int(self.ui.config("ui", "timeout", "600")),
1106 int(self.ui.config("ui", "timeout", "600")),
1106 releasefn, desc=desc)
1107 releasefn, desc=desc)
1107 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1108 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1108 if acquirefn:
1109 if acquirefn:
1109 acquirefn()
1110 acquirefn()
1110 return l
1111 return l
1111
1112
1112 def _afterlock(self, callback):
1113 def _afterlock(self, callback):
1113 """add a callback to the current repository lock.
1114 """add a callback to the current repository lock.
1114
1115
1115 The callback will be executed on lock release."""
1116 The callback will be executed on lock release."""
1116 l = self._lockref and self._lockref()
1117 l = self._lockref and self._lockref()
1117 if l:
1118 if l:
1118 l.postrelease.append(callback)
1119 l.postrelease.append(callback)
1119 else:
1120 else:
1120 callback()
1121 callback()
1121
1122
1122 def lock(self, wait=True):
1123 def lock(self, wait=True):
1123 '''Lock the repository store (.hg/store) and return a weak reference
1124 '''Lock the repository store (.hg/store) and return a weak reference
1124 to the lock. Use this before modifying the store (e.g. committing or
1125 to the lock. Use this before modifying the store (e.g. committing or
1125 stripping). If you are opening a transaction, get a lock as well.)'''
1126 stripping). If you are opening a transaction, get a lock as well.)'''
1126 l = self._lockref and self._lockref()
1127 l = self._lockref and self._lockref()
1127 if l is not None and l.held:
1128 if l is not None and l.held:
1128 l.lock()
1129 l.lock()
1129 return l
1130 return l
1130
1131
1131 def unlock():
1132 def unlock():
1132 for k, ce in self._filecache.items():
1133 for k, ce in self._filecache.items():
1133 if k == 'dirstate' or k not in self.__dict__:
1134 if k == 'dirstate' or k not in self.__dict__:
1134 continue
1135 continue
1135 ce.refresh()
1136 ce.refresh()
1136
1137
1137 l = self._lock(self.svfs, "lock", wait, unlock,
1138 l = self._lock(self.svfs, "lock", wait, unlock,
1138 self.invalidate, _('repository %s') % self.origroot)
1139 self.invalidate, _('repository %s') % self.origroot)
1139 self._lockref = weakref.ref(l)
1140 self._lockref = weakref.ref(l)
1140 return l
1141 return l
1141
1142
1142 def wlock(self, wait=True):
1143 def wlock(self, wait=True):
1143 '''Lock the non-store parts of the repository (everything under
1144 '''Lock the non-store parts of the repository (everything under
1144 .hg except .hg/store) and return a weak reference to the lock.
1145 .hg except .hg/store) and return a weak reference to the lock.
1145 Use this before modifying files in .hg.'''
1146 Use this before modifying files in .hg.'''
1146 l = self._wlockref and self._wlockref()
1147 l = self._wlockref and self._wlockref()
1147 if l is not None and l.held:
1148 if l is not None and l.held:
1148 l.lock()
1149 l.lock()
1149 return l
1150 return l
1150
1151
1151 def unlock():
1152 def unlock():
1152 if self.dirstate.pendingparentchange():
1153 if self.dirstate.pendingparentchange():
1153 self.dirstate.invalidate()
1154 self.dirstate.invalidate()
1154 else:
1155 else:
1155 self.dirstate.write()
1156 self.dirstate.write()
1156
1157
1157 self._filecache['dirstate'].refresh()
1158 self._filecache['dirstate'].refresh()
1158
1159
1159 l = self._lock(self.vfs, "wlock", wait, unlock,
1160 l = self._lock(self.vfs, "wlock", wait, unlock,
1160 self.invalidatedirstate, _('working directory of %s') %
1161 self.invalidatedirstate, _('working directory of %s') %
1161 self.origroot)
1162 self.origroot)
1162 self._wlockref = weakref.ref(l)
1163 self._wlockref = weakref.ref(l)
1163 return l
1164 return l
1164
1165
1165 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1166 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1166 """
1167 """
1167 commit an individual file as part of a larger transaction
1168 commit an individual file as part of a larger transaction
1168 """
1169 """
1169
1170
1170 fname = fctx.path()
1171 fname = fctx.path()
1171 text = fctx.data()
1172 text = fctx.data()
1172 flog = self.file(fname)
1173 flog = self.file(fname)
1173 fparent1 = manifest1.get(fname, nullid)
1174 fparent1 = manifest1.get(fname, nullid)
1174 fparent2 = manifest2.get(fname, nullid)
1175 fparent2 = manifest2.get(fname, nullid)
1175
1176
1176 meta = {}
1177 meta = {}
1177 copy = fctx.renamed()
1178 copy = fctx.renamed()
1178 if copy and copy[0] != fname:
1179 if copy and copy[0] != fname:
1179 # Mark the new revision of this file as a copy of another
1180 # Mark the new revision of this file as a copy of another
1180 # file. This copy data will effectively act as a parent
1181 # file. This copy data will effectively act as a parent
1181 # of this new revision. If this is a merge, the first
1182 # of this new revision. If this is a merge, the first
1182 # parent will be the nullid (meaning "look up the copy data")
1183 # parent will be the nullid (meaning "look up the copy data")
1183 # and the second one will be the other parent. For example:
1184 # and the second one will be the other parent. For example:
1184 #
1185 #
1185 # 0 --- 1 --- 3 rev1 changes file foo
1186 # 0 --- 1 --- 3 rev1 changes file foo
1186 # \ / rev2 renames foo to bar and changes it
1187 # \ / rev2 renames foo to bar and changes it
1187 # \- 2 -/ rev3 should have bar with all changes and
1188 # \- 2 -/ rev3 should have bar with all changes and
1188 # should record that bar descends from
1189 # should record that bar descends from
1189 # bar in rev2 and foo in rev1
1190 # bar in rev2 and foo in rev1
1190 #
1191 #
1191 # this allows this merge to succeed:
1192 # this allows this merge to succeed:
1192 #
1193 #
1193 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1194 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1194 # \ / merging rev3 and rev4 should use bar@rev2
1195 # \ / merging rev3 and rev4 should use bar@rev2
1195 # \- 2 --- 4 as the merge base
1196 # \- 2 --- 4 as the merge base
1196 #
1197 #
1197
1198
1198 cfname = copy[0]
1199 cfname = copy[0]
1199 crev = manifest1.get(cfname)
1200 crev = manifest1.get(cfname)
1200 newfparent = fparent2
1201 newfparent = fparent2
1201
1202
1202 if manifest2: # branch merge
1203 if manifest2: # branch merge
1203 if fparent2 == nullid or crev is None: # copied on remote side
1204 if fparent2 == nullid or crev is None: # copied on remote side
1204 if cfname in manifest2:
1205 if cfname in manifest2:
1205 crev = manifest2[cfname]
1206 crev = manifest2[cfname]
1206 newfparent = fparent1
1207 newfparent = fparent1
1207
1208
1208 # find source in nearest ancestor if we've lost track
1209 # find source in nearest ancestor if we've lost track
1209 if not crev:
1210 if not crev:
1210 self.ui.debug(" %s: searching for copy revision for %s\n" %
1211 self.ui.debug(" %s: searching for copy revision for %s\n" %
1211 (fname, cfname))
1212 (fname, cfname))
1212 for ancestor in self[None].ancestors():
1213 for ancestor in self[None].ancestors():
1213 if cfname in ancestor:
1214 if cfname in ancestor:
1214 crev = ancestor[cfname].filenode()
1215 crev = ancestor[cfname].filenode()
1215 break
1216 break
1216
1217
1217 if crev:
1218 if crev:
1218 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1219 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1219 meta["copy"] = cfname
1220 meta["copy"] = cfname
1220 meta["copyrev"] = hex(crev)
1221 meta["copyrev"] = hex(crev)
1221 fparent1, fparent2 = nullid, newfparent
1222 fparent1, fparent2 = nullid, newfparent
1222 else:
1223 else:
1223 self.ui.warn(_("warning: can't find ancestor for '%s' "
1224 self.ui.warn(_("warning: can't find ancestor for '%s' "
1224 "copied from '%s'!\n") % (fname, cfname))
1225 "copied from '%s'!\n") % (fname, cfname))
1225
1226
1226 elif fparent1 == nullid:
1227 elif fparent1 == nullid:
1227 fparent1, fparent2 = fparent2, nullid
1228 fparent1, fparent2 = fparent2, nullid
1228 elif fparent2 != nullid:
1229 elif fparent2 != nullid:
1229 # is one parent an ancestor of the other?
1230 # is one parent an ancestor of the other?
1230 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1231 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1231 if fparent1 in fparentancestors:
1232 if fparent1 in fparentancestors:
1232 fparent1, fparent2 = fparent2, nullid
1233 fparent1, fparent2 = fparent2, nullid
1233 elif fparent2 in fparentancestors:
1234 elif fparent2 in fparentancestors:
1234 fparent2 = nullid
1235 fparent2 = nullid
1235
1236
1236 # is the file changed?
1237 # is the file changed?
1237 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1238 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1238 changelist.append(fname)
1239 changelist.append(fname)
1239 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1240 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1240 # are just the flags changed during merge?
1241 # are just the flags changed during merge?
1241 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1242 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1242 changelist.append(fname)
1243 changelist.append(fname)
1243
1244
1244 return fparent1
1245 return fparent1
1245
1246
1246 @unfilteredmethod
1247 @unfilteredmethod
1247 def commit(self, text="", user=None, date=None, match=None, force=False,
1248 def commit(self, text="", user=None, date=None, match=None, force=False,
1248 editor=False, extra={}):
1249 editor=False, extra={}):
1249 """Add a new revision to current repository.
1250 """Add a new revision to current repository.
1250
1251
1251 Revision information is gathered from the working directory,
1252 Revision information is gathered from the working directory,
1252 match can be used to filter the committed files. If editor is
1253 match can be used to filter the committed files. If editor is
1253 supplied, it is called to get a commit message.
1254 supplied, it is called to get a commit message.
1254 """
1255 """
1255
1256
1256 def fail(f, msg):
1257 def fail(f, msg):
1257 raise util.Abort('%s: %s' % (f, msg))
1258 raise util.Abort('%s: %s' % (f, msg))
1258
1259
1259 if not match:
1260 if not match:
1260 match = matchmod.always(self.root, '')
1261 match = matchmod.always(self.root, '')
1261
1262
1262 if not force:
1263 if not force:
1263 vdirs = []
1264 vdirs = []
1264 match.explicitdir = vdirs.append
1265 match.explicitdir = vdirs.append
1265 match.bad = fail
1266 match.bad = fail
1266
1267
1267 wlock = self.wlock()
1268 wlock = self.wlock()
1268 try:
1269 try:
1269 wctx = self[None]
1270 wctx = self[None]
1270 merge = len(wctx.parents()) > 1
1271 merge = len(wctx.parents()) > 1
1271
1272
1272 if (not force and merge and match and
1273 if (not force and merge and match and
1273 (match.files() or match.anypats())):
1274 (match.files() or match.anypats())):
1274 raise util.Abort(_('cannot partially commit a merge '
1275 raise util.Abort(_('cannot partially commit a merge '
1275 '(do not specify files or patterns)'))
1276 '(do not specify files or patterns)'))
1276
1277
1277 status = self.status(match=match, clean=force)
1278 status = self.status(match=match, clean=force)
1278 if force:
1279 if force:
1279 status.modified.extend(status.clean) # mq may commit clean files
1280 status.modified.extend(status.clean) # mq may commit clean files
1280
1281
1281 # check subrepos
1282 # check subrepos
1282 subs = []
1283 subs = []
1283 commitsubs = set()
1284 commitsubs = set()
1284 newstate = wctx.substate.copy()
1285 newstate = wctx.substate.copy()
1285 # only manage subrepos and .hgsubstate if .hgsub is present
1286 # only manage subrepos and .hgsubstate if .hgsub is present
1286 if '.hgsub' in wctx:
1287 if '.hgsub' in wctx:
1287 # we'll decide whether to track this ourselves, thanks
1288 # we'll decide whether to track this ourselves, thanks
1288 for c in status.modified, status.added, status.removed:
1289 for c in status.modified, status.added, status.removed:
1289 if '.hgsubstate' in c:
1290 if '.hgsubstate' in c:
1290 c.remove('.hgsubstate')
1291 c.remove('.hgsubstate')
1291
1292
1292 # compare current state to last committed state
1293 # compare current state to last committed state
1293 # build new substate based on last committed state
1294 # build new substate based on last committed state
1294 oldstate = wctx.p1().substate
1295 oldstate = wctx.p1().substate
1295 for s in sorted(newstate.keys()):
1296 for s in sorted(newstate.keys()):
1296 if not match(s):
1297 if not match(s):
1297 # ignore working copy, use old state if present
1298 # ignore working copy, use old state if present
1298 if s in oldstate:
1299 if s in oldstate:
1299 newstate[s] = oldstate[s]
1300 newstate[s] = oldstate[s]
1300 continue
1301 continue
1301 if not force:
1302 if not force:
1302 raise util.Abort(
1303 raise util.Abort(
1303 _("commit with new subrepo %s excluded") % s)
1304 _("commit with new subrepo %s excluded") % s)
1304 if wctx.sub(s).dirty(True):
1305 if wctx.sub(s).dirty(True):
1305 if not self.ui.configbool('ui', 'commitsubrepos'):
1306 if not self.ui.configbool('ui', 'commitsubrepos'):
1306 raise util.Abort(
1307 raise util.Abort(
1307 _("uncommitted changes in subrepo %s") % s,
1308 _("uncommitted changes in subrepo %s") % s,
1308 hint=_("use --subrepos for recursive commit"))
1309 hint=_("use --subrepos for recursive commit"))
1309 subs.append(s)
1310 subs.append(s)
1310 commitsubs.add(s)
1311 commitsubs.add(s)
1311 else:
1312 else:
1312 bs = wctx.sub(s).basestate()
1313 bs = wctx.sub(s).basestate()
1313 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1314 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1314 if oldstate.get(s, (None, None, None))[1] != bs:
1315 if oldstate.get(s, (None, None, None))[1] != bs:
1315 subs.append(s)
1316 subs.append(s)
1316
1317
1317 # check for removed subrepos
1318 # check for removed subrepos
1318 for p in wctx.parents():
1319 for p in wctx.parents():
1319 r = [s for s in p.substate if s not in newstate]
1320 r = [s for s in p.substate if s not in newstate]
1320 subs += [s for s in r if match(s)]
1321 subs += [s for s in r if match(s)]
1321 if subs:
1322 if subs:
1322 if (not match('.hgsub') and
1323 if (not match('.hgsub') and
1323 '.hgsub' in (wctx.modified() + wctx.added())):
1324 '.hgsub' in (wctx.modified() + wctx.added())):
1324 raise util.Abort(
1325 raise util.Abort(
1325 _("can't commit subrepos without .hgsub"))
1326 _("can't commit subrepos without .hgsub"))
1326 status.modified.insert(0, '.hgsubstate')
1327 status.modified.insert(0, '.hgsubstate')
1327
1328
1328 elif '.hgsub' in status.removed:
1329 elif '.hgsub' in status.removed:
1329 # clean up .hgsubstate when .hgsub is removed
1330 # clean up .hgsubstate when .hgsub is removed
1330 if ('.hgsubstate' in wctx and
1331 if ('.hgsubstate' in wctx and
1331 '.hgsubstate' not in (status.modified + status.added +
1332 '.hgsubstate' not in (status.modified + status.added +
1332 status.removed)):
1333 status.removed)):
1333 status.removed.insert(0, '.hgsubstate')
1334 status.removed.insert(0, '.hgsubstate')
1334
1335
1335 # make sure all explicit patterns are matched
1336 # make sure all explicit patterns are matched
1336 if not force and match.files():
1337 if not force and match.files():
1337 matched = set(status.modified + status.added + status.removed)
1338 matched = set(status.modified + status.added + status.removed)
1338
1339
1339 for f in match.files():
1340 for f in match.files():
1340 f = self.dirstate.normalize(f)
1341 f = self.dirstate.normalize(f)
1341 if f == '.' or f in matched or f in wctx.substate:
1342 if f == '.' or f in matched or f in wctx.substate:
1342 continue
1343 continue
1343 if f in status.deleted:
1344 if f in status.deleted:
1344 fail(f, _('file not found!'))
1345 fail(f, _('file not found!'))
1345 if f in vdirs: # visited directory
1346 if f in vdirs: # visited directory
1346 d = f + '/'
1347 d = f + '/'
1347 for mf in matched:
1348 for mf in matched:
1348 if mf.startswith(d):
1349 if mf.startswith(d):
1349 break
1350 break
1350 else:
1351 else:
1351 fail(f, _("no match under directory!"))
1352 fail(f, _("no match under directory!"))
1352 elif f not in self.dirstate:
1353 elif f not in self.dirstate:
1353 fail(f, _("file not tracked!"))
1354 fail(f, _("file not tracked!"))
1354
1355
1355 cctx = context.workingcommitctx(self, status,
1356 cctx = context.workingcommitctx(self, status,
1356 text, user, date, extra)
1357 text, user, date, extra)
1357
1358
1358 if (not force and not extra.get("close") and not merge
1359 if (not force and not extra.get("close") and not merge
1359 and not cctx.files()
1360 and not cctx.files()
1360 and wctx.branch() == wctx.p1().branch()):
1361 and wctx.branch() == wctx.p1().branch()):
1361 return None
1362 return None
1362
1363
1363 if merge and cctx.deleted():
1364 if merge and cctx.deleted():
1364 raise util.Abort(_("cannot commit merge with missing files"))
1365 raise util.Abort(_("cannot commit merge with missing files"))
1365
1366
1366 ms = mergemod.mergestate(self)
1367 ms = mergemod.mergestate(self)
1367 for f in status.modified:
1368 for f in status.modified:
1368 if f in ms and ms[f] == 'u':
1369 if f in ms and ms[f] == 'u':
1369 raise util.Abort(_("unresolved merge conflicts "
1370 raise util.Abort(_("unresolved merge conflicts "
1370 "(see hg help resolve)"))
1371 "(see hg help resolve)"))
1371
1372
1372 if editor:
1373 if editor:
1373 cctx._text = editor(self, cctx, subs)
1374 cctx._text = editor(self, cctx, subs)
1374 edited = (text != cctx._text)
1375 edited = (text != cctx._text)
1375
1376
1376 # Save commit message in case this transaction gets rolled back
1377 # Save commit message in case this transaction gets rolled back
1377 # (e.g. by a pretxncommit hook). Leave the content alone on
1378 # (e.g. by a pretxncommit hook). Leave the content alone on
1378 # the assumption that the user will use the same editor again.
1379 # the assumption that the user will use the same editor again.
1379 msgfn = self.savecommitmessage(cctx._text)
1380 msgfn = self.savecommitmessage(cctx._text)
1380
1381
1381 # commit subs and write new state
1382 # commit subs and write new state
1382 if subs:
1383 if subs:
1383 for s in sorted(commitsubs):
1384 for s in sorted(commitsubs):
1384 sub = wctx.sub(s)
1385 sub = wctx.sub(s)
1385 self.ui.status(_('committing subrepository %s\n') %
1386 self.ui.status(_('committing subrepository %s\n') %
1386 subrepo.subrelpath(sub))
1387 subrepo.subrelpath(sub))
1387 sr = sub.commit(cctx._text, user, date)
1388 sr = sub.commit(cctx._text, user, date)
1388 newstate[s] = (newstate[s][0], sr)
1389 newstate[s] = (newstate[s][0], sr)
1389 subrepo.writestate(self, newstate)
1390 subrepo.writestate(self, newstate)
1390
1391
1391 p1, p2 = self.dirstate.parents()
1392 p1, p2 = self.dirstate.parents()
1392 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1393 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1393 try:
1394 try:
1394 self.hook("precommit", throw=True, parent1=hookp1,
1395 self.hook("precommit", throw=True, parent1=hookp1,
1395 parent2=hookp2)
1396 parent2=hookp2)
1396 ret = self.commitctx(cctx, True)
1397 ret = self.commitctx(cctx, True)
1397 except: # re-raises
1398 except: # re-raises
1398 if edited:
1399 if edited:
1399 self.ui.write(
1400 self.ui.write(
1400 _('note: commit message saved in %s\n') % msgfn)
1401 _('note: commit message saved in %s\n') % msgfn)
1401 raise
1402 raise
1402
1403
1403 # update bookmarks, dirstate and mergestate
1404 # update bookmarks, dirstate and mergestate
1404 bookmarks.update(self, [p1, p2], ret)
1405 bookmarks.update(self, [p1, p2], ret)
1405 cctx.markcommitted(ret)
1406 cctx.markcommitted(ret)
1406 ms.reset()
1407 ms.reset()
1407 finally:
1408 finally:
1408 wlock.release()
1409 wlock.release()
1409
1410
1410 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1411 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1411 # hack for command that use a temporary commit (eg: histedit)
1412 # hack for command that use a temporary commit (eg: histedit)
1412 # temporary commit got stripped before hook release
1413 # temporary commit got stripped before hook release
1413 if node in self:
1414 if node in self:
1414 self.hook("commit", node=node, parent1=parent1,
1415 self.hook("commit", node=node, parent1=parent1,
1415 parent2=parent2)
1416 parent2=parent2)
1416 self._afterlock(commithook)
1417 self._afterlock(commithook)
1417 return ret
1418 return ret
1418
1419
1419 @unfilteredmethod
1420 @unfilteredmethod
1420 def commitctx(self, ctx, error=False):
1421 def commitctx(self, ctx, error=False):
1421 """Add a new revision to current repository.
1422 """Add a new revision to current repository.
1422 Revision information is passed via the context argument.
1423 Revision information is passed via the context argument.
1423 """
1424 """
1424
1425
1425 tr = None
1426 tr = None
1426 p1, p2 = ctx.p1(), ctx.p2()
1427 p1, p2 = ctx.p1(), ctx.p2()
1427 user = ctx.user()
1428 user = ctx.user()
1428
1429
1429 lock = self.lock()
1430 lock = self.lock()
1430 try:
1431 try:
1431 tr = self.transaction("commit")
1432 tr = self.transaction("commit")
1432 trp = weakref.proxy(tr)
1433 trp = weakref.proxy(tr)
1433
1434
1434 if ctx.files():
1435 if ctx.files():
1435 m1 = p1.manifest()
1436 m1 = p1.manifest()
1436 m2 = p2.manifest()
1437 m2 = p2.manifest()
1437 m = m1.copy()
1438 m = m1.copy()
1438
1439
1439 # check in files
1440 # check in files
1440 added = []
1441 added = []
1441 changed = []
1442 changed = []
1442 removed = list(ctx.removed())
1443 removed = list(ctx.removed())
1443 linkrev = len(self)
1444 linkrev = len(self)
1444 self.ui.note(_("committing files:\n"))
1445 self.ui.note(_("committing files:\n"))
1445 for f in sorted(ctx.modified() + ctx.added()):
1446 for f in sorted(ctx.modified() + ctx.added()):
1446 self.ui.note(f + "\n")
1447 self.ui.note(f + "\n")
1447 try:
1448 try:
1448 fctx = ctx[f]
1449 fctx = ctx[f]
1449 if fctx is None:
1450 if fctx is None:
1450 removed.append(f)
1451 removed.append(f)
1451 else:
1452 else:
1452 added.append(f)
1453 added.append(f)
1453 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1454 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1454 trp, changed)
1455 trp, changed)
1455 m.setflag(f, fctx.flags())
1456 m.setflag(f, fctx.flags())
1456 except OSError, inst:
1457 except OSError, inst:
1457 self.ui.warn(_("trouble committing %s!\n") % f)
1458 self.ui.warn(_("trouble committing %s!\n") % f)
1458 raise
1459 raise
1459 except IOError, inst:
1460 except IOError, inst:
1460 errcode = getattr(inst, 'errno', errno.ENOENT)
1461 errcode = getattr(inst, 'errno', errno.ENOENT)
1461 if error or errcode and errcode != errno.ENOENT:
1462 if error or errcode and errcode != errno.ENOENT:
1462 self.ui.warn(_("trouble committing %s!\n") % f)
1463 self.ui.warn(_("trouble committing %s!\n") % f)
1463 raise
1464 raise
1464
1465
1465 # update manifest
1466 # update manifest
1466 self.ui.note(_("committing manifest\n"))
1467 self.ui.note(_("committing manifest\n"))
1467 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1468 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1468 drop = [f for f in removed if f in m]
1469 drop = [f for f in removed if f in m]
1469 for f in drop:
1470 for f in drop:
1470 del m[f]
1471 del m[f]
1471 mn = self.manifest.add(m, trp, linkrev,
1472 mn = self.manifest.add(m, trp, linkrev,
1472 p1.manifestnode(), p2.manifestnode(),
1473 p1.manifestnode(), p2.manifestnode(),
1473 added, drop)
1474 added, drop)
1474 files = changed + removed
1475 files = changed + removed
1475 else:
1476 else:
1476 mn = p1.manifestnode()
1477 mn = p1.manifestnode()
1477 files = []
1478 files = []
1478
1479
1479 # update changelog
1480 # update changelog
1480 self.ui.note(_("committing changelog\n"))
1481 self.ui.note(_("committing changelog\n"))
1481 self.changelog.delayupdate(tr)
1482 self.changelog.delayupdate(tr)
1482 n = self.changelog.add(mn, files, ctx.description(),
1483 n = self.changelog.add(mn, files, ctx.description(),
1483 trp, p1.node(), p2.node(),
1484 trp, p1.node(), p2.node(),
1484 user, ctx.date(), ctx.extra().copy())
1485 user, ctx.date(), ctx.extra().copy())
1485 p = lambda: tr.writepending() and self.root or ""
1486 p = lambda: tr.writepending() and self.root or ""
1486 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1487 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1487 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1488 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1488 parent2=xp2, pending=p)
1489 parent2=xp2, pending=p)
1489 # set the new commit is proper phase
1490 # set the new commit is proper phase
1490 targetphase = subrepo.newcommitphase(self.ui, ctx)
1491 targetphase = subrepo.newcommitphase(self.ui, ctx)
1491 if targetphase:
1492 if targetphase:
1492 # retract boundary do not alter parent changeset.
1493 # retract boundary do not alter parent changeset.
1493 # if a parent have higher the resulting phase will
1494 # if a parent have higher the resulting phase will
1494 # be compliant anyway
1495 # be compliant anyway
1495 #
1496 #
1496 # if minimal phase was 0 we don't need to retract anything
1497 # if minimal phase was 0 we don't need to retract anything
1497 phases.retractboundary(self, tr, targetphase, [n])
1498 phases.retractboundary(self, tr, targetphase, [n])
1498 tr.close()
1499 tr.close()
1499 branchmap.updatecache(self.filtered('served'))
1500 branchmap.updatecache(self.filtered('served'))
1500 return n
1501 return n
1501 finally:
1502 finally:
1502 if tr:
1503 if tr:
1503 tr.release()
1504 tr.release()
1504 lock.release()
1505 lock.release()
1505
1506
1506 @unfilteredmethod
1507 @unfilteredmethod
1507 def destroying(self):
1508 def destroying(self):
1508 '''Inform the repository that nodes are about to be destroyed.
1509 '''Inform the repository that nodes are about to be destroyed.
1509 Intended for use by strip and rollback, so there's a common
1510 Intended for use by strip and rollback, so there's a common
1510 place for anything that has to be done before destroying history.
1511 place for anything that has to be done before destroying history.
1511
1512
1512 This is mostly useful for saving state that is in memory and waiting
1513 This is mostly useful for saving state that is in memory and waiting
1513 to be flushed when the current lock is released. Because a call to
1514 to be flushed when the current lock is released. Because a call to
1514 destroyed is imminent, the repo will be invalidated causing those
1515 destroyed is imminent, the repo will be invalidated causing those
1515 changes to stay in memory (waiting for the next unlock), or vanish
1516 changes to stay in memory (waiting for the next unlock), or vanish
1516 completely.
1517 completely.
1517 '''
1518 '''
1518 # When using the same lock to commit and strip, the phasecache is left
1519 # When using the same lock to commit and strip, the phasecache is left
1519 # dirty after committing. Then when we strip, the repo is invalidated,
1520 # dirty after committing. Then when we strip, the repo is invalidated,
1520 # causing those changes to disappear.
1521 # causing those changes to disappear.
1521 if '_phasecache' in vars(self):
1522 if '_phasecache' in vars(self):
1522 self._phasecache.write()
1523 self._phasecache.write()
1523
1524
1524 @unfilteredmethod
1525 @unfilteredmethod
1525 def destroyed(self):
1526 def destroyed(self):
1526 '''Inform the repository that nodes have been destroyed.
1527 '''Inform the repository that nodes have been destroyed.
1527 Intended for use by strip and rollback, so there's a common
1528 Intended for use by strip and rollback, so there's a common
1528 place for anything that has to be done after destroying history.
1529 place for anything that has to be done after destroying history.
1529 '''
1530 '''
1530 # When one tries to:
1531 # When one tries to:
1531 # 1) destroy nodes thus calling this method (e.g. strip)
1532 # 1) destroy nodes thus calling this method (e.g. strip)
1532 # 2) use phasecache somewhere (e.g. commit)
1533 # 2) use phasecache somewhere (e.g. commit)
1533 #
1534 #
1534 # then 2) will fail because the phasecache contains nodes that were
1535 # then 2) will fail because the phasecache contains nodes that were
1535 # removed. We can either remove phasecache from the filecache,
1536 # removed. We can either remove phasecache from the filecache,
1536 # causing it to reload next time it is accessed, or simply filter
1537 # causing it to reload next time it is accessed, or simply filter
1537 # the removed nodes now and write the updated cache.
1538 # the removed nodes now and write the updated cache.
1538 self._phasecache.filterunknown(self)
1539 self._phasecache.filterunknown(self)
1539 self._phasecache.write()
1540 self._phasecache.write()
1540
1541
1541 # update the 'served' branch cache to help read only server process
1542 # update the 'served' branch cache to help read only server process
1542 # Thanks to branchcache collaboration this is done from the nearest
1543 # Thanks to branchcache collaboration this is done from the nearest
1543 # filtered subset and it is expected to be fast.
1544 # filtered subset and it is expected to be fast.
1544 branchmap.updatecache(self.filtered('served'))
1545 branchmap.updatecache(self.filtered('served'))
1545
1546
1546 # Ensure the persistent tag cache is updated. Doing it now
1547 # Ensure the persistent tag cache is updated. Doing it now
1547 # means that the tag cache only has to worry about destroyed
1548 # means that the tag cache only has to worry about destroyed
1548 # heads immediately after a strip/rollback. That in turn
1549 # heads immediately after a strip/rollback. That in turn
1549 # guarantees that "cachetip == currenttip" (comparing both rev
1550 # guarantees that "cachetip == currenttip" (comparing both rev
1550 # and node) always means no nodes have been added or destroyed.
1551 # and node) always means no nodes have been added or destroyed.
1551
1552
1552 # XXX this is suboptimal when qrefresh'ing: we strip the current
1553 # XXX this is suboptimal when qrefresh'ing: we strip the current
1553 # head, refresh the tag cache, then immediately add a new head.
1554 # head, refresh the tag cache, then immediately add a new head.
1554 # But I think doing it this way is necessary for the "instant
1555 # But I think doing it this way is necessary for the "instant
1555 # tag cache retrieval" case to work.
1556 # tag cache retrieval" case to work.
1556 self.invalidate()
1557 self.invalidate()
1557
1558
1558 def walk(self, match, node=None):
1559 def walk(self, match, node=None):
1559 '''
1560 '''
1560 walk recursively through the directory tree or a given
1561 walk recursively through the directory tree or a given
1561 changeset, finding all files matched by the match
1562 changeset, finding all files matched by the match
1562 function
1563 function
1563 '''
1564 '''
1564 return self[node].walk(match)
1565 return self[node].walk(match)
1565
1566
1566 def status(self, node1='.', node2=None, match=None,
1567 def status(self, node1='.', node2=None, match=None,
1567 ignored=False, clean=False, unknown=False,
1568 ignored=False, clean=False, unknown=False,
1568 listsubrepos=False):
1569 listsubrepos=False):
1569 '''a convenience method that calls node1.status(node2)'''
1570 '''a convenience method that calls node1.status(node2)'''
1570 return self[node1].status(node2, match, ignored, clean, unknown,
1571 return self[node1].status(node2, match, ignored, clean, unknown,
1571 listsubrepos)
1572 listsubrepos)
1572
1573
1573 def heads(self, start=None):
1574 def heads(self, start=None):
1574 heads = self.changelog.heads(start)
1575 heads = self.changelog.heads(start)
1575 # sort the output in rev descending order
1576 # sort the output in rev descending order
1576 return sorted(heads, key=self.changelog.rev, reverse=True)
1577 return sorted(heads, key=self.changelog.rev, reverse=True)
1577
1578
1578 def branchheads(self, branch=None, start=None, closed=False):
1579 def branchheads(self, branch=None, start=None, closed=False):
1579 '''return a (possibly filtered) list of heads for the given branch
1580 '''return a (possibly filtered) list of heads for the given branch
1580
1581
1581 Heads are returned in topological order, from newest to oldest.
1582 Heads are returned in topological order, from newest to oldest.
1582 If branch is None, use the dirstate branch.
1583 If branch is None, use the dirstate branch.
1583 If start is not None, return only heads reachable from start.
1584 If start is not None, return only heads reachable from start.
1584 If closed is True, return heads that are marked as closed as well.
1585 If closed is True, return heads that are marked as closed as well.
1585 '''
1586 '''
1586 if branch is None:
1587 if branch is None:
1587 branch = self[None].branch()
1588 branch = self[None].branch()
1588 branches = self.branchmap()
1589 branches = self.branchmap()
1589 if branch not in branches:
1590 if branch not in branches:
1590 return []
1591 return []
1591 # the cache returns heads ordered lowest to highest
1592 # the cache returns heads ordered lowest to highest
1592 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1593 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1593 if start is not None:
1594 if start is not None:
1594 # filter out the heads that cannot be reached from startrev
1595 # filter out the heads that cannot be reached from startrev
1595 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1596 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1596 bheads = [h for h in bheads if h in fbheads]
1597 bheads = [h for h in bheads if h in fbheads]
1597 return bheads
1598 return bheads
1598
1599
1599 def branches(self, nodes):
1600 def branches(self, nodes):
1600 if not nodes:
1601 if not nodes:
1601 nodes = [self.changelog.tip()]
1602 nodes = [self.changelog.tip()]
1602 b = []
1603 b = []
1603 for n in nodes:
1604 for n in nodes:
1604 t = n
1605 t = n
1605 while True:
1606 while True:
1606 p = self.changelog.parents(n)
1607 p = self.changelog.parents(n)
1607 if p[1] != nullid or p[0] == nullid:
1608 if p[1] != nullid or p[0] == nullid:
1608 b.append((t, n, p[0], p[1]))
1609 b.append((t, n, p[0], p[1]))
1609 break
1610 break
1610 n = p[0]
1611 n = p[0]
1611 return b
1612 return b
1612
1613
1613 def between(self, pairs):
1614 def between(self, pairs):
1614 r = []
1615 r = []
1615
1616
1616 for top, bottom in pairs:
1617 for top, bottom in pairs:
1617 n, l, i = top, [], 0
1618 n, l, i = top, [], 0
1618 f = 1
1619 f = 1
1619
1620
1620 while n != bottom and n != nullid:
1621 while n != bottom and n != nullid:
1621 p = self.changelog.parents(n)[0]
1622 p = self.changelog.parents(n)[0]
1622 if i == f:
1623 if i == f:
1623 l.append(n)
1624 l.append(n)
1624 f = f * 2
1625 f = f * 2
1625 n = p
1626 n = p
1626 i += 1
1627 i += 1
1627
1628
1628 r.append(l)
1629 r.append(l)
1629
1630
1630 return r
1631 return r
1631
1632
1632 def checkpush(self, pushop):
1633 def checkpush(self, pushop):
1633 """Extensions can override this function if additional checks have
1634 """Extensions can override this function if additional checks have
1634 to be performed before pushing, or call it if they override push
1635 to be performed before pushing, or call it if they override push
1635 command.
1636 command.
1636 """
1637 """
1637 pass
1638 pass
1638
1639
1639 @unfilteredpropertycache
1640 @unfilteredpropertycache
1640 def prepushoutgoinghooks(self):
1641 def prepushoutgoinghooks(self):
1641 """Return util.hooks consists of "(repo, remote, outgoing)"
1642 """Return util.hooks consists of "(repo, remote, outgoing)"
1642 functions, which are called before pushing changesets.
1643 functions, which are called before pushing changesets.
1643 """
1644 """
1644 return util.hooks()
1645 return util.hooks()
1645
1646
1646 def stream_in(self, remote, requirements):
1647 def stream_in(self, remote, requirements):
1647 lock = self.lock()
1648 lock = self.lock()
1648 try:
1649 try:
1649 # Save remote branchmap. We will use it later
1650 # Save remote branchmap. We will use it later
1650 # to speed up branchcache creation
1651 # to speed up branchcache creation
1651 rbranchmap = None
1652 rbranchmap = None
1652 if remote.capable("branchmap"):
1653 if remote.capable("branchmap"):
1653 rbranchmap = remote.branchmap()
1654 rbranchmap = remote.branchmap()
1654
1655
1655 fp = remote.stream_out()
1656 fp = remote.stream_out()
1656 l = fp.readline()
1657 l = fp.readline()
1657 try:
1658 try:
1658 resp = int(l)
1659 resp = int(l)
1659 except ValueError:
1660 except ValueError:
1660 raise error.ResponseError(
1661 raise error.ResponseError(
1661 _('unexpected response from remote server:'), l)
1662 _('unexpected response from remote server:'), l)
1662 if resp == 1:
1663 if resp == 1:
1663 raise util.Abort(_('operation forbidden by server'))
1664 raise util.Abort(_('operation forbidden by server'))
1664 elif resp == 2:
1665 elif resp == 2:
1665 raise util.Abort(_('locking the remote repository failed'))
1666 raise util.Abort(_('locking the remote repository failed'))
1666 elif resp != 0:
1667 elif resp != 0:
1667 raise util.Abort(_('the server sent an unknown error code'))
1668 raise util.Abort(_('the server sent an unknown error code'))
1668 self.ui.status(_('streaming all changes\n'))
1669 self.ui.status(_('streaming all changes\n'))
1669 l = fp.readline()
1670 l = fp.readline()
1670 try:
1671 try:
1671 total_files, total_bytes = map(int, l.split(' ', 1))
1672 total_files, total_bytes = map(int, l.split(' ', 1))
1672 except (ValueError, TypeError):
1673 except (ValueError, TypeError):
1673 raise error.ResponseError(
1674 raise error.ResponseError(
1674 _('unexpected response from remote server:'), l)
1675 _('unexpected response from remote server:'), l)
1675 self.ui.status(_('%d files to transfer, %s of data\n') %
1676 self.ui.status(_('%d files to transfer, %s of data\n') %
1676 (total_files, util.bytecount(total_bytes)))
1677 (total_files, util.bytecount(total_bytes)))
1677 handled_bytes = 0
1678 handled_bytes = 0
1678 self.ui.progress(_('clone'), 0, total=total_bytes)
1679 self.ui.progress(_('clone'), 0, total=total_bytes)
1679 start = time.time()
1680 start = time.time()
1680
1681
1681 tr = self.transaction(_('clone'))
1682 tr = self.transaction(_('clone'))
1682 try:
1683 try:
1683 for i in xrange(total_files):
1684 for i in xrange(total_files):
1684 # XXX doesn't support '\n' or '\r' in filenames
1685 # XXX doesn't support '\n' or '\r' in filenames
1685 l = fp.readline()
1686 l = fp.readline()
1686 try:
1687 try:
1687 name, size = l.split('\0', 1)
1688 name, size = l.split('\0', 1)
1688 size = int(size)
1689 size = int(size)
1689 except (ValueError, TypeError):
1690 except (ValueError, TypeError):
1690 raise error.ResponseError(
1691 raise error.ResponseError(
1691 _('unexpected response from remote server:'), l)
1692 _('unexpected response from remote server:'), l)
1692 if self.ui.debugflag:
1693 if self.ui.debugflag:
1693 self.ui.debug('adding %s (%s)\n' %
1694 self.ui.debug('adding %s (%s)\n' %
1694 (name, util.bytecount(size)))
1695 (name, util.bytecount(size)))
1695 # for backwards compat, name was partially encoded
1696 # for backwards compat, name was partially encoded
1696 ofp = self.svfs(store.decodedir(name), 'w')
1697 ofp = self.svfs(store.decodedir(name), 'w')
1697 for chunk in util.filechunkiter(fp, limit=size):
1698 for chunk in util.filechunkiter(fp, limit=size):
1698 handled_bytes += len(chunk)
1699 handled_bytes += len(chunk)
1699 self.ui.progress(_('clone'), handled_bytes,
1700 self.ui.progress(_('clone'), handled_bytes,
1700 total=total_bytes)
1701 total=total_bytes)
1701 ofp.write(chunk)
1702 ofp.write(chunk)
1702 ofp.close()
1703 ofp.close()
1703 tr.close()
1704 tr.close()
1704 finally:
1705 finally:
1705 tr.release()
1706 tr.release()
1706
1707
1707 # Writing straight to files circumvented the inmemory caches
1708 # Writing straight to files circumvented the inmemory caches
1708 self.invalidate()
1709 self.invalidate()
1709
1710
1710 elapsed = time.time() - start
1711 elapsed = time.time() - start
1711 if elapsed <= 0:
1712 if elapsed <= 0:
1712 elapsed = 0.001
1713 elapsed = 0.001
1713 self.ui.progress(_('clone'), None)
1714 self.ui.progress(_('clone'), None)
1714 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1715 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1715 (util.bytecount(total_bytes), elapsed,
1716 (util.bytecount(total_bytes), elapsed,
1716 util.bytecount(total_bytes / elapsed)))
1717 util.bytecount(total_bytes / elapsed)))
1717
1718
1718 # new requirements = old non-format requirements +
1719 # new requirements = old non-format requirements +
1719 # new format-related
1720 # new format-related
1720 # requirements from the streamed-in repository
1721 # requirements from the streamed-in repository
1721 requirements.update(set(self.requirements) - self.supportedformats)
1722 requirements.update(set(self.requirements) - self.supportedformats)
1722 self._applyrequirements(requirements)
1723 self._applyrequirements(requirements)
1723 self._writerequirements()
1724 self._writerequirements()
1724
1725
1725 if rbranchmap:
1726 if rbranchmap:
1726 rbheads = []
1727 rbheads = []
1727 closed = []
1728 closed = []
1728 for bheads in rbranchmap.itervalues():
1729 for bheads in rbranchmap.itervalues():
1729 rbheads.extend(bheads)
1730 rbheads.extend(bheads)
1730 for h in bheads:
1731 for h in bheads:
1731 r = self.changelog.rev(h)
1732 r = self.changelog.rev(h)
1732 b, c = self.changelog.branchinfo(r)
1733 b, c = self.changelog.branchinfo(r)
1733 if c:
1734 if c:
1734 closed.append(h)
1735 closed.append(h)
1735
1736
1736 if rbheads:
1737 if rbheads:
1737 rtiprev = max((int(self.changelog.rev(node))
1738 rtiprev = max((int(self.changelog.rev(node))
1738 for node in rbheads))
1739 for node in rbheads))
1739 cache = branchmap.branchcache(rbranchmap,
1740 cache = branchmap.branchcache(rbranchmap,
1740 self[rtiprev].node(),
1741 self[rtiprev].node(),
1741 rtiprev,
1742 rtiprev,
1742 closednodes=closed)
1743 closednodes=closed)
1743 # Try to stick it as low as possible
1744 # Try to stick it as low as possible
1744 # filter above served are unlikely to be fetch from a clone
1745 # filter above served are unlikely to be fetch from a clone
1745 for candidate in ('base', 'immutable', 'served'):
1746 for candidate in ('base', 'immutable', 'served'):
1746 rview = self.filtered(candidate)
1747 rview = self.filtered(candidate)
1747 if cache.validfor(rview):
1748 if cache.validfor(rview):
1748 self._branchcaches[candidate] = cache
1749 self._branchcaches[candidate] = cache
1749 cache.write(rview)
1750 cache.write(rview)
1750 break
1751 break
1751 self.invalidate()
1752 self.invalidate()
1752 return len(self.heads()) + 1
1753 return len(self.heads()) + 1
1753 finally:
1754 finally:
1754 lock.release()
1755 lock.release()
1755
1756
1756 def clone(self, remote, heads=[], stream=None):
1757 def clone(self, remote, heads=[], stream=None):
1757 '''clone remote repository.
1758 '''clone remote repository.
1758
1759
1759 keyword arguments:
1760 keyword arguments:
1760 heads: list of revs to clone (forces use of pull)
1761 heads: list of revs to clone (forces use of pull)
1761 stream: use streaming clone if possible'''
1762 stream: use streaming clone if possible'''
1762
1763
1763 # now, all clients that can request uncompressed clones can
1764 # now, all clients that can request uncompressed clones can
1764 # read repo formats supported by all servers that can serve
1765 # read repo formats supported by all servers that can serve
1765 # them.
1766 # them.
1766
1767
1767 # if revlog format changes, client will have to check version
1768 # if revlog format changes, client will have to check version
1768 # and format flags on "stream" capability, and use
1769 # and format flags on "stream" capability, and use
1769 # uncompressed only if compatible.
1770 # uncompressed only if compatible.
1770
1771
1771 if stream is None:
1772 if stream is None:
1772 # if the server explicitly prefers to stream (for fast LANs)
1773 # if the server explicitly prefers to stream (for fast LANs)
1773 stream = remote.capable('stream-preferred')
1774 stream = remote.capable('stream-preferred')
1774
1775
1775 if stream and not heads:
1776 if stream and not heads:
1776 # 'stream' means remote revlog format is revlogv1 only
1777 # 'stream' means remote revlog format is revlogv1 only
1777 if remote.capable('stream'):
1778 if remote.capable('stream'):
1778 self.stream_in(remote, set(('revlogv1',)))
1779 self.stream_in(remote, set(('revlogv1',)))
1779 else:
1780 else:
1780 # otherwise, 'streamreqs' contains the remote revlog format
1781 # otherwise, 'streamreqs' contains the remote revlog format
1781 streamreqs = remote.capable('streamreqs')
1782 streamreqs = remote.capable('streamreqs')
1782 if streamreqs:
1783 if streamreqs:
1783 streamreqs = set(streamreqs.split(','))
1784 streamreqs = set(streamreqs.split(','))
1784 # if we support it, stream in and adjust our requirements
1785 # if we support it, stream in and adjust our requirements
1785 if not streamreqs - self.supportedformats:
1786 if not streamreqs - self.supportedformats:
1786 self.stream_in(remote, streamreqs)
1787 self.stream_in(remote, streamreqs)
1787
1788
1788 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1789 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1789 try:
1790 try:
1790 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1791 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1791 ret = exchange.pull(self, remote, heads).cgresult
1792 ret = exchange.pull(self, remote, heads).cgresult
1792 finally:
1793 finally:
1793 self.ui.restoreconfig(quiet)
1794 self.ui.restoreconfig(quiet)
1794 return ret
1795 return ret
1795
1796
1796 def pushkey(self, namespace, key, old, new):
1797 def pushkey(self, namespace, key, old, new):
1797 try:
1798 try:
1798 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1799 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1799 old=old, new=new)
1800 old=old, new=new)
1800 except error.HookAbort, exc:
1801 except error.HookAbort, exc:
1801 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1802 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1802 if exc.hint:
1803 if exc.hint:
1803 self.ui.write_err(_("(%s)\n") % exc.hint)
1804 self.ui.write_err(_("(%s)\n") % exc.hint)
1804 return False
1805 return False
1805 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1806 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1806 ret = pushkey.push(self, namespace, key, old, new)
1807 ret = pushkey.push(self, namespace, key, old, new)
1807 def runhook():
1808 def runhook():
1808 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1809 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1809 ret=ret)
1810 ret=ret)
1810 self._afterlock(runhook)
1811 self._afterlock(runhook)
1811 return ret
1812 return ret
1812
1813
1813 def listkeys(self, namespace):
1814 def listkeys(self, namespace):
1814 self.hook('prelistkeys', throw=True, namespace=namespace)
1815 self.hook('prelistkeys', throw=True, namespace=namespace)
1815 self.ui.debug('listing keys for "%s"\n' % namespace)
1816 self.ui.debug('listing keys for "%s"\n' % namespace)
1816 values = pushkey.list(self, namespace)
1817 values = pushkey.list(self, namespace)
1817 self.hook('listkeys', namespace=namespace, values=values)
1818 self.hook('listkeys', namespace=namespace, values=values)
1818 return values
1819 return values
1819
1820
1820 def debugwireargs(self, one, two, three=None, four=None, five=None):
1821 def debugwireargs(self, one, two, three=None, four=None, five=None):
1821 '''used to test argument passing over the wire'''
1822 '''used to test argument passing over the wire'''
1822 return "%s %s %s %s %s" % (one, two, three, four, five)
1823 return "%s %s %s %s %s" % (one, two, three, four, five)
1823
1824
1824 def savecommitmessage(self, text):
1825 def savecommitmessage(self, text):
1825 fp = self.vfs('last-message.txt', 'wb')
1826 fp = self.vfs('last-message.txt', 'wb')
1826 try:
1827 try:
1827 fp.write(text)
1828 fp.write(text)
1828 finally:
1829 finally:
1829 fp.close()
1830 fp.close()
1830 return self.pathto(fp.name[len(self.root) + 1:])
1831 return self.pathto(fp.name[len(self.root) + 1:])
1831
1832
1832 # used to avoid circular references so destructors work
1833 # used to avoid circular references so destructors work
1833 def aftertrans(files):
1834 def aftertrans(files):
1834 renamefiles = [tuple(t) for t in files]
1835 renamefiles = [tuple(t) for t in files]
1835 def a():
1836 def a():
1836 for vfs, src, dest in renamefiles:
1837 for vfs, src, dest in renamefiles:
1837 try:
1838 try:
1838 vfs.rename(src, dest)
1839 vfs.rename(src, dest)
1839 except OSError: # journal file does not yet exist
1840 except OSError: # journal file does not yet exist
1840 pass
1841 pass
1841 return a
1842 return a
1842
1843
1843 def undoname(fn):
1844 def undoname(fn):
1844 base, name = os.path.split(fn)
1845 base, name = os.path.split(fn)
1845 assert name.startswith('journal')
1846 assert name.startswith('journal')
1846 return os.path.join(base, name.replace('journal', 'undo', 1))
1847 return os.path.join(base, name.replace('journal', 'undo', 1))
1847
1848
1848 def instance(ui, path, create):
1849 def instance(ui, path, create):
1849 return localrepository(ui, util.urllocalpath(path), create)
1850 return localrepository(ui, util.urllocalpath(path), create)
1850
1851
1851 def islocal(path):
1852 def islocal(path):
1852 return True
1853 return True
@@ -1,512 +1,513 b''
1 # transaction.py - simple journaling scheme for mercurial
1 # transaction.py - simple journaling scheme for mercurial
2 #
2 #
3 # This transaction scheme is intended to gracefully handle program
3 # This transaction scheme is intended to gracefully handle program
4 # errors and interruptions. More serious failures like system crashes
4 # errors and interruptions. More serious failures like system crashes
5 # can be recovered with an fsck-like tool. As the whole repository is
5 # can be recovered with an fsck-like tool. As the whole repository is
6 # effectively log-structured, this should amount to simply truncating
6 # effectively log-structured, this should amount to simply truncating
7 # anything that isn't referenced in the changelog.
7 # anything that isn't referenced in the changelog.
8 #
8 #
9 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
9 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
10 #
10 #
11 # This software may be used and distributed according to the terms of the
11 # This software may be used and distributed according to the terms of the
12 # GNU General Public License version 2 or any later version.
12 # GNU General Public License version 2 or any later version.
13
13
14 from i18n import _
14 from i18n import _
15 import errno
15 import errno
16 import error, util
16 import error, util
17
17
18 version = 2
18 version = 2
19
19
20 def active(func):
20 def active(func):
21 def _active(self, *args, **kwds):
21 def _active(self, *args, **kwds):
22 if self.count == 0:
22 if self.count == 0:
23 raise error.Abort(_(
23 raise error.Abort(_(
24 'cannot use transaction when it is already committed/aborted'))
24 'cannot use transaction when it is already committed/aborted'))
25 return func(self, *args, **kwds)
25 return func(self, *args, **kwds)
26 return _active
26 return _active
27
27
28 def _playback(journal, report, opener, vfsmap, entries, backupentries,
28 def _playback(journal, report, opener, vfsmap, entries, backupentries,
29 unlink=True):
29 unlink=True):
30 for f, o, _ignore in entries:
30 for f, o, _ignore in entries:
31 if o or not unlink:
31 if o or not unlink:
32 try:
32 try:
33 fp = opener(f, 'a')
33 fp = opener(f, 'a')
34 fp.truncate(o)
34 fp.truncate(o)
35 fp.close()
35 fp.close()
36 except IOError:
36 except IOError:
37 report(_("failed to truncate %s\n") % f)
37 report(_("failed to truncate %s\n") % f)
38 raise
38 raise
39 else:
39 else:
40 try:
40 try:
41 opener.unlink(f)
41 opener.unlink(f)
42 except (IOError, OSError), inst:
42 except (IOError, OSError), inst:
43 if inst.errno != errno.ENOENT:
43 if inst.errno != errno.ENOENT:
44 raise
44 raise
45
45
46 backupfiles = []
46 backupfiles = []
47 for l, f, b, c in backupentries:
47 for l, f, b, c in backupentries:
48 if l not in vfsmap and c:
48 if l not in vfsmap and c:
49 report("couldn't handle %s: unknown cache location %s\n"
49 report("couldn't handle %s: unknown cache location %s\n"
50 % (b, l))
50 % (b, l))
51 vfs = vfsmap[l]
51 vfs = vfsmap[l]
52 try:
52 try:
53 if f and b:
53 if f and b:
54 filepath = vfs.join(f)
54 filepath = vfs.join(f)
55 backuppath = vfs.join(b)
55 backuppath = vfs.join(b)
56 try:
56 try:
57 util.copyfile(backuppath, filepath)
57 util.copyfile(backuppath, filepath)
58 backupfiles.append(b)
58 backupfiles.append(b)
59 except IOError:
59 except IOError:
60 report(_("failed to recover %s\n") % f)
60 report(_("failed to recover %s\n") % f)
61 else:
61 else:
62 target = f or b
62 target = f or b
63 try:
63 try:
64 vfs.unlink(target)
64 vfs.unlink(target)
65 except (IOError, OSError), inst:
65 except (IOError, OSError), inst:
66 if inst.errno != errno.ENOENT:
66 if inst.errno != errno.ENOENT:
67 raise
67 raise
68 except (IOError, OSError, util.Abort), inst:
68 except (IOError, OSError, util.Abort), inst:
69 if not c:
69 if not c:
70 raise
70 raise
71
71
72 opener.unlink(journal)
72 opener.unlink(journal)
73 backuppath = "%s.backupfiles" % journal
73 backuppath = "%s.backupfiles" % journal
74 if opener.exists(backuppath):
74 if opener.exists(backuppath):
75 opener.unlink(backuppath)
75 opener.unlink(backuppath)
76 try:
76 try:
77 for f in backupfiles:
77 for f in backupfiles:
78 if opener.exists(f):
78 if opener.exists(f):
79 opener.unlink(f)
79 opener.unlink(f)
80 except (IOError, OSError, util.Abort), inst:
80 except (IOError, OSError, util.Abort), inst:
81 # only pure backup file remains, it is sage to ignore any error
81 # only pure backup file remains, it is sage to ignore any error
82 pass
82 pass
83
83
84 class transaction(object):
84 class transaction(object):
85 def __init__(self, report, opener, vfsmap, journalname, after=None,
85 def __init__(self, report, opener, vfsmap, journalname, undoname=None,
86 createmode=None):
86 after=None, createmode=None):
87 """Begin a new transaction
87 """Begin a new transaction
88
88
89 Begins a new transaction that allows rolling back writes in the event of
89 Begins a new transaction that allows rolling back writes in the event of
90 an exception.
90 an exception.
91
91
92 * `after`: called after the transaction has been committed
92 * `after`: called after the transaction has been committed
93 * `createmode`: the mode of the journal file that will be created
93 * `createmode`: the mode of the journal file that will be created
94 """
94 """
95 self.count = 1
95 self.count = 1
96 self.usages = 1
96 self.usages = 1
97 self.report = report
97 self.report = report
98 # a vfs to the store content
98 # a vfs to the store content
99 self.opener = opener
99 self.opener = opener
100 # a map to access file in various {location -> vfs}
100 # a map to access file in various {location -> vfs}
101 vfsmap = vfsmap.copy()
101 vfsmap = vfsmap.copy()
102 vfsmap[''] = opener # set default value
102 vfsmap[''] = opener # set default value
103 self._vfsmap = vfsmap
103 self._vfsmap = vfsmap
104 self.after = after
104 self.after = after
105 self.entries = []
105 self.entries = []
106 self.map = {}
106 self.map = {}
107 self.journal = journalname
107 self.journal = journalname
108 self.undoname = undoname
108 self._queue = []
109 self._queue = []
109 # a dict of arguments to be passed to hooks
110 # a dict of arguments to be passed to hooks
110 self.hookargs = {}
111 self.hookargs = {}
111 self.file = opener.open(self.journal, "w")
112 self.file = opener.open(self.journal, "w")
112
113
113 # a list of ('location', 'path', 'backuppath', cache) entries.
114 # a list of ('location', 'path', 'backuppath', cache) entries.
114 # - if 'backuppath' is empty, no file existed at backup time
115 # - if 'backuppath' is empty, no file existed at backup time
115 # - if 'path' is empty, this is a temporary transaction file
116 # - if 'path' is empty, this is a temporary transaction file
116 # - if 'location' is not empty, the path is outside main opener reach.
117 # - if 'location' is not empty, the path is outside main opener reach.
117 # use 'location' value as a key in a vfsmap to find the right 'vfs'
118 # use 'location' value as a key in a vfsmap to find the right 'vfs'
118 # (cache is currently unused)
119 # (cache is currently unused)
119 self._backupentries = []
120 self._backupentries = []
120 self._backupmap = {}
121 self._backupmap = {}
121 self._backupjournal = "%s.backupfiles" % self.journal
122 self._backupjournal = "%s.backupfiles" % self.journal
122 self._backupsfile = opener.open(self._backupjournal, 'w')
123 self._backupsfile = opener.open(self._backupjournal, 'w')
123 self._backupsfile.write('%d\n' % version)
124 self._backupsfile.write('%d\n' % version)
124
125
125 if createmode is not None:
126 if createmode is not None:
126 opener.chmod(self.journal, createmode & 0666)
127 opener.chmod(self.journal, createmode & 0666)
127 opener.chmod(self._backupjournal, createmode & 0666)
128 opener.chmod(self._backupjournal, createmode & 0666)
128
129
129 # hold file generations to be performed on commit
130 # hold file generations to be performed on commit
130 self._filegenerators = {}
131 self._filegenerators = {}
131 # hold callback to write pending data for hooks
132 # hold callback to write pending data for hooks
132 self._pendingcallback = {}
133 self._pendingcallback = {}
133 # True is any pending data have been written ever
134 # True is any pending data have been written ever
134 self._anypending = False
135 self._anypending = False
135 # holds callback to call when writing the transaction
136 # holds callback to call when writing the transaction
136 self._finalizecallback = {}
137 self._finalizecallback = {}
137 # hold callback for post transaction close
138 # hold callback for post transaction close
138 self._postclosecallback = {}
139 self._postclosecallback = {}
139 # holds callbacks to call during abort
140 # holds callbacks to call during abort
140 self._abortcallback = {}
141 self._abortcallback = {}
141
142
142 def __del__(self):
143 def __del__(self):
143 if self.journal:
144 if self.journal:
144 self._abort()
145 self._abort()
145
146
146 @active
147 @active
147 def startgroup(self):
148 def startgroup(self):
148 """delay registration of file entry
149 """delay registration of file entry
149
150
150 This is used by strip to delay vision of strip offset. The transaction
151 This is used by strip to delay vision of strip offset. The transaction
151 sees either none or all of the strip actions to be done."""
152 sees either none or all of the strip actions to be done."""
152 self._queue.append([])
153 self._queue.append([])
153
154
154 @active
155 @active
155 def endgroup(self):
156 def endgroup(self):
156 """apply delayed registration of file entry.
157 """apply delayed registration of file entry.
157
158
158 This is used by strip to delay vision of strip offset. The transaction
159 This is used by strip to delay vision of strip offset. The transaction
159 sees either none or all of the strip actions to be done."""
160 sees either none or all of the strip actions to be done."""
160 q = self._queue.pop()
161 q = self._queue.pop()
161 for f, o, data in q:
162 for f, o, data in q:
162 self._addentry(f, o, data)
163 self._addentry(f, o, data)
163
164
164 @active
165 @active
165 def add(self, file, offset, data=None):
166 def add(self, file, offset, data=None):
166 """record the state of an append-only file before update"""
167 """record the state of an append-only file before update"""
167 if file in self.map or file in self._backupmap:
168 if file in self.map or file in self._backupmap:
168 return
169 return
169 if self._queue:
170 if self._queue:
170 self._queue[-1].append((file, offset, data))
171 self._queue[-1].append((file, offset, data))
171 return
172 return
172
173
173 self._addentry(file, offset, data)
174 self._addentry(file, offset, data)
174
175
175 def _addentry(self, file, offset, data):
176 def _addentry(self, file, offset, data):
176 """add a append-only entry to memory and on-disk state"""
177 """add a append-only entry to memory and on-disk state"""
177 if file in self.map or file in self._backupmap:
178 if file in self.map or file in self._backupmap:
178 return
179 return
179 self.entries.append((file, offset, data))
180 self.entries.append((file, offset, data))
180 self.map[file] = len(self.entries) - 1
181 self.map[file] = len(self.entries) - 1
181 # add enough data to the journal to do the truncate
182 # add enough data to the journal to do the truncate
182 self.file.write("%s\0%d\n" % (file, offset))
183 self.file.write("%s\0%d\n" % (file, offset))
183 self.file.flush()
184 self.file.flush()
184
185
185 @active
186 @active
186 def addbackup(self, file, hardlink=True, location=''):
187 def addbackup(self, file, hardlink=True, location=''):
187 """Adds a backup of the file to the transaction
188 """Adds a backup of the file to the transaction
188
189
189 Calling addbackup() creates a hardlink backup of the specified file
190 Calling addbackup() creates a hardlink backup of the specified file
190 that is used to recover the file in the event of the transaction
191 that is used to recover the file in the event of the transaction
191 aborting.
192 aborting.
192
193
193 * `file`: the file path, relative to .hg/store
194 * `file`: the file path, relative to .hg/store
194 * `hardlink`: use a hardlink to quickly create the backup
195 * `hardlink`: use a hardlink to quickly create the backup
195 """
196 """
196 if self._queue:
197 if self._queue:
197 msg = 'cannot use transaction.addbackup inside "group"'
198 msg = 'cannot use transaction.addbackup inside "group"'
198 raise RuntimeError(msg)
199 raise RuntimeError(msg)
199
200
200 if file in self.map or file in self._backupmap:
201 if file in self.map or file in self._backupmap:
201 return
202 return
202 vfs = self._vfsmap[location]
203 vfs = self._vfsmap[location]
203 dirname, filename = vfs.split(file)
204 dirname, filename = vfs.split(file)
204 backupfilename = "%s.backup.%s" % (self.journal, filename)
205 backupfilename = "%s.backup.%s" % (self.journal, filename)
205 backupfile = vfs.reljoin(dirname, backupfilename)
206 backupfile = vfs.reljoin(dirname, backupfilename)
206 if vfs.exists(file):
207 if vfs.exists(file):
207 filepath = vfs.join(file)
208 filepath = vfs.join(file)
208 backuppath = vfs.join(backupfile)
209 backuppath = vfs.join(backupfile)
209 util.copyfile(filepath, backuppath, hardlink=hardlink)
210 util.copyfile(filepath, backuppath, hardlink=hardlink)
210 else:
211 else:
211 backupfile = ''
212 backupfile = ''
212
213
213 self._addbackupentry((location, file, backupfile, False))
214 self._addbackupentry((location, file, backupfile, False))
214
215
215 def _addbackupentry(self, entry):
216 def _addbackupentry(self, entry):
216 """register a new backup entry and write it to disk"""
217 """register a new backup entry and write it to disk"""
217 self._backupentries.append(entry)
218 self._backupentries.append(entry)
218 self._backupmap[file] = len(self._backupentries) - 1
219 self._backupmap[file] = len(self._backupentries) - 1
219 self._backupsfile.write("%s\0%s\0%s\0%d\n" % entry)
220 self._backupsfile.write("%s\0%s\0%s\0%d\n" % entry)
220 self._backupsfile.flush()
221 self._backupsfile.flush()
221
222
222 @active
223 @active
223 def registertmp(self, tmpfile, location=''):
224 def registertmp(self, tmpfile, location=''):
224 """register a temporary transaction file
225 """register a temporary transaction file
225
226
226 Such files will be deleted when the transaction exits (on both
227 Such files will be deleted when the transaction exits (on both
227 failure and success).
228 failure and success).
228 """
229 """
229 self._addbackupentry((location, '', tmpfile, False))
230 self._addbackupentry((location, '', tmpfile, False))
230
231
231 @active
232 @active
232 def addfilegenerator(self, genid, filenames, genfunc, order=0,
233 def addfilegenerator(self, genid, filenames, genfunc, order=0,
233 location=''):
234 location=''):
234 """add a function to generates some files at transaction commit
235 """add a function to generates some files at transaction commit
235
236
236 The `genfunc` argument is a function capable of generating proper
237 The `genfunc` argument is a function capable of generating proper
237 content of each entry in the `filename` tuple.
238 content of each entry in the `filename` tuple.
238
239
239 At transaction close time, `genfunc` will be called with one file
240 At transaction close time, `genfunc` will be called with one file
240 object argument per entries in `filenames`.
241 object argument per entries in `filenames`.
241
242
242 The transaction itself is responsible for the backup, creation and
243 The transaction itself is responsible for the backup, creation and
243 final write of such file.
244 final write of such file.
244
245
245 The `genid` argument is used to ensure the same set of file is only
246 The `genid` argument is used to ensure the same set of file is only
246 generated once. Call to `addfilegenerator` for a `genid` already
247 generated once. Call to `addfilegenerator` for a `genid` already
247 present will overwrite the old entry.
248 present will overwrite the old entry.
248
249
249 The `order` argument may be used to control the order in which multiple
250 The `order` argument may be used to control the order in which multiple
250 generator will be executed.
251 generator will be executed.
251
252
252 The `location` arguments may be used to indicate the files are located
253 The `location` arguments may be used to indicate the files are located
253 outside of the the standard directory for transaction. It should match
254 outside of the the standard directory for transaction. It should match
254 one of the key of the `transaction.vfsmap` dictionary.
255 one of the key of the `transaction.vfsmap` dictionary.
255 """
256 """
256 # For now, we are unable to do proper backup and restore of custom vfs
257 # For now, we are unable to do proper backup and restore of custom vfs
257 # but for bookmarks that are handled outside this mechanism.
258 # but for bookmarks that are handled outside this mechanism.
258 self._filegenerators[genid] = (order, filenames, genfunc, location)
259 self._filegenerators[genid] = (order, filenames, genfunc, location)
259
260
260 def _generatefiles(self, suffix=''):
261 def _generatefiles(self, suffix=''):
261 # write files registered for generation
262 # write files registered for generation
262 any = False
263 any = False
263 for entry in sorted(self._filegenerators.values()):
264 for entry in sorted(self._filegenerators.values()):
264 any = True
265 any = True
265 order, filenames, genfunc, location = entry
266 order, filenames, genfunc, location = entry
266 vfs = self._vfsmap[location]
267 vfs = self._vfsmap[location]
267 files = []
268 files = []
268 try:
269 try:
269 for name in filenames:
270 for name in filenames:
270 name += suffix
271 name += suffix
271 if suffix:
272 if suffix:
272 self.registertmp(name, location=location)
273 self.registertmp(name, location=location)
273 else:
274 else:
274 self.addbackup(name, location=location)
275 self.addbackup(name, location=location)
275 files.append(vfs(name, 'w', atomictemp=True))
276 files.append(vfs(name, 'w', atomictemp=True))
276 genfunc(*files)
277 genfunc(*files)
277 finally:
278 finally:
278 for f in files:
279 for f in files:
279 f.close()
280 f.close()
280 return any
281 return any
281
282
282 @active
283 @active
283 def find(self, file):
284 def find(self, file):
284 if file in self.map:
285 if file in self.map:
285 return self.entries[self.map[file]]
286 return self.entries[self.map[file]]
286 if file in self._backupmap:
287 if file in self._backupmap:
287 return self._backupentries[self._backupmap[file]]
288 return self._backupentries[self._backupmap[file]]
288 return None
289 return None
289
290
290 @active
291 @active
291 def replace(self, file, offset, data=None):
292 def replace(self, file, offset, data=None):
292 '''
293 '''
293 replace can only replace already committed entries
294 replace can only replace already committed entries
294 that are not pending in the queue
295 that are not pending in the queue
295 '''
296 '''
296
297
297 if file not in self.map:
298 if file not in self.map:
298 raise KeyError(file)
299 raise KeyError(file)
299 index = self.map[file]
300 index = self.map[file]
300 self.entries[index] = (file, offset, data)
301 self.entries[index] = (file, offset, data)
301 self.file.write("%s\0%d\n" % (file, offset))
302 self.file.write("%s\0%d\n" % (file, offset))
302 self.file.flush()
303 self.file.flush()
303
304
304 @active
305 @active
305 def nest(self):
306 def nest(self):
306 self.count += 1
307 self.count += 1
307 self.usages += 1
308 self.usages += 1
308 return self
309 return self
309
310
310 def release(self):
311 def release(self):
311 if self.count > 0:
312 if self.count > 0:
312 self.usages -= 1
313 self.usages -= 1
313 # if the transaction scopes are left without being closed, fail
314 # if the transaction scopes are left without being closed, fail
314 if self.count > 0 and self.usages == 0:
315 if self.count > 0 and self.usages == 0:
315 self._abort()
316 self._abort()
316
317
317 def running(self):
318 def running(self):
318 return self.count > 0
319 return self.count > 0
319
320
320 def addpending(self, category, callback):
321 def addpending(self, category, callback):
321 """add a callback to be called when the transaction is pending
322 """add a callback to be called when the transaction is pending
322
323
323 The transaction will be given as callback's first argument.
324 The transaction will be given as callback's first argument.
324
325
325 Category is a unique identifier to allow overwriting an old callback
326 Category is a unique identifier to allow overwriting an old callback
326 with a newer callback.
327 with a newer callback.
327 """
328 """
328 self._pendingcallback[category] = callback
329 self._pendingcallback[category] = callback
329
330
330 @active
331 @active
331 def writepending(self):
332 def writepending(self):
332 '''write pending file to temporary version
333 '''write pending file to temporary version
333
334
334 This is used to allow hooks to view a transaction before commit'''
335 This is used to allow hooks to view a transaction before commit'''
335 categories = sorted(self._pendingcallback)
336 categories = sorted(self._pendingcallback)
336 for cat in categories:
337 for cat in categories:
337 # remove callback since the data will have been flushed
338 # remove callback since the data will have been flushed
338 any = self._pendingcallback.pop(cat)(self)
339 any = self._pendingcallback.pop(cat)(self)
339 self._anypending = self._anypending or any
340 self._anypending = self._anypending or any
340 self._anypending |= self._generatefiles(suffix='.pending')
341 self._anypending |= self._generatefiles(suffix='.pending')
341 return self._anypending
342 return self._anypending
342
343
343 @active
344 @active
344 def addfinalize(self, category, callback):
345 def addfinalize(self, category, callback):
345 """add a callback to be called when the transaction is closed
346 """add a callback to be called when the transaction is closed
346
347
347 The transaction will be given as callback's first argument.
348 The transaction will be given as callback's first argument.
348
349
349 Category is a unique identifier to allow overwriting old callbacks with
350 Category is a unique identifier to allow overwriting old callbacks with
350 newer callbacks.
351 newer callbacks.
351 """
352 """
352 self._finalizecallback[category] = callback
353 self._finalizecallback[category] = callback
353
354
354 @active
355 @active
355 def addpostclose(self, category, callback):
356 def addpostclose(self, category, callback):
356 """add a callback to be called after the transaction is closed
357 """add a callback to be called after the transaction is closed
357
358
358 The transaction will be given as callback's first argument.
359 The transaction will be given as callback's first argument.
359
360
360 Category is a unique identifier to allow overwriting an old callback
361 Category is a unique identifier to allow overwriting an old callback
361 with a newer callback.
362 with a newer callback.
362 """
363 """
363 self._postclosecallback[category] = callback
364 self._postclosecallback[category] = callback
364
365
365 @active
366 @active
366 def addabort(self, category, callback):
367 def addabort(self, category, callback):
367 """add a callback to be called when the transaction is aborted.
368 """add a callback to be called when the transaction is aborted.
368
369
369 The transaction will be given as the first argument to the callback.
370 The transaction will be given as the first argument to the callback.
370
371
371 Category is a unique identifier to allow overwriting an old callback
372 Category is a unique identifier to allow overwriting an old callback
372 with a newer callback.
373 with a newer callback.
373 """
374 """
374 self._abortcallback[category] = callback
375 self._abortcallback[category] = callback
375
376
376 @active
377 @active
377 def close(self):
378 def close(self):
378 '''commit the transaction'''
379 '''commit the transaction'''
379 if self.count == 1:
380 if self.count == 1:
380 self._generatefiles()
381 self._generatefiles()
381 categories = sorted(self._finalizecallback)
382 categories = sorted(self._finalizecallback)
382 for cat in categories:
383 for cat in categories:
383 self._finalizecallback[cat](self)
384 self._finalizecallback[cat](self)
384
385
385 self.count -= 1
386 self.count -= 1
386 if self.count != 0:
387 if self.count != 0:
387 return
388 return
388 self.file.close()
389 self.file.close()
389 self._backupsfile.close()
390 self._backupsfile.close()
390 # cleanup temporary files
391 # cleanup temporary files
391 for l, f, b, c in self._backupentries:
392 for l, f, b, c in self._backupentries:
392 if l not in self._vfsmap and c:
393 if l not in self._vfsmap and c:
393 self.report("couldn't remote %s: unknown cache location %s\n"
394 self.report("couldn't remote %s: unknown cache location %s\n"
394 % (b, l))
395 % (b, l))
395 continue
396 continue
396 vfs = self._vfsmap[l]
397 vfs = self._vfsmap[l]
397 if not f and b and vfs.exists(b):
398 if not f and b and vfs.exists(b):
398 try:
399 try:
399 vfs.unlink(b)
400 vfs.unlink(b)
400 except (IOError, OSError, util.Abort), inst:
401 except (IOError, OSError, util.Abort), inst:
401 if not c:
402 if not c:
402 raise
403 raise
403 # Abort may be raise by read only opener
404 # Abort may be raise by read only opener
404 self.report("couldn't remote %s: %s\n"
405 self.report("couldn't remote %s: %s\n"
405 % (vfs.join(b), inst))
406 % (vfs.join(b), inst))
406 self.entries = []
407 self.entries = []
407 if self.after:
408 if self.after:
408 self.after()
409 self.after()
409 if self.opener.isfile(self.journal):
410 if self.opener.isfile(self.journal):
410 self.opener.unlink(self.journal)
411 self.opener.unlink(self.journal)
411 if self.opener.isfile(self._backupjournal):
412 if self.opener.isfile(self._backupjournal):
412 self.opener.unlink(self._backupjournal)
413 self.opener.unlink(self._backupjournal)
413 for l, _f, b, c in self._backupentries:
414 for l, _f, b, c in self._backupentries:
414 if l not in self._vfsmap and c:
415 if l not in self._vfsmap and c:
415 self.report("couldn't remote %s: unknown cache location"
416 self.report("couldn't remote %s: unknown cache location"
416 "%s\n" % (b, l))
417 "%s\n" % (b, l))
417 continue
418 continue
418 vfs = self._vfsmap[l]
419 vfs = self._vfsmap[l]
419 if b and vfs.exists(b):
420 if b and vfs.exists(b):
420 try:
421 try:
421 vfs.unlink(b)
422 vfs.unlink(b)
422 except (IOError, OSError, util.Abort), inst:
423 except (IOError, OSError, util.Abort), inst:
423 if not c:
424 if not c:
424 raise
425 raise
425 # Abort may be raise by read only opener
426 # Abort may be raise by read only opener
426 self.report("couldn't remote %s: %s\n"
427 self.report("couldn't remote %s: %s\n"
427 % (vfs.join(b), inst))
428 % (vfs.join(b), inst))
428 self._backupentries = []
429 self._backupentries = []
429 self.journal = None
430 self.journal = None
430 # run post close action
431 # run post close action
431 categories = sorted(self._postclosecallback)
432 categories = sorted(self._postclosecallback)
432 for cat in categories:
433 for cat in categories:
433 self._postclosecallback[cat](self)
434 self._postclosecallback[cat](self)
434
435
435 @active
436 @active
436 def abort(self):
437 def abort(self):
437 '''abort the transaction (generally called on error, or when the
438 '''abort the transaction (generally called on error, or when the
438 transaction is not explicitly committed before going out of
439 transaction is not explicitly committed before going out of
439 scope)'''
440 scope)'''
440 self._abort()
441 self._abort()
441
442
442 def _abort(self):
443 def _abort(self):
443 self.count = 0
444 self.count = 0
444 self.usages = 0
445 self.usages = 0
445 self.file.close()
446 self.file.close()
446 self._backupsfile.close()
447 self._backupsfile.close()
447
448
448 try:
449 try:
449 if not self.entries and not self._backupentries:
450 if not self.entries and not self._backupentries:
450 if self.journal:
451 if self.journal:
451 self.opener.unlink(self.journal)
452 self.opener.unlink(self.journal)
452 if self._backupjournal:
453 if self._backupjournal:
453 self.opener.unlink(self._backupjournal)
454 self.opener.unlink(self._backupjournal)
454 return
455 return
455
456
456 self.report(_("transaction abort!\n"))
457 self.report(_("transaction abort!\n"))
457
458
458 try:
459 try:
459 for cat in sorted(self._abortcallback):
460 for cat in sorted(self._abortcallback):
460 self._abortcallback[cat](self)
461 self._abortcallback[cat](self)
461 _playback(self.journal, self.report, self.opener, self._vfsmap,
462 _playback(self.journal, self.report, self.opener, self._vfsmap,
462 self.entries, self._backupentries, False)
463 self.entries, self._backupentries, False)
463 self.report(_("rollback completed\n"))
464 self.report(_("rollback completed\n"))
464 except Exception:
465 except Exception:
465 self.report(_("rollback failed - please run hg recover\n"))
466 self.report(_("rollback failed - please run hg recover\n"))
466 finally:
467 finally:
467 self.journal = None
468 self.journal = None
468
469
469
470
470 def rollback(opener, vfsmap, file, report):
471 def rollback(opener, vfsmap, file, report):
471 """Rolls back the transaction contained in the given file
472 """Rolls back the transaction contained in the given file
472
473
473 Reads the entries in the specified file, and the corresponding
474 Reads the entries in the specified file, and the corresponding
474 '*.backupfiles' file, to recover from an incomplete transaction.
475 '*.backupfiles' file, to recover from an incomplete transaction.
475
476
476 * `file`: a file containing a list of entries, specifying where
477 * `file`: a file containing a list of entries, specifying where
477 to truncate each file. The file should contain a list of
478 to truncate each file. The file should contain a list of
478 file\0offset pairs, delimited by newlines. The corresponding
479 file\0offset pairs, delimited by newlines. The corresponding
479 '*.backupfiles' file should contain a list of file\0backupfile
480 '*.backupfiles' file should contain a list of file\0backupfile
480 pairs, delimited by \0.
481 pairs, delimited by \0.
481 """
482 """
482 entries = []
483 entries = []
483 backupentries = []
484 backupentries = []
484
485
485 fp = opener.open(file)
486 fp = opener.open(file)
486 lines = fp.readlines()
487 lines = fp.readlines()
487 fp.close()
488 fp.close()
488 for l in lines:
489 for l in lines:
489 try:
490 try:
490 f, o = l.split('\0')
491 f, o = l.split('\0')
491 entries.append((f, int(o), None))
492 entries.append((f, int(o), None))
492 except ValueError:
493 except ValueError:
493 report(_("couldn't read journal entry %r!\n") % l)
494 report(_("couldn't read journal entry %r!\n") % l)
494
495
495 backupjournal = "%s.backupfiles" % file
496 backupjournal = "%s.backupfiles" % file
496 if opener.exists(backupjournal):
497 if opener.exists(backupjournal):
497 fp = opener.open(backupjournal)
498 fp = opener.open(backupjournal)
498 lines = fp.readlines()
499 lines = fp.readlines()
499 if lines:
500 if lines:
500 ver = lines[0][:-1]
501 ver = lines[0][:-1]
501 if ver == str(version):
502 if ver == str(version):
502 for line in lines[1:]:
503 for line in lines[1:]:
503 if line:
504 if line:
504 # Shave off the trailing newline
505 # Shave off the trailing newline
505 line = line[:-1]
506 line = line[:-1]
506 l, f, b, c = line.split('\0')
507 l, f, b, c = line.split('\0')
507 backupentries.append((l, f, b, bool(c)))
508 backupentries.append((l, f, b, bool(c)))
508 else:
509 else:
509 report(_("journal was created by a different version of "
510 report(_("journal was created by a different version of "
510 "Mercurial"))
511 "Mercurial"))
511
512
512 _playback(file, report, opener, vfsmap, entries, backupentries)
513 _playback(file, report, opener, vfsmap, entries, backupentries)
General Comments 0
You need to be logged in to leave comments. Login now