##// END OF EJS Templates
obsolete: add a "format.obsstore-version" config option...
Pierre-Yves David -
r22852:e994b034 default
parent child Browse files
Show More
@@ -1,1781 +1,1787
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 propertycache = util.propertycache
21 propertycache = util.propertycache
22 filecache = scmutil.filecache
22 filecache = scmutil.filecache
23
23
24 class repofilecache(filecache):
24 class repofilecache(filecache):
25 """All filecache usage on repo are done for logic that should be unfiltered
25 """All filecache usage on repo are done for logic that should be unfiltered
26 """
26 """
27
27
28 def __get__(self, repo, type=None):
28 def __get__(self, repo, type=None):
29 return super(repofilecache, self).__get__(repo.unfiltered(), type)
29 return super(repofilecache, self).__get__(repo.unfiltered(), type)
30 def __set__(self, repo, value):
30 def __set__(self, repo, value):
31 return super(repofilecache, self).__set__(repo.unfiltered(), value)
31 return super(repofilecache, self).__set__(repo.unfiltered(), value)
32 def __delete__(self, repo):
32 def __delete__(self, repo):
33 return super(repofilecache, self).__delete__(repo.unfiltered())
33 return super(repofilecache, self).__delete__(repo.unfiltered())
34
34
35 class storecache(repofilecache):
35 class storecache(repofilecache):
36 """filecache for files in the store"""
36 """filecache for files in the store"""
37 def join(self, obj, fname):
37 def join(self, obj, fname):
38 return obj.sjoin(fname)
38 return obj.sjoin(fname)
39
39
40 class unfilteredpropertycache(propertycache):
40 class unfilteredpropertycache(propertycache):
41 """propertycache that apply to unfiltered repo only"""
41 """propertycache that apply to unfiltered repo only"""
42
42
43 def __get__(self, repo, type=None):
43 def __get__(self, repo, type=None):
44 unfi = repo.unfiltered()
44 unfi = repo.unfiltered()
45 if unfi is repo:
45 if unfi is repo:
46 return super(unfilteredpropertycache, self).__get__(unfi)
46 return super(unfilteredpropertycache, self).__get__(unfi)
47 return getattr(unfi, self.name)
47 return getattr(unfi, self.name)
48
48
49 class filteredpropertycache(propertycache):
49 class filteredpropertycache(propertycache):
50 """propertycache that must take filtering in account"""
50 """propertycache that must take filtering in account"""
51
51
52 def cachevalue(self, obj, value):
52 def cachevalue(self, obj, value):
53 object.__setattr__(obj, self.name, value)
53 object.__setattr__(obj, self.name, value)
54
54
55
55
56 def hasunfilteredcache(repo, name):
56 def hasunfilteredcache(repo, name):
57 """check if a repo has an unfilteredpropertycache value for <name>"""
57 """check if a repo has an unfilteredpropertycache value for <name>"""
58 return name in vars(repo.unfiltered())
58 return name in vars(repo.unfiltered())
59
59
60 def unfilteredmethod(orig):
60 def unfilteredmethod(orig):
61 """decorate method that always need to be run on unfiltered version"""
61 """decorate method that always need to be run on unfiltered version"""
62 def wrapper(repo, *args, **kwargs):
62 def wrapper(repo, *args, **kwargs):
63 return orig(repo.unfiltered(), *args, **kwargs)
63 return orig(repo.unfiltered(), *args, **kwargs)
64 return wrapper
64 return wrapper
65
65
66 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
66 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
67 'unbundle'))
67 'unbundle'))
68 legacycaps = moderncaps.union(set(['changegroupsubset']))
68 legacycaps = moderncaps.union(set(['changegroupsubset']))
69
69
70 class localpeer(peer.peerrepository):
70 class localpeer(peer.peerrepository):
71 '''peer for a local repo; reflects only the most recent API'''
71 '''peer for a local repo; reflects only the most recent API'''
72
72
73 def __init__(self, repo, caps=moderncaps):
73 def __init__(self, repo, caps=moderncaps):
74 peer.peerrepository.__init__(self)
74 peer.peerrepository.__init__(self)
75 self._repo = repo.filtered('served')
75 self._repo = repo.filtered('served')
76 self.ui = repo.ui
76 self.ui = repo.ui
77 self._caps = repo._restrictcapabilities(caps)
77 self._caps = repo._restrictcapabilities(caps)
78 self.requirements = repo.requirements
78 self.requirements = repo.requirements
79 self.supportedformats = repo.supportedformats
79 self.supportedformats = repo.supportedformats
80
80
81 def close(self):
81 def close(self):
82 self._repo.close()
82 self._repo.close()
83
83
84 def _capabilities(self):
84 def _capabilities(self):
85 return self._caps
85 return self._caps
86
86
87 def local(self):
87 def local(self):
88 return self._repo
88 return self._repo
89
89
90 def canpush(self):
90 def canpush(self):
91 return True
91 return True
92
92
93 def url(self):
93 def url(self):
94 return self._repo.url()
94 return self._repo.url()
95
95
96 def lookup(self, key):
96 def lookup(self, key):
97 return self._repo.lookup(key)
97 return self._repo.lookup(key)
98
98
99 def branchmap(self):
99 def branchmap(self):
100 return self._repo.branchmap()
100 return self._repo.branchmap()
101
101
102 def heads(self):
102 def heads(self):
103 return self._repo.heads()
103 return self._repo.heads()
104
104
105 def known(self, nodes):
105 def known(self, nodes):
106 return self._repo.known(nodes)
106 return self._repo.known(nodes)
107
107
108 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
108 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
109 format='HG10', **kwargs):
109 format='HG10', **kwargs):
110 cg = exchange.getbundle(self._repo, source, heads=heads,
110 cg = exchange.getbundle(self._repo, source, heads=heads,
111 common=common, bundlecaps=bundlecaps, **kwargs)
111 common=common, bundlecaps=bundlecaps, **kwargs)
112 if bundlecaps is not None and 'HG2X' in bundlecaps:
112 if bundlecaps is not None and 'HG2X' in bundlecaps:
113 # When requesting a bundle2, getbundle returns a stream to make the
113 # When requesting a bundle2, getbundle returns a stream to make the
114 # wire level function happier. We need to build a proper object
114 # wire level function happier. We need to build a proper object
115 # from it in local peer.
115 # from it in local peer.
116 cg = bundle2.unbundle20(self.ui, cg)
116 cg = bundle2.unbundle20(self.ui, cg)
117 return cg
117 return cg
118
118
119 # TODO We might want to move the next two calls into legacypeer and add
119 # TODO We might want to move the next two calls into legacypeer and add
120 # unbundle instead.
120 # unbundle instead.
121
121
122 def unbundle(self, cg, heads, url):
122 def unbundle(self, cg, heads, url):
123 """apply a bundle on a repo
123 """apply a bundle on a repo
124
124
125 This function handles the repo locking itself."""
125 This function handles the repo locking itself."""
126 try:
126 try:
127 cg = exchange.readbundle(self.ui, cg, None)
127 cg = exchange.readbundle(self.ui, cg, None)
128 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
128 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
129 if util.safehasattr(ret, 'getchunks'):
129 if util.safehasattr(ret, 'getchunks'):
130 # This is a bundle20 object, turn it into an unbundler.
130 # This is a bundle20 object, turn it into an unbundler.
131 # This little dance should be dropped eventually when the API
131 # This little dance should be dropped eventually when the API
132 # is finally improved.
132 # is finally improved.
133 stream = util.chunkbuffer(ret.getchunks())
133 stream = util.chunkbuffer(ret.getchunks())
134 ret = bundle2.unbundle20(self.ui, stream)
134 ret = bundle2.unbundle20(self.ui, stream)
135 return ret
135 return ret
136 except error.PushRaced, exc:
136 except error.PushRaced, exc:
137 raise error.ResponseError(_('push failed:'), str(exc))
137 raise error.ResponseError(_('push failed:'), str(exc))
138
138
139 def lock(self):
139 def lock(self):
140 return self._repo.lock()
140 return self._repo.lock()
141
141
142 def addchangegroup(self, cg, source, url):
142 def addchangegroup(self, cg, source, url):
143 return changegroup.addchangegroup(self._repo, cg, source, url)
143 return changegroup.addchangegroup(self._repo, cg, source, url)
144
144
145 def pushkey(self, namespace, key, old, new):
145 def pushkey(self, namespace, key, old, new):
146 return self._repo.pushkey(namespace, key, old, new)
146 return self._repo.pushkey(namespace, key, old, new)
147
147
148 def listkeys(self, namespace):
148 def listkeys(self, namespace):
149 return self._repo.listkeys(namespace)
149 return self._repo.listkeys(namespace)
150
150
151 def debugwireargs(self, one, two, three=None, four=None, five=None):
151 def debugwireargs(self, one, two, three=None, four=None, five=None):
152 '''used to test argument passing over the wire'''
152 '''used to test argument passing over the wire'''
153 return "%s %s %s %s %s" % (one, two, three, four, five)
153 return "%s %s %s %s %s" % (one, two, three, four, five)
154
154
155 class locallegacypeer(localpeer):
155 class locallegacypeer(localpeer):
156 '''peer extension which implements legacy methods too; used for tests with
156 '''peer extension which implements legacy methods too; used for tests with
157 restricted capabilities'''
157 restricted capabilities'''
158
158
159 def __init__(self, repo):
159 def __init__(self, repo):
160 localpeer.__init__(self, repo, caps=legacycaps)
160 localpeer.__init__(self, repo, caps=legacycaps)
161
161
162 def branches(self, nodes):
162 def branches(self, nodes):
163 return self._repo.branches(nodes)
163 return self._repo.branches(nodes)
164
164
165 def between(self, pairs):
165 def between(self, pairs):
166 return self._repo.between(pairs)
166 return self._repo.between(pairs)
167
167
168 def changegroup(self, basenodes, source):
168 def changegroup(self, basenodes, source):
169 return changegroup.changegroup(self._repo, basenodes, source)
169 return changegroup.changegroup(self._repo, basenodes, source)
170
170
171 def changegroupsubset(self, bases, heads, source):
171 def changegroupsubset(self, bases, heads, source):
172 return changegroup.changegroupsubset(self._repo, bases, heads, source)
172 return changegroup.changegroupsubset(self._repo, bases, heads, source)
173
173
174 class localrepository(object):
174 class localrepository(object):
175
175
176 supportedformats = set(('revlogv1', 'generaldelta'))
176 supportedformats = set(('revlogv1', 'generaldelta'))
177 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
177 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
178 'dotencode'))
178 'dotencode'))
179 openerreqs = set(('revlogv1', 'generaldelta'))
179 openerreqs = set(('revlogv1', 'generaldelta'))
180 requirements = ['revlogv1']
180 requirements = ['revlogv1']
181 filtername = None
181 filtername = None
182
182
183 # a list of (ui, featureset) functions.
183 # a list of (ui, featureset) functions.
184 # only functions defined in module of enabled extensions are invoked
184 # only functions defined in module of enabled extensions are invoked
185 featuresetupfuncs = set()
185 featuresetupfuncs = set()
186
186
187 def _baserequirements(self, create):
187 def _baserequirements(self, create):
188 return self.requirements[:]
188 return self.requirements[:]
189
189
190 def __init__(self, baseui, path=None, create=False):
190 def __init__(self, baseui, path=None, create=False):
191 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
191 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
192 self.wopener = self.wvfs
192 self.wopener = self.wvfs
193 self.root = self.wvfs.base
193 self.root = self.wvfs.base
194 self.path = self.wvfs.join(".hg")
194 self.path = self.wvfs.join(".hg")
195 self.origroot = path
195 self.origroot = path
196 self.auditor = pathutil.pathauditor(self.root, self._checknested)
196 self.auditor = pathutil.pathauditor(self.root, self._checknested)
197 self.vfs = scmutil.vfs(self.path)
197 self.vfs = scmutil.vfs(self.path)
198 self.opener = self.vfs
198 self.opener = self.vfs
199 self.baseui = baseui
199 self.baseui = baseui
200 self.ui = baseui.copy()
200 self.ui = baseui.copy()
201 self.ui.copy = baseui.copy # prevent copying repo configuration
201 self.ui.copy = baseui.copy # prevent copying repo configuration
202 # A list of callback to shape the phase if no data were found.
202 # A list of callback to shape the phase if no data were found.
203 # Callback are in the form: func(repo, roots) --> processed root.
203 # Callback are in the form: func(repo, roots) --> processed root.
204 # This list it to be filled by extension during repo setup
204 # This list it to be filled by extension during repo setup
205 self._phasedefaults = []
205 self._phasedefaults = []
206 try:
206 try:
207 self.ui.readconfig(self.join("hgrc"), self.root)
207 self.ui.readconfig(self.join("hgrc"), self.root)
208 extensions.loadall(self.ui)
208 extensions.loadall(self.ui)
209 except IOError:
209 except IOError:
210 pass
210 pass
211
211
212 if self.featuresetupfuncs:
212 if self.featuresetupfuncs:
213 self.supported = set(self._basesupported) # use private copy
213 self.supported = set(self._basesupported) # use private copy
214 extmods = set(m.__name__ for n, m
214 extmods = set(m.__name__ for n, m
215 in extensions.extensions(self.ui))
215 in extensions.extensions(self.ui))
216 for setupfunc in self.featuresetupfuncs:
216 for setupfunc in self.featuresetupfuncs:
217 if setupfunc.__module__ in extmods:
217 if setupfunc.__module__ in extmods:
218 setupfunc(self.ui, self.supported)
218 setupfunc(self.ui, self.supported)
219 else:
219 else:
220 self.supported = self._basesupported
220 self.supported = self._basesupported
221
221
222 if not self.vfs.isdir():
222 if not self.vfs.isdir():
223 if create:
223 if create:
224 if not self.wvfs.exists():
224 if not self.wvfs.exists():
225 self.wvfs.makedirs()
225 self.wvfs.makedirs()
226 self.vfs.makedir(notindexed=True)
226 self.vfs.makedir(notindexed=True)
227 requirements = self._baserequirements(create)
227 requirements = self._baserequirements(create)
228 if self.ui.configbool('format', 'usestore', True):
228 if self.ui.configbool('format', 'usestore', True):
229 self.vfs.mkdir("store")
229 self.vfs.mkdir("store")
230 requirements.append("store")
230 requirements.append("store")
231 if self.ui.configbool('format', 'usefncache', True):
231 if self.ui.configbool('format', 'usefncache', True):
232 requirements.append("fncache")
232 requirements.append("fncache")
233 if self.ui.configbool('format', 'dotencode', True):
233 if self.ui.configbool('format', 'dotencode', True):
234 requirements.append('dotencode')
234 requirements.append('dotencode')
235 # create an invalid changelog
235 # create an invalid changelog
236 self.vfs.append(
236 self.vfs.append(
237 "00changelog.i",
237 "00changelog.i",
238 '\0\0\0\2' # represents revlogv2
238 '\0\0\0\2' # represents revlogv2
239 ' dummy changelog to prevent using the old repo layout'
239 ' dummy changelog to prevent using the old repo layout'
240 )
240 )
241 if self.ui.configbool('format', 'generaldelta', False):
241 if self.ui.configbool('format', 'generaldelta', False):
242 requirements.append("generaldelta")
242 requirements.append("generaldelta")
243 requirements = set(requirements)
243 requirements = set(requirements)
244 else:
244 else:
245 raise error.RepoError(_("repository %s not found") % path)
245 raise error.RepoError(_("repository %s not found") % path)
246 elif create:
246 elif create:
247 raise error.RepoError(_("repository %s already exists") % path)
247 raise error.RepoError(_("repository %s already exists") % path)
248 else:
248 else:
249 try:
249 try:
250 requirements = scmutil.readrequires(self.vfs, self.supported)
250 requirements = scmutil.readrequires(self.vfs, self.supported)
251 except IOError, inst:
251 except IOError, inst:
252 if inst.errno != errno.ENOENT:
252 if inst.errno != errno.ENOENT:
253 raise
253 raise
254 requirements = set()
254 requirements = set()
255
255
256 self.sharedpath = self.path
256 self.sharedpath = self.path
257 try:
257 try:
258 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
258 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
259 realpath=True)
259 realpath=True)
260 s = vfs.base
260 s = vfs.base
261 if not vfs.exists():
261 if not vfs.exists():
262 raise error.RepoError(
262 raise error.RepoError(
263 _('.hg/sharedpath points to nonexistent directory %s') % s)
263 _('.hg/sharedpath points to nonexistent directory %s') % s)
264 self.sharedpath = s
264 self.sharedpath = s
265 except IOError, inst:
265 except IOError, inst:
266 if inst.errno != errno.ENOENT:
266 if inst.errno != errno.ENOENT:
267 raise
267 raise
268
268
269 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
269 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
270 self.spath = self.store.path
270 self.spath = self.store.path
271 self.svfs = self.store.vfs
271 self.svfs = self.store.vfs
272 self.sopener = self.svfs
272 self.sopener = self.svfs
273 self.sjoin = self.store.join
273 self.sjoin = self.store.join
274 self.vfs.createmode = self.store.createmode
274 self.vfs.createmode = self.store.createmode
275 self._applyrequirements(requirements)
275 self._applyrequirements(requirements)
276 if create:
276 if create:
277 self._writerequirements()
277 self._writerequirements()
278
278
279
279
280 self._branchcaches = {}
280 self._branchcaches = {}
281 self.filterpats = {}
281 self.filterpats = {}
282 self._datafilters = {}
282 self._datafilters = {}
283 self._transref = self._lockref = self._wlockref = None
283 self._transref = self._lockref = self._wlockref = None
284
284
285 # A cache for various files under .hg/ that tracks file changes,
285 # A cache for various files under .hg/ that tracks file changes,
286 # (used by the filecache decorator)
286 # (used by the filecache decorator)
287 #
287 #
288 # Maps a property name to its util.filecacheentry
288 # Maps a property name to its util.filecacheentry
289 self._filecache = {}
289 self._filecache = {}
290
290
291 # hold sets of revision to be filtered
291 # hold sets of revision to be filtered
292 # should be cleared when something might have changed the filter value:
292 # should be cleared when something might have changed the filter value:
293 # - new changesets,
293 # - new changesets,
294 # - phase change,
294 # - phase change,
295 # - new obsolescence marker,
295 # - new obsolescence marker,
296 # - working directory parent change,
296 # - working directory parent change,
297 # - bookmark changes
297 # - bookmark changes
298 self.filteredrevcache = {}
298 self.filteredrevcache = {}
299
299
300 def close(self):
300 def close(self):
301 pass
301 pass
302
302
303 def _restrictcapabilities(self, caps):
303 def _restrictcapabilities(self, caps):
304 # bundle2 is not ready for prime time, drop it unless explicitly
304 # bundle2 is not ready for prime time, drop it unless explicitly
305 # required by the tests (or some brave tester)
305 # required by the tests (or some brave tester)
306 if self.ui.configbool('experimental', 'bundle2-exp', False):
306 if self.ui.configbool('experimental', 'bundle2-exp', False):
307 caps = set(caps)
307 caps = set(caps)
308 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
308 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
309 caps.add('bundle2-exp=' + urllib.quote(capsblob))
309 caps.add('bundle2-exp=' + urllib.quote(capsblob))
310 return caps
310 return caps
311
311
312 def _applyrequirements(self, requirements):
312 def _applyrequirements(self, requirements):
313 self.requirements = requirements
313 self.requirements = requirements
314 self.sopener.options = dict((r, 1) for r in requirements
314 self.sopener.options = dict((r, 1) for r in requirements
315 if r in self.openerreqs)
315 if r in self.openerreqs)
316 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
316 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
317 if chunkcachesize is not None:
317 if chunkcachesize is not None:
318 self.sopener.options['chunkcachesize'] = chunkcachesize
318 self.sopener.options['chunkcachesize'] = chunkcachesize
319
319
320 def _writerequirements(self):
320 def _writerequirements(self):
321 reqfile = self.opener("requires", "w")
321 reqfile = self.opener("requires", "w")
322 for r in sorted(self.requirements):
322 for r in sorted(self.requirements):
323 reqfile.write("%s\n" % r)
323 reqfile.write("%s\n" % r)
324 reqfile.close()
324 reqfile.close()
325
325
326 def _checknested(self, path):
326 def _checknested(self, path):
327 """Determine if path is a legal nested repository."""
327 """Determine if path is a legal nested repository."""
328 if not path.startswith(self.root):
328 if not path.startswith(self.root):
329 return False
329 return False
330 subpath = path[len(self.root) + 1:]
330 subpath = path[len(self.root) + 1:]
331 normsubpath = util.pconvert(subpath)
331 normsubpath = util.pconvert(subpath)
332
332
333 # XXX: Checking against the current working copy is wrong in
333 # XXX: Checking against the current working copy is wrong in
334 # the sense that it can reject things like
334 # the sense that it can reject things like
335 #
335 #
336 # $ hg cat -r 10 sub/x.txt
336 # $ hg cat -r 10 sub/x.txt
337 #
337 #
338 # if sub/ is no longer a subrepository in the working copy
338 # if sub/ is no longer a subrepository in the working copy
339 # parent revision.
339 # parent revision.
340 #
340 #
341 # However, it can of course also allow things that would have
341 # However, it can of course also allow things that would have
342 # been rejected before, such as the above cat command if sub/
342 # been rejected before, such as the above cat command if sub/
343 # is a subrepository now, but was a normal directory before.
343 # is a subrepository now, but was a normal directory before.
344 # The old path auditor would have rejected by mistake since it
344 # The old path auditor would have rejected by mistake since it
345 # panics when it sees sub/.hg/.
345 # panics when it sees sub/.hg/.
346 #
346 #
347 # All in all, checking against the working copy seems sensible
347 # All in all, checking against the working copy seems sensible
348 # since we want to prevent access to nested repositories on
348 # since we want to prevent access to nested repositories on
349 # the filesystem *now*.
349 # the filesystem *now*.
350 ctx = self[None]
350 ctx = self[None]
351 parts = util.splitpath(subpath)
351 parts = util.splitpath(subpath)
352 while parts:
352 while parts:
353 prefix = '/'.join(parts)
353 prefix = '/'.join(parts)
354 if prefix in ctx.substate:
354 if prefix in ctx.substate:
355 if prefix == normsubpath:
355 if prefix == normsubpath:
356 return True
356 return True
357 else:
357 else:
358 sub = ctx.sub(prefix)
358 sub = ctx.sub(prefix)
359 return sub.checknested(subpath[len(prefix) + 1:])
359 return sub.checknested(subpath[len(prefix) + 1:])
360 else:
360 else:
361 parts.pop()
361 parts.pop()
362 return False
362 return False
363
363
364 def peer(self):
364 def peer(self):
365 return localpeer(self) # not cached to avoid reference cycle
365 return localpeer(self) # not cached to avoid reference cycle
366
366
367 def unfiltered(self):
367 def unfiltered(self):
368 """Return unfiltered version of the repository
368 """Return unfiltered version of the repository
369
369
370 Intended to be overwritten by filtered repo."""
370 Intended to be overwritten by filtered repo."""
371 return self
371 return self
372
372
373 def filtered(self, name):
373 def filtered(self, name):
374 """Return a filtered version of a repository"""
374 """Return a filtered version of a repository"""
375 # build a new class with the mixin and the current class
375 # build a new class with the mixin and the current class
376 # (possibly subclass of the repo)
376 # (possibly subclass of the repo)
377 class proxycls(repoview.repoview, self.unfiltered().__class__):
377 class proxycls(repoview.repoview, self.unfiltered().__class__):
378 pass
378 pass
379 return proxycls(self, name)
379 return proxycls(self, name)
380
380
381 @repofilecache('bookmarks')
381 @repofilecache('bookmarks')
382 def _bookmarks(self):
382 def _bookmarks(self):
383 return bookmarks.bmstore(self)
383 return bookmarks.bmstore(self)
384
384
385 @repofilecache('bookmarks.current')
385 @repofilecache('bookmarks.current')
386 def _bookmarkcurrent(self):
386 def _bookmarkcurrent(self):
387 return bookmarks.readcurrent(self)
387 return bookmarks.readcurrent(self)
388
388
389 def bookmarkheads(self, bookmark):
389 def bookmarkheads(self, bookmark):
390 name = bookmark.split('@', 1)[0]
390 name = bookmark.split('@', 1)[0]
391 heads = []
391 heads = []
392 for mark, n in self._bookmarks.iteritems():
392 for mark, n in self._bookmarks.iteritems():
393 if mark.split('@', 1)[0] == name:
393 if mark.split('@', 1)[0] == name:
394 heads.append(n)
394 heads.append(n)
395 return heads
395 return heads
396
396
397 @storecache('phaseroots')
397 @storecache('phaseroots')
398 def _phasecache(self):
398 def _phasecache(self):
399 return phases.phasecache(self, self._phasedefaults)
399 return phases.phasecache(self, self._phasedefaults)
400
400
401 @storecache('obsstore')
401 @storecache('obsstore')
402 def obsstore(self):
402 def obsstore(self):
403 store = obsolete.obsstore(self.sopener)
403 # read default format for new obsstore.
404 defaultformat = self.ui.configint('format', 'obsstore-version', None)
405 # rely on obsstore class default when possible.
406 kwargs = {}
407 if defaultformat is not None:
408 defaultformat['defaultformat'] = defaultformat
409 store = obsolete.obsstore(self.sopener, **kwargs)
404 if store and not obsolete._enabled:
410 if store and not obsolete._enabled:
405 # message is rare enough to not be translated
411 # message is rare enough to not be translated
406 msg = 'obsolete feature not enabled but %i markers found!\n'
412 msg = 'obsolete feature not enabled but %i markers found!\n'
407 self.ui.warn(msg % len(list(store)))
413 self.ui.warn(msg % len(list(store)))
408 return store
414 return store
409
415
410 @storecache('00changelog.i')
416 @storecache('00changelog.i')
411 def changelog(self):
417 def changelog(self):
412 c = changelog.changelog(self.sopener)
418 c = changelog.changelog(self.sopener)
413 if 'HG_PENDING' in os.environ:
419 if 'HG_PENDING' in os.environ:
414 p = os.environ['HG_PENDING']
420 p = os.environ['HG_PENDING']
415 if p.startswith(self.root):
421 if p.startswith(self.root):
416 c.readpending('00changelog.i.a')
422 c.readpending('00changelog.i.a')
417 return c
423 return c
418
424
419 @storecache('00manifest.i')
425 @storecache('00manifest.i')
420 def manifest(self):
426 def manifest(self):
421 return manifest.manifest(self.sopener)
427 return manifest.manifest(self.sopener)
422
428
423 @repofilecache('dirstate')
429 @repofilecache('dirstate')
424 def dirstate(self):
430 def dirstate(self):
425 warned = [0]
431 warned = [0]
426 def validate(node):
432 def validate(node):
427 try:
433 try:
428 self.changelog.rev(node)
434 self.changelog.rev(node)
429 return node
435 return node
430 except error.LookupError:
436 except error.LookupError:
431 if not warned[0]:
437 if not warned[0]:
432 warned[0] = True
438 warned[0] = True
433 self.ui.warn(_("warning: ignoring unknown"
439 self.ui.warn(_("warning: ignoring unknown"
434 " working parent %s!\n") % short(node))
440 " working parent %s!\n") % short(node))
435 return nullid
441 return nullid
436
442
437 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
443 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
438
444
439 def __getitem__(self, changeid):
445 def __getitem__(self, changeid):
440 if changeid is None:
446 if changeid is None:
441 return context.workingctx(self)
447 return context.workingctx(self)
442 return context.changectx(self, changeid)
448 return context.changectx(self, changeid)
443
449
444 def __contains__(self, changeid):
450 def __contains__(self, changeid):
445 try:
451 try:
446 return bool(self.lookup(changeid))
452 return bool(self.lookup(changeid))
447 except error.RepoLookupError:
453 except error.RepoLookupError:
448 return False
454 return False
449
455
450 def __nonzero__(self):
456 def __nonzero__(self):
451 return True
457 return True
452
458
453 def __len__(self):
459 def __len__(self):
454 return len(self.changelog)
460 return len(self.changelog)
455
461
456 def __iter__(self):
462 def __iter__(self):
457 return iter(self.changelog)
463 return iter(self.changelog)
458
464
459 def revs(self, expr, *args):
465 def revs(self, expr, *args):
460 '''Return a list of revisions matching the given revset'''
466 '''Return a list of revisions matching the given revset'''
461 expr = revset.formatspec(expr, *args)
467 expr = revset.formatspec(expr, *args)
462 m = revset.match(None, expr)
468 m = revset.match(None, expr)
463 return m(self, revset.spanset(self))
469 return m(self, revset.spanset(self))
464
470
465 def set(self, expr, *args):
471 def set(self, expr, *args):
466 '''
472 '''
467 Yield a context for each matching revision, after doing arg
473 Yield a context for each matching revision, after doing arg
468 replacement via revset.formatspec
474 replacement via revset.formatspec
469 '''
475 '''
470 for r in self.revs(expr, *args):
476 for r in self.revs(expr, *args):
471 yield self[r]
477 yield self[r]
472
478
473 def url(self):
479 def url(self):
474 return 'file:' + self.root
480 return 'file:' + self.root
475
481
476 def hook(self, name, throw=False, **args):
482 def hook(self, name, throw=False, **args):
477 """Call a hook, passing this repo instance.
483 """Call a hook, passing this repo instance.
478
484
479 This a convenience method to aid invoking hooks. Extensions likely
485 This a convenience method to aid invoking hooks. Extensions likely
480 won't call this unless they have registered a custom hook or are
486 won't call this unless they have registered a custom hook or are
481 replacing code that is expected to call a hook.
487 replacing code that is expected to call a hook.
482 """
488 """
483 return hook.hook(self.ui, self, name, throw, **args)
489 return hook.hook(self.ui, self, name, throw, **args)
484
490
485 @unfilteredmethod
491 @unfilteredmethod
486 def _tag(self, names, node, message, local, user, date, extra={},
492 def _tag(self, names, node, message, local, user, date, extra={},
487 editor=False):
493 editor=False):
488 if isinstance(names, str):
494 if isinstance(names, str):
489 names = (names,)
495 names = (names,)
490
496
491 branches = self.branchmap()
497 branches = self.branchmap()
492 for name in names:
498 for name in names:
493 self.hook('pretag', throw=True, node=hex(node), tag=name,
499 self.hook('pretag', throw=True, node=hex(node), tag=name,
494 local=local)
500 local=local)
495 if name in branches:
501 if name in branches:
496 self.ui.warn(_("warning: tag %s conflicts with existing"
502 self.ui.warn(_("warning: tag %s conflicts with existing"
497 " branch name\n") % name)
503 " branch name\n") % name)
498
504
499 def writetags(fp, names, munge, prevtags):
505 def writetags(fp, names, munge, prevtags):
500 fp.seek(0, 2)
506 fp.seek(0, 2)
501 if prevtags and prevtags[-1] != '\n':
507 if prevtags and prevtags[-1] != '\n':
502 fp.write('\n')
508 fp.write('\n')
503 for name in names:
509 for name in names:
504 m = munge and munge(name) or name
510 m = munge and munge(name) or name
505 if (self._tagscache.tagtypes and
511 if (self._tagscache.tagtypes and
506 name in self._tagscache.tagtypes):
512 name in self._tagscache.tagtypes):
507 old = self.tags().get(name, nullid)
513 old = self.tags().get(name, nullid)
508 fp.write('%s %s\n' % (hex(old), m))
514 fp.write('%s %s\n' % (hex(old), m))
509 fp.write('%s %s\n' % (hex(node), m))
515 fp.write('%s %s\n' % (hex(node), m))
510 fp.close()
516 fp.close()
511
517
512 prevtags = ''
518 prevtags = ''
513 if local:
519 if local:
514 try:
520 try:
515 fp = self.opener('localtags', 'r+')
521 fp = self.opener('localtags', 'r+')
516 except IOError:
522 except IOError:
517 fp = self.opener('localtags', 'a')
523 fp = self.opener('localtags', 'a')
518 else:
524 else:
519 prevtags = fp.read()
525 prevtags = fp.read()
520
526
521 # local tags are stored in the current charset
527 # local tags are stored in the current charset
522 writetags(fp, names, None, prevtags)
528 writetags(fp, names, None, prevtags)
523 for name in names:
529 for name in names:
524 self.hook('tag', node=hex(node), tag=name, local=local)
530 self.hook('tag', node=hex(node), tag=name, local=local)
525 return
531 return
526
532
527 try:
533 try:
528 fp = self.wfile('.hgtags', 'rb+')
534 fp = self.wfile('.hgtags', 'rb+')
529 except IOError, e:
535 except IOError, e:
530 if e.errno != errno.ENOENT:
536 if e.errno != errno.ENOENT:
531 raise
537 raise
532 fp = self.wfile('.hgtags', 'ab')
538 fp = self.wfile('.hgtags', 'ab')
533 else:
539 else:
534 prevtags = fp.read()
540 prevtags = fp.read()
535
541
536 # committed tags are stored in UTF-8
542 # committed tags are stored in UTF-8
537 writetags(fp, names, encoding.fromlocal, prevtags)
543 writetags(fp, names, encoding.fromlocal, prevtags)
538
544
539 fp.close()
545 fp.close()
540
546
541 self.invalidatecaches()
547 self.invalidatecaches()
542
548
543 if '.hgtags' not in self.dirstate:
549 if '.hgtags' not in self.dirstate:
544 self[None].add(['.hgtags'])
550 self[None].add(['.hgtags'])
545
551
546 m = matchmod.exact(self.root, '', ['.hgtags'])
552 m = matchmod.exact(self.root, '', ['.hgtags'])
547 tagnode = self.commit(message, user, date, extra=extra, match=m,
553 tagnode = self.commit(message, user, date, extra=extra, match=m,
548 editor=editor)
554 editor=editor)
549
555
550 for name in names:
556 for name in names:
551 self.hook('tag', node=hex(node), tag=name, local=local)
557 self.hook('tag', node=hex(node), tag=name, local=local)
552
558
553 return tagnode
559 return tagnode
554
560
555 def tag(self, names, node, message, local, user, date, editor=False):
561 def tag(self, names, node, message, local, user, date, editor=False):
556 '''tag a revision with one or more symbolic names.
562 '''tag a revision with one or more symbolic names.
557
563
558 names is a list of strings or, when adding a single tag, names may be a
564 names is a list of strings or, when adding a single tag, names may be a
559 string.
565 string.
560
566
561 if local is True, the tags are stored in a per-repository file.
567 if local is True, the tags are stored in a per-repository file.
562 otherwise, they are stored in the .hgtags file, and a new
568 otherwise, they are stored in the .hgtags file, and a new
563 changeset is committed with the change.
569 changeset is committed with the change.
564
570
565 keyword arguments:
571 keyword arguments:
566
572
567 local: whether to store tags in non-version-controlled file
573 local: whether to store tags in non-version-controlled file
568 (default False)
574 (default False)
569
575
570 message: commit message to use if committing
576 message: commit message to use if committing
571
577
572 user: name of user to use if committing
578 user: name of user to use if committing
573
579
574 date: date tuple to use if committing'''
580 date: date tuple to use if committing'''
575
581
576 if not local:
582 if not local:
577 m = matchmod.exact(self.root, '', ['.hgtags'])
583 m = matchmod.exact(self.root, '', ['.hgtags'])
578 if util.any(self.status(match=m, unknown=True, ignored=True)):
584 if util.any(self.status(match=m, unknown=True, ignored=True)):
579 raise util.Abort(_('working copy of .hgtags is changed'),
585 raise util.Abort(_('working copy of .hgtags is changed'),
580 hint=_('please commit .hgtags manually'))
586 hint=_('please commit .hgtags manually'))
581
587
582 self.tags() # instantiate the cache
588 self.tags() # instantiate the cache
583 self._tag(names, node, message, local, user, date, editor=editor)
589 self._tag(names, node, message, local, user, date, editor=editor)
584
590
585 @filteredpropertycache
591 @filteredpropertycache
586 def _tagscache(self):
592 def _tagscache(self):
587 '''Returns a tagscache object that contains various tags related
593 '''Returns a tagscache object that contains various tags related
588 caches.'''
594 caches.'''
589
595
590 # This simplifies its cache management by having one decorated
596 # This simplifies its cache management by having one decorated
591 # function (this one) and the rest simply fetch things from it.
597 # function (this one) and the rest simply fetch things from it.
592 class tagscache(object):
598 class tagscache(object):
593 def __init__(self):
599 def __init__(self):
594 # These two define the set of tags for this repository. tags
600 # These two define the set of tags for this repository. tags
595 # maps tag name to node; tagtypes maps tag name to 'global' or
601 # maps tag name to node; tagtypes maps tag name to 'global' or
596 # 'local'. (Global tags are defined by .hgtags across all
602 # 'local'. (Global tags are defined by .hgtags across all
597 # heads, and local tags are defined in .hg/localtags.)
603 # heads, and local tags are defined in .hg/localtags.)
598 # They constitute the in-memory cache of tags.
604 # They constitute the in-memory cache of tags.
599 self.tags = self.tagtypes = None
605 self.tags = self.tagtypes = None
600
606
601 self.nodetagscache = self.tagslist = None
607 self.nodetagscache = self.tagslist = None
602
608
603 cache = tagscache()
609 cache = tagscache()
604 cache.tags, cache.tagtypes = self._findtags()
610 cache.tags, cache.tagtypes = self._findtags()
605
611
606 return cache
612 return cache
607
613
608 def tags(self):
614 def tags(self):
609 '''return a mapping of tag to node'''
615 '''return a mapping of tag to node'''
610 t = {}
616 t = {}
611 if self.changelog.filteredrevs:
617 if self.changelog.filteredrevs:
612 tags, tt = self._findtags()
618 tags, tt = self._findtags()
613 else:
619 else:
614 tags = self._tagscache.tags
620 tags = self._tagscache.tags
615 for k, v in tags.iteritems():
621 for k, v in tags.iteritems():
616 try:
622 try:
617 # ignore tags to unknown nodes
623 # ignore tags to unknown nodes
618 self.changelog.rev(v)
624 self.changelog.rev(v)
619 t[k] = v
625 t[k] = v
620 except (error.LookupError, ValueError):
626 except (error.LookupError, ValueError):
621 pass
627 pass
622 return t
628 return t
623
629
624 def _findtags(self):
630 def _findtags(self):
625 '''Do the hard work of finding tags. Return a pair of dicts
631 '''Do the hard work of finding tags. Return a pair of dicts
626 (tags, tagtypes) where tags maps tag name to node, and tagtypes
632 (tags, tagtypes) where tags maps tag name to node, and tagtypes
627 maps tag name to a string like \'global\' or \'local\'.
633 maps tag name to a string like \'global\' or \'local\'.
628 Subclasses or extensions are free to add their own tags, but
634 Subclasses or extensions are free to add their own tags, but
629 should be aware that the returned dicts will be retained for the
635 should be aware that the returned dicts will be retained for the
630 duration of the localrepo object.'''
636 duration of the localrepo object.'''
631
637
632 # XXX what tagtype should subclasses/extensions use? Currently
638 # XXX what tagtype should subclasses/extensions use? Currently
633 # mq and bookmarks add tags, but do not set the tagtype at all.
639 # mq and bookmarks add tags, but do not set the tagtype at all.
634 # Should each extension invent its own tag type? Should there
640 # Should each extension invent its own tag type? Should there
635 # be one tagtype for all such "virtual" tags? Or is the status
641 # be one tagtype for all such "virtual" tags? Or is the status
636 # quo fine?
642 # quo fine?
637
643
638 alltags = {} # map tag name to (node, hist)
644 alltags = {} # map tag name to (node, hist)
639 tagtypes = {}
645 tagtypes = {}
640
646
641 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
647 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
642 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
648 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
643
649
644 # Build the return dicts. Have to re-encode tag names because
650 # Build the return dicts. Have to re-encode tag names because
645 # the tags module always uses UTF-8 (in order not to lose info
651 # the tags module always uses UTF-8 (in order not to lose info
646 # writing to the cache), but the rest of Mercurial wants them in
652 # writing to the cache), but the rest of Mercurial wants them in
647 # local encoding.
653 # local encoding.
648 tags = {}
654 tags = {}
649 for (name, (node, hist)) in alltags.iteritems():
655 for (name, (node, hist)) in alltags.iteritems():
650 if node != nullid:
656 if node != nullid:
651 tags[encoding.tolocal(name)] = node
657 tags[encoding.tolocal(name)] = node
652 tags['tip'] = self.changelog.tip()
658 tags['tip'] = self.changelog.tip()
653 tagtypes = dict([(encoding.tolocal(name), value)
659 tagtypes = dict([(encoding.tolocal(name), value)
654 for (name, value) in tagtypes.iteritems()])
660 for (name, value) in tagtypes.iteritems()])
655 return (tags, tagtypes)
661 return (tags, tagtypes)
656
662
657 def tagtype(self, tagname):
663 def tagtype(self, tagname):
658 '''
664 '''
659 return the type of the given tag. result can be:
665 return the type of the given tag. result can be:
660
666
661 'local' : a local tag
667 'local' : a local tag
662 'global' : a global tag
668 'global' : a global tag
663 None : tag does not exist
669 None : tag does not exist
664 '''
670 '''
665
671
666 return self._tagscache.tagtypes.get(tagname)
672 return self._tagscache.tagtypes.get(tagname)
667
673
668 def tagslist(self):
674 def tagslist(self):
669 '''return a list of tags ordered by revision'''
675 '''return a list of tags ordered by revision'''
670 if not self._tagscache.tagslist:
676 if not self._tagscache.tagslist:
671 l = []
677 l = []
672 for t, n in self.tags().iteritems():
678 for t, n in self.tags().iteritems():
673 l.append((self.changelog.rev(n), t, n))
679 l.append((self.changelog.rev(n), t, n))
674 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
680 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
675
681
676 return self._tagscache.tagslist
682 return self._tagscache.tagslist
677
683
678 def nodetags(self, node):
684 def nodetags(self, node):
679 '''return the tags associated with a node'''
685 '''return the tags associated with a node'''
680 if not self._tagscache.nodetagscache:
686 if not self._tagscache.nodetagscache:
681 nodetagscache = {}
687 nodetagscache = {}
682 for t, n in self._tagscache.tags.iteritems():
688 for t, n in self._tagscache.tags.iteritems():
683 nodetagscache.setdefault(n, []).append(t)
689 nodetagscache.setdefault(n, []).append(t)
684 for tags in nodetagscache.itervalues():
690 for tags in nodetagscache.itervalues():
685 tags.sort()
691 tags.sort()
686 self._tagscache.nodetagscache = nodetagscache
692 self._tagscache.nodetagscache = nodetagscache
687 return self._tagscache.nodetagscache.get(node, [])
693 return self._tagscache.nodetagscache.get(node, [])
688
694
689 def nodebookmarks(self, node):
695 def nodebookmarks(self, node):
690 marks = []
696 marks = []
691 for bookmark, n in self._bookmarks.iteritems():
697 for bookmark, n in self._bookmarks.iteritems():
692 if n == node:
698 if n == node:
693 marks.append(bookmark)
699 marks.append(bookmark)
694 return sorted(marks)
700 return sorted(marks)
695
701
696 def branchmap(self):
702 def branchmap(self):
697 '''returns a dictionary {branch: [branchheads]} with branchheads
703 '''returns a dictionary {branch: [branchheads]} with branchheads
698 ordered by increasing revision number'''
704 ordered by increasing revision number'''
699 branchmap.updatecache(self)
705 branchmap.updatecache(self)
700 return self._branchcaches[self.filtername]
706 return self._branchcaches[self.filtername]
701
707
702 def branchtip(self, branch):
708 def branchtip(self, branch):
703 '''return the tip node for a given branch'''
709 '''return the tip node for a given branch'''
704 try:
710 try:
705 return self.branchmap().branchtip(branch)
711 return self.branchmap().branchtip(branch)
706 except KeyError:
712 except KeyError:
707 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
713 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
708
714
709 def lookup(self, key):
715 def lookup(self, key):
710 return self[key].node()
716 return self[key].node()
711
717
712 def lookupbranch(self, key, remote=None):
718 def lookupbranch(self, key, remote=None):
713 repo = remote or self
719 repo = remote or self
714 if key in repo.branchmap():
720 if key in repo.branchmap():
715 return key
721 return key
716
722
717 repo = (remote and remote.local()) and remote or self
723 repo = (remote and remote.local()) and remote or self
718 return repo[key].branch()
724 return repo[key].branch()
719
725
720 def known(self, nodes):
726 def known(self, nodes):
721 nm = self.changelog.nodemap
727 nm = self.changelog.nodemap
722 pc = self._phasecache
728 pc = self._phasecache
723 result = []
729 result = []
724 for n in nodes:
730 for n in nodes:
725 r = nm.get(n)
731 r = nm.get(n)
726 resp = not (r is None or pc.phase(self, r) >= phases.secret)
732 resp = not (r is None or pc.phase(self, r) >= phases.secret)
727 result.append(resp)
733 result.append(resp)
728 return result
734 return result
729
735
730 def local(self):
736 def local(self):
731 return self
737 return self
732
738
733 def cancopy(self):
739 def cancopy(self):
734 # so statichttprepo's override of local() works
740 # so statichttprepo's override of local() works
735 if not self.local():
741 if not self.local():
736 return False
742 return False
737 if not self.ui.configbool('phases', 'publish', True):
743 if not self.ui.configbool('phases', 'publish', True):
738 return True
744 return True
739 # if publishing we can't copy if there is filtered content
745 # if publishing we can't copy if there is filtered content
740 return not self.filtered('visible').changelog.filteredrevs
746 return not self.filtered('visible').changelog.filteredrevs
741
747
742 def join(self, f, *insidef):
748 def join(self, f, *insidef):
743 return os.path.join(self.path, f, *insidef)
749 return os.path.join(self.path, f, *insidef)
744
750
745 def wjoin(self, f, *insidef):
751 def wjoin(self, f, *insidef):
746 return os.path.join(self.root, f, *insidef)
752 return os.path.join(self.root, f, *insidef)
747
753
748 def file(self, f):
754 def file(self, f):
749 if f[0] == '/':
755 if f[0] == '/':
750 f = f[1:]
756 f = f[1:]
751 return filelog.filelog(self.sopener, f)
757 return filelog.filelog(self.sopener, f)
752
758
753 def changectx(self, changeid):
759 def changectx(self, changeid):
754 return self[changeid]
760 return self[changeid]
755
761
756 def parents(self, changeid=None):
762 def parents(self, changeid=None):
757 '''get list of changectxs for parents of changeid'''
763 '''get list of changectxs for parents of changeid'''
758 return self[changeid].parents()
764 return self[changeid].parents()
759
765
760 def setparents(self, p1, p2=nullid):
766 def setparents(self, p1, p2=nullid):
761 self.dirstate.beginparentchange()
767 self.dirstate.beginparentchange()
762 copies = self.dirstate.setparents(p1, p2)
768 copies = self.dirstate.setparents(p1, p2)
763 pctx = self[p1]
769 pctx = self[p1]
764 if copies:
770 if copies:
765 # Adjust copy records, the dirstate cannot do it, it
771 # Adjust copy records, the dirstate cannot do it, it
766 # requires access to parents manifests. Preserve them
772 # requires access to parents manifests. Preserve them
767 # only for entries added to first parent.
773 # only for entries added to first parent.
768 for f in copies:
774 for f in copies:
769 if f not in pctx and copies[f] in pctx:
775 if f not in pctx and copies[f] in pctx:
770 self.dirstate.copy(copies[f], f)
776 self.dirstate.copy(copies[f], f)
771 if p2 == nullid:
777 if p2 == nullid:
772 for f, s in sorted(self.dirstate.copies().items()):
778 for f, s in sorted(self.dirstate.copies().items()):
773 if f not in pctx and s not in pctx:
779 if f not in pctx and s not in pctx:
774 self.dirstate.copy(None, f)
780 self.dirstate.copy(None, f)
775 self.dirstate.endparentchange()
781 self.dirstate.endparentchange()
776
782
777 def filectx(self, path, changeid=None, fileid=None):
783 def filectx(self, path, changeid=None, fileid=None):
778 """changeid can be a changeset revision, node, or tag.
784 """changeid can be a changeset revision, node, or tag.
779 fileid can be a file revision or node."""
785 fileid can be a file revision or node."""
780 return context.filectx(self, path, changeid, fileid)
786 return context.filectx(self, path, changeid, fileid)
781
787
782 def getcwd(self):
788 def getcwd(self):
783 return self.dirstate.getcwd()
789 return self.dirstate.getcwd()
784
790
785 def pathto(self, f, cwd=None):
791 def pathto(self, f, cwd=None):
786 return self.dirstate.pathto(f, cwd)
792 return self.dirstate.pathto(f, cwd)
787
793
788 def wfile(self, f, mode='r'):
794 def wfile(self, f, mode='r'):
789 return self.wopener(f, mode)
795 return self.wopener(f, mode)
790
796
791 def _link(self, f):
797 def _link(self, f):
792 return self.wvfs.islink(f)
798 return self.wvfs.islink(f)
793
799
794 def _loadfilter(self, filter):
800 def _loadfilter(self, filter):
795 if filter not in self.filterpats:
801 if filter not in self.filterpats:
796 l = []
802 l = []
797 for pat, cmd in self.ui.configitems(filter):
803 for pat, cmd in self.ui.configitems(filter):
798 if cmd == '!':
804 if cmd == '!':
799 continue
805 continue
800 mf = matchmod.match(self.root, '', [pat])
806 mf = matchmod.match(self.root, '', [pat])
801 fn = None
807 fn = None
802 params = cmd
808 params = cmd
803 for name, filterfn in self._datafilters.iteritems():
809 for name, filterfn in self._datafilters.iteritems():
804 if cmd.startswith(name):
810 if cmd.startswith(name):
805 fn = filterfn
811 fn = filterfn
806 params = cmd[len(name):].lstrip()
812 params = cmd[len(name):].lstrip()
807 break
813 break
808 if not fn:
814 if not fn:
809 fn = lambda s, c, **kwargs: util.filter(s, c)
815 fn = lambda s, c, **kwargs: util.filter(s, c)
810 # Wrap old filters not supporting keyword arguments
816 # Wrap old filters not supporting keyword arguments
811 if not inspect.getargspec(fn)[2]:
817 if not inspect.getargspec(fn)[2]:
812 oldfn = fn
818 oldfn = fn
813 fn = lambda s, c, **kwargs: oldfn(s, c)
819 fn = lambda s, c, **kwargs: oldfn(s, c)
814 l.append((mf, fn, params))
820 l.append((mf, fn, params))
815 self.filterpats[filter] = l
821 self.filterpats[filter] = l
816 return self.filterpats[filter]
822 return self.filterpats[filter]
817
823
818 def _filter(self, filterpats, filename, data):
824 def _filter(self, filterpats, filename, data):
819 for mf, fn, cmd in filterpats:
825 for mf, fn, cmd in filterpats:
820 if mf(filename):
826 if mf(filename):
821 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
827 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
822 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
828 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
823 break
829 break
824
830
825 return data
831 return data
826
832
827 @unfilteredpropertycache
833 @unfilteredpropertycache
828 def _encodefilterpats(self):
834 def _encodefilterpats(self):
829 return self._loadfilter('encode')
835 return self._loadfilter('encode')
830
836
831 @unfilteredpropertycache
837 @unfilteredpropertycache
832 def _decodefilterpats(self):
838 def _decodefilterpats(self):
833 return self._loadfilter('decode')
839 return self._loadfilter('decode')
834
840
835 def adddatafilter(self, name, filter):
841 def adddatafilter(self, name, filter):
836 self._datafilters[name] = filter
842 self._datafilters[name] = filter
837
843
838 def wread(self, filename):
844 def wread(self, filename):
839 if self._link(filename):
845 if self._link(filename):
840 data = self.wvfs.readlink(filename)
846 data = self.wvfs.readlink(filename)
841 else:
847 else:
842 data = self.wopener.read(filename)
848 data = self.wopener.read(filename)
843 return self._filter(self._encodefilterpats, filename, data)
849 return self._filter(self._encodefilterpats, filename, data)
844
850
845 def wwrite(self, filename, data, flags):
851 def wwrite(self, filename, data, flags):
846 data = self._filter(self._decodefilterpats, filename, data)
852 data = self._filter(self._decodefilterpats, filename, data)
847 if 'l' in flags:
853 if 'l' in flags:
848 self.wopener.symlink(data, filename)
854 self.wopener.symlink(data, filename)
849 else:
855 else:
850 self.wopener.write(filename, data)
856 self.wopener.write(filename, data)
851 if 'x' in flags:
857 if 'x' in flags:
852 self.wvfs.setflags(filename, False, True)
858 self.wvfs.setflags(filename, False, True)
853
859
854 def wwritedata(self, filename, data):
860 def wwritedata(self, filename, data):
855 return self._filter(self._decodefilterpats, filename, data)
861 return self._filter(self._decodefilterpats, filename, data)
856
862
857 def transaction(self, desc, report=None):
863 def transaction(self, desc, report=None):
858 tr = self._transref and self._transref() or None
864 tr = self._transref and self._transref() or None
859 if tr and tr.running():
865 if tr and tr.running():
860 return tr.nest()
866 return tr.nest()
861
867
862 # abort here if the journal already exists
868 # abort here if the journal already exists
863 if self.svfs.exists("journal"):
869 if self.svfs.exists("journal"):
864 raise error.RepoError(
870 raise error.RepoError(
865 _("abandoned transaction found"),
871 _("abandoned transaction found"),
866 hint=_("run 'hg recover' to clean up transaction"))
872 hint=_("run 'hg recover' to clean up transaction"))
867
873
868 def onclose():
874 def onclose():
869 self.store.write(self._transref())
875 self.store.write(self._transref())
870
876
871 self._writejournal(desc)
877 self._writejournal(desc)
872 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
878 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
873 rp = report and report or self.ui.warn
879 rp = report and report or self.ui.warn
874 tr = transaction.transaction(rp, self.sopener,
880 tr = transaction.transaction(rp, self.sopener,
875 "journal",
881 "journal",
876 aftertrans(renames),
882 aftertrans(renames),
877 self.store.createmode,
883 self.store.createmode,
878 onclose)
884 onclose)
879 self._transref = weakref.ref(tr)
885 self._transref = weakref.ref(tr)
880 return tr
886 return tr
881
887
882 def _journalfiles(self):
888 def _journalfiles(self):
883 return ((self.svfs, 'journal'),
889 return ((self.svfs, 'journal'),
884 (self.vfs, 'journal.dirstate'),
890 (self.vfs, 'journal.dirstate'),
885 (self.vfs, 'journal.branch'),
891 (self.vfs, 'journal.branch'),
886 (self.vfs, 'journal.desc'),
892 (self.vfs, 'journal.desc'),
887 (self.vfs, 'journal.bookmarks'),
893 (self.vfs, 'journal.bookmarks'),
888 (self.svfs, 'journal.phaseroots'))
894 (self.svfs, 'journal.phaseroots'))
889
895
890 def undofiles(self):
896 def undofiles(self):
891 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
897 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
892
898
893 def _writejournal(self, desc):
899 def _writejournal(self, desc):
894 self.opener.write("journal.dirstate",
900 self.opener.write("journal.dirstate",
895 self.opener.tryread("dirstate"))
901 self.opener.tryread("dirstate"))
896 self.opener.write("journal.branch",
902 self.opener.write("journal.branch",
897 encoding.fromlocal(self.dirstate.branch()))
903 encoding.fromlocal(self.dirstate.branch()))
898 self.opener.write("journal.desc",
904 self.opener.write("journal.desc",
899 "%d\n%s\n" % (len(self), desc))
905 "%d\n%s\n" % (len(self), desc))
900 self.opener.write("journal.bookmarks",
906 self.opener.write("journal.bookmarks",
901 self.opener.tryread("bookmarks"))
907 self.opener.tryread("bookmarks"))
902 self.sopener.write("journal.phaseroots",
908 self.sopener.write("journal.phaseroots",
903 self.sopener.tryread("phaseroots"))
909 self.sopener.tryread("phaseroots"))
904
910
905 def recover(self):
911 def recover(self):
906 lock = self.lock()
912 lock = self.lock()
907 try:
913 try:
908 if self.svfs.exists("journal"):
914 if self.svfs.exists("journal"):
909 self.ui.status(_("rolling back interrupted transaction\n"))
915 self.ui.status(_("rolling back interrupted transaction\n"))
910 transaction.rollback(self.sopener, "journal",
916 transaction.rollback(self.sopener, "journal",
911 self.ui.warn)
917 self.ui.warn)
912 self.invalidate()
918 self.invalidate()
913 return True
919 return True
914 else:
920 else:
915 self.ui.warn(_("no interrupted transaction available\n"))
921 self.ui.warn(_("no interrupted transaction available\n"))
916 return False
922 return False
917 finally:
923 finally:
918 lock.release()
924 lock.release()
919
925
920 def rollback(self, dryrun=False, force=False):
926 def rollback(self, dryrun=False, force=False):
921 wlock = lock = None
927 wlock = lock = None
922 try:
928 try:
923 wlock = self.wlock()
929 wlock = self.wlock()
924 lock = self.lock()
930 lock = self.lock()
925 if self.svfs.exists("undo"):
931 if self.svfs.exists("undo"):
926 return self._rollback(dryrun, force)
932 return self._rollback(dryrun, force)
927 else:
933 else:
928 self.ui.warn(_("no rollback information available\n"))
934 self.ui.warn(_("no rollback information available\n"))
929 return 1
935 return 1
930 finally:
936 finally:
931 release(lock, wlock)
937 release(lock, wlock)
932
938
933 @unfilteredmethod # Until we get smarter cache management
939 @unfilteredmethod # Until we get smarter cache management
934 def _rollback(self, dryrun, force):
940 def _rollback(self, dryrun, force):
935 ui = self.ui
941 ui = self.ui
936 try:
942 try:
937 args = self.opener.read('undo.desc').splitlines()
943 args = self.opener.read('undo.desc').splitlines()
938 (oldlen, desc, detail) = (int(args[0]), args[1], None)
944 (oldlen, desc, detail) = (int(args[0]), args[1], None)
939 if len(args) >= 3:
945 if len(args) >= 3:
940 detail = args[2]
946 detail = args[2]
941 oldtip = oldlen - 1
947 oldtip = oldlen - 1
942
948
943 if detail and ui.verbose:
949 if detail and ui.verbose:
944 msg = (_('repository tip rolled back to revision %s'
950 msg = (_('repository tip rolled back to revision %s'
945 ' (undo %s: %s)\n')
951 ' (undo %s: %s)\n')
946 % (oldtip, desc, detail))
952 % (oldtip, desc, detail))
947 else:
953 else:
948 msg = (_('repository tip rolled back to revision %s'
954 msg = (_('repository tip rolled back to revision %s'
949 ' (undo %s)\n')
955 ' (undo %s)\n')
950 % (oldtip, desc))
956 % (oldtip, desc))
951 except IOError:
957 except IOError:
952 msg = _('rolling back unknown transaction\n')
958 msg = _('rolling back unknown transaction\n')
953 desc = None
959 desc = None
954
960
955 if not force and self['.'] != self['tip'] and desc == 'commit':
961 if not force and self['.'] != self['tip'] and desc == 'commit':
956 raise util.Abort(
962 raise util.Abort(
957 _('rollback of last commit while not checked out '
963 _('rollback of last commit while not checked out '
958 'may lose data'), hint=_('use -f to force'))
964 'may lose data'), hint=_('use -f to force'))
959
965
960 ui.status(msg)
966 ui.status(msg)
961 if dryrun:
967 if dryrun:
962 return 0
968 return 0
963
969
964 parents = self.dirstate.parents()
970 parents = self.dirstate.parents()
965 self.destroying()
971 self.destroying()
966 transaction.rollback(self.sopener, 'undo', ui.warn)
972 transaction.rollback(self.sopener, 'undo', ui.warn)
967 if self.vfs.exists('undo.bookmarks'):
973 if self.vfs.exists('undo.bookmarks'):
968 self.vfs.rename('undo.bookmarks', 'bookmarks')
974 self.vfs.rename('undo.bookmarks', 'bookmarks')
969 if self.svfs.exists('undo.phaseroots'):
975 if self.svfs.exists('undo.phaseroots'):
970 self.svfs.rename('undo.phaseroots', 'phaseroots')
976 self.svfs.rename('undo.phaseroots', 'phaseroots')
971 self.invalidate()
977 self.invalidate()
972
978
973 parentgone = (parents[0] not in self.changelog.nodemap or
979 parentgone = (parents[0] not in self.changelog.nodemap or
974 parents[1] not in self.changelog.nodemap)
980 parents[1] not in self.changelog.nodemap)
975 if parentgone:
981 if parentgone:
976 self.vfs.rename('undo.dirstate', 'dirstate')
982 self.vfs.rename('undo.dirstate', 'dirstate')
977 try:
983 try:
978 branch = self.opener.read('undo.branch')
984 branch = self.opener.read('undo.branch')
979 self.dirstate.setbranch(encoding.tolocal(branch))
985 self.dirstate.setbranch(encoding.tolocal(branch))
980 except IOError:
986 except IOError:
981 ui.warn(_('named branch could not be reset: '
987 ui.warn(_('named branch could not be reset: '
982 'current branch is still \'%s\'\n')
988 'current branch is still \'%s\'\n')
983 % self.dirstate.branch())
989 % self.dirstate.branch())
984
990
985 self.dirstate.invalidate()
991 self.dirstate.invalidate()
986 parents = tuple([p.rev() for p in self.parents()])
992 parents = tuple([p.rev() for p in self.parents()])
987 if len(parents) > 1:
993 if len(parents) > 1:
988 ui.status(_('working directory now based on '
994 ui.status(_('working directory now based on '
989 'revisions %d and %d\n') % parents)
995 'revisions %d and %d\n') % parents)
990 else:
996 else:
991 ui.status(_('working directory now based on '
997 ui.status(_('working directory now based on '
992 'revision %d\n') % parents)
998 'revision %d\n') % parents)
993 # TODO: if we know which new heads may result from this rollback, pass
999 # TODO: if we know which new heads may result from this rollback, pass
994 # them to destroy(), which will prevent the branchhead cache from being
1000 # them to destroy(), which will prevent the branchhead cache from being
995 # invalidated.
1001 # invalidated.
996 self.destroyed()
1002 self.destroyed()
997 return 0
1003 return 0
998
1004
999 def invalidatecaches(self):
1005 def invalidatecaches(self):
1000
1006
1001 if '_tagscache' in vars(self):
1007 if '_tagscache' in vars(self):
1002 # can't use delattr on proxy
1008 # can't use delattr on proxy
1003 del self.__dict__['_tagscache']
1009 del self.__dict__['_tagscache']
1004
1010
1005 self.unfiltered()._branchcaches.clear()
1011 self.unfiltered()._branchcaches.clear()
1006 self.invalidatevolatilesets()
1012 self.invalidatevolatilesets()
1007
1013
1008 def invalidatevolatilesets(self):
1014 def invalidatevolatilesets(self):
1009 self.filteredrevcache.clear()
1015 self.filteredrevcache.clear()
1010 obsolete.clearobscaches(self)
1016 obsolete.clearobscaches(self)
1011
1017
1012 def invalidatedirstate(self):
1018 def invalidatedirstate(self):
1013 '''Invalidates the dirstate, causing the next call to dirstate
1019 '''Invalidates the dirstate, causing the next call to dirstate
1014 to check if it was modified since the last time it was read,
1020 to check if it was modified since the last time it was read,
1015 rereading it if it has.
1021 rereading it if it has.
1016
1022
1017 This is different to dirstate.invalidate() that it doesn't always
1023 This is different to dirstate.invalidate() that it doesn't always
1018 rereads the dirstate. Use dirstate.invalidate() if you want to
1024 rereads the dirstate. Use dirstate.invalidate() if you want to
1019 explicitly read the dirstate again (i.e. restoring it to a previous
1025 explicitly read the dirstate again (i.e. restoring it to a previous
1020 known good state).'''
1026 known good state).'''
1021 if hasunfilteredcache(self, 'dirstate'):
1027 if hasunfilteredcache(self, 'dirstate'):
1022 for k in self.dirstate._filecache:
1028 for k in self.dirstate._filecache:
1023 try:
1029 try:
1024 delattr(self.dirstate, k)
1030 delattr(self.dirstate, k)
1025 except AttributeError:
1031 except AttributeError:
1026 pass
1032 pass
1027 delattr(self.unfiltered(), 'dirstate')
1033 delattr(self.unfiltered(), 'dirstate')
1028
1034
1029 def invalidate(self):
1035 def invalidate(self):
1030 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1036 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1031 for k in self._filecache:
1037 for k in self._filecache:
1032 # dirstate is invalidated separately in invalidatedirstate()
1038 # dirstate is invalidated separately in invalidatedirstate()
1033 if k == 'dirstate':
1039 if k == 'dirstate':
1034 continue
1040 continue
1035
1041
1036 try:
1042 try:
1037 delattr(unfiltered, k)
1043 delattr(unfiltered, k)
1038 except AttributeError:
1044 except AttributeError:
1039 pass
1045 pass
1040 self.invalidatecaches()
1046 self.invalidatecaches()
1041 self.store.invalidatecaches()
1047 self.store.invalidatecaches()
1042
1048
1043 def invalidateall(self):
1049 def invalidateall(self):
1044 '''Fully invalidates both store and non-store parts, causing the
1050 '''Fully invalidates both store and non-store parts, causing the
1045 subsequent operation to reread any outside changes.'''
1051 subsequent operation to reread any outside changes.'''
1046 # extension should hook this to invalidate its caches
1052 # extension should hook this to invalidate its caches
1047 self.invalidate()
1053 self.invalidate()
1048 self.invalidatedirstate()
1054 self.invalidatedirstate()
1049
1055
1050 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1056 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1051 try:
1057 try:
1052 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1058 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1053 except error.LockHeld, inst:
1059 except error.LockHeld, inst:
1054 if not wait:
1060 if not wait:
1055 raise
1061 raise
1056 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1062 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1057 (desc, inst.locker))
1063 (desc, inst.locker))
1058 # default to 600 seconds timeout
1064 # default to 600 seconds timeout
1059 l = lockmod.lock(vfs, lockname,
1065 l = lockmod.lock(vfs, lockname,
1060 int(self.ui.config("ui", "timeout", "600")),
1066 int(self.ui.config("ui", "timeout", "600")),
1061 releasefn, desc=desc)
1067 releasefn, desc=desc)
1062 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1068 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1063 if acquirefn:
1069 if acquirefn:
1064 acquirefn()
1070 acquirefn()
1065 return l
1071 return l
1066
1072
1067 def _afterlock(self, callback):
1073 def _afterlock(self, callback):
1068 """add a callback to the current repository lock.
1074 """add a callback to the current repository lock.
1069
1075
1070 The callback will be executed on lock release."""
1076 The callback will be executed on lock release."""
1071 l = self._lockref and self._lockref()
1077 l = self._lockref and self._lockref()
1072 if l:
1078 if l:
1073 l.postrelease.append(callback)
1079 l.postrelease.append(callback)
1074 else:
1080 else:
1075 callback()
1081 callback()
1076
1082
1077 def lock(self, wait=True):
1083 def lock(self, wait=True):
1078 '''Lock the repository store (.hg/store) and return a weak reference
1084 '''Lock the repository store (.hg/store) and return a weak reference
1079 to the lock. Use this before modifying the store (e.g. committing or
1085 to the lock. Use this before modifying the store (e.g. committing or
1080 stripping). If you are opening a transaction, get a lock as well.)'''
1086 stripping). If you are opening a transaction, get a lock as well.)'''
1081 l = self._lockref and self._lockref()
1087 l = self._lockref and self._lockref()
1082 if l is not None and l.held:
1088 if l is not None and l.held:
1083 l.lock()
1089 l.lock()
1084 return l
1090 return l
1085
1091
1086 def unlock():
1092 def unlock():
1087 for k, ce in self._filecache.items():
1093 for k, ce in self._filecache.items():
1088 if k == 'dirstate' or k not in self.__dict__:
1094 if k == 'dirstate' or k not in self.__dict__:
1089 continue
1095 continue
1090 ce.refresh()
1096 ce.refresh()
1091
1097
1092 l = self._lock(self.svfs, "lock", wait, unlock,
1098 l = self._lock(self.svfs, "lock", wait, unlock,
1093 self.invalidate, _('repository %s') % self.origroot)
1099 self.invalidate, _('repository %s') % self.origroot)
1094 self._lockref = weakref.ref(l)
1100 self._lockref = weakref.ref(l)
1095 return l
1101 return l
1096
1102
1097 def wlock(self, wait=True):
1103 def wlock(self, wait=True):
1098 '''Lock the non-store parts of the repository (everything under
1104 '''Lock the non-store parts of the repository (everything under
1099 .hg except .hg/store) and return a weak reference to the lock.
1105 .hg except .hg/store) and return a weak reference to the lock.
1100 Use this before modifying files in .hg.'''
1106 Use this before modifying files in .hg.'''
1101 l = self._wlockref and self._wlockref()
1107 l = self._wlockref and self._wlockref()
1102 if l is not None and l.held:
1108 if l is not None and l.held:
1103 l.lock()
1109 l.lock()
1104 return l
1110 return l
1105
1111
1106 def unlock():
1112 def unlock():
1107 if self.dirstate.pendingparentchange():
1113 if self.dirstate.pendingparentchange():
1108 self.dirstate.invalidate()
1114 self.dirstate.invalidate()
1109 else:
1115 else:
1110 self.dirstate.write()
1116 self.dirstate.write()
1111
1117
1112 self._filecache['dirstate'].refresh()
1118 self._filecache['dirstate'].refresh()
1113
1119
1114 l = self._lock(self.vfs, "wlock", wait, unlock,
1120 l = self._lock(self.vfs, "wlock", wait, unlock,
1115 self.invalidatedirstate, _('working directory of %s') %
1121 self.invalidatedirstate, _('working directory of %s') %
1116 self.origroot)
1122 self.origroot)
1117 self._wlockref = weakref.ref(l)
1123 self._wlockref = weakref.ref(l)
1118 return l
1124 return l
1119
1125
1120 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1126 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1121 """
1127 """
1122 commit an individual file as part of a larger transaction
1128 commit an individual file as part of a larger transaction
1123 """
1129 """
1124
1130
1125 fname = fctx.path()
1131 fname = fctx.path()
1126 text = fctx.data()
1132 text = fctx.data()
1127 flog = self.file(fname)
1133 flog = self.file(fname)
1128 fparent1 = manifest1.get(fname, nullid)
1134 fparent1 = manifest1.get(fname, nullid)
1129 fparent2 = manifest2.get(fname, nullid)
1135 fparent2 = manifest2.get(fname, nullid)
1130
1136
1131 meta = {}
1137 meta = {}
1132 copy = fctx.renamed()
1138 copy = fctx.renamed()
1133 if copy and copy[0] != fname:
1139 if copy and copy[0] != fname:
1134 # Mark the new revision of this file as a copy of another
1140 # Mark the new revision of this file as a copy of another
1135 # file. This copy data will effectively act as a parent
1141 # file. This copy data will effectively act as a parent
1136 # of this new revision. If this is a merge, the first
1142 # of this new revision. If this is a merge, the first
1137 # parent will be the nullid (meaning "look up the copy data")
1143 # parent will be the nullid (meaning "look up the copy data")
1138 # and the second one will be the other parent. For example:
1144 # and the second one will be the other parent. For example:
1139 #
1145 #
1140 # 0 --- 1 --- 3 rev1 changes file foo
1146 # 0 --- 1 --- 3 rev1 changes file foo
1141 # \ / rev2 renames foo to bar and changes it
1147 # \ / rev2 renames foo to bar and changes it
1142 # \- 2 -/ rev3 should have bar with all changes and
1148 # \- 2 -/ rev3 should have bar with all changes and
1143 # should record that bar descends from
1149 # should record that bar descends from
1144 # bar in rev2 and foo in rev1
1150 # bar in rev2 and foo in rev1
1145 #
1151 #
1146 # this allows this merge to succeed:
1152 # this allows this merge to succeed:
1147 #
1153 #
1148 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1154 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1149 # \ / merging rev3 and rev4 should use bar@rev2
1155 # \ / merging rev3 and rev4 should use bar@rev2
1150 # \- 2 --- 4 as the merge base
1156 # \- 2 --- 4 as the merge base
1151 #
1157 #
1152
1158
1153 cfname = copy[0]
1159 cfname = copy[0]
1154 crev = manifest1.get(cfname)
1160 crev = manifest1.get(cfname)
1155 newfparent = fparent2
1161 newfparent = fparent2
1156
1162
1157 if manifest2: # branch merge
1163 if manifest2: # branch merge
1158 if fparent2 == nullid or crev is None: # copied on remote side
1164 if fparent2 == nullid or crev is None: # copied on remote side
1159 if cfname in manifest2:
1165 if cfname in manifest2:
1160 crev = manifest2[cfname]
1166 crev = manifest2[cfname]
1161 newfparent = fparent1
1167 newfparent = fparent1
1162
1168
1163 # find source in nearest ancestor if we've lost track
1169 # find source in nearest ancestor if we've lost track
1164 if not crev:
1170 if not crev:
1165 self.ui.debug(" %s: searching for copy revision for %s\n" %
1171 self.ui.debug(" %s: searching for copy revision for %s\n" %
1166 (fname, cfname))
1172 (fname, cfname))
1167 for ancestor in self[None].ancestors():
1173 for ancestor in self[None].ancestors():
1168 if cfname in ancestor:
1174 if cfname in ancestor:
1169 crev = ancestor[cfname].filenode()
1175 crev = ancestor[cfname].filenode()
1170 break
1176 break
1171
1177
1172 if crev:
1178 if crev:
1173 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1179 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1174 meta["copy"] = cfname
1180 meta["copy"] = cfname
1175 meta["copyrev"] = hex(crev)
1181 meta["copyrev"] = hex(crev)
1176 fparent1, fparent2 = nullid, newfparent
1182 fparent1, fparent2 = nullid, newfparent
1177 else:
1183 else:
1178 self.ui.warn(_("warning: can't find ancestor for '%s' "
1184 self.ui.warn(_("warning: can't find ancestor for '%s' "
1179 "copied from '%s'!\n") % (fname, cfname))
1185 "copied from '%s'!\n") % (fname, cfname))
1180
1186
1181 elif fparent1 == nullid:
1187 elif fparent1 == nullid:
1182 fparent1, fparent2 = fparent2, nullid
1188 fparent1, fparent2 = fparent2, nullid
1183 elif fparent2 != nullid:
1189 elif fparent2 != nullid:
1184 # is one parent an ancestor of the other?
1190 # is one parent an ancestor of the other?
1185 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1191 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1186 if fparent1 in fparentancestors:
1192 if fparent1 in fparentancestors:
1187 fparent1, fparent2 = fparent2, nullid
1193 fparent1, fparent2 = fparent2, nullid
1188 elif fparent2 in fparentancestors:
1194 elif fparent2 in fparentancestors:
1189 fparent2 = nullid
1195 fparent2 = nullid
1190
1196
1191 # is the file changed?
1197 # is the file changed?
1192 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1198 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1193 changelist.append(fname)
1199 changelist.append(fname)
1194 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1200 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1195 # are just the flags changed during merge?
1201 # are just the flags changed during merge?
1196 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1202 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1197 changelist.append(fname)
1203 changelist.append(fname)
1198
1204
1199 return fparent1
1205 return fparent1
1200
1206
1201 @unfilteredmethod
1207 @unfilteredmethod
1202 def commit(self, text="", user=None, date=None, match=None, force=False,
1208 def commit(self, text="", user=None, date=None, match=None, force=False,
1203 editor=False, extra={}):
1209 editor=False, extra={}):
1204 """Add a new revision to current repository.
1210 """Add a new revision to current repository.
1205
1211
1206 Revision information is gathered from the working directory,
1212 Revision information is gathered from the working directory,
1207 match can be used to filter the committed files. If editor is
1213 match can be used to filter the committed files. If editor is
1208 supplied, it is called to get a commit message.
1214 supplied, it is called to get a commit message.
1209 """
1215 """
1210
1216
1211 def fail(f, msg):
1217 def fail(f, msg):
1212 raise util.Abort('%s: %s' % (f, msg))
1218 raise util.Abort('%s: %s' % (f, msg))
1213
1219
1214 if not match:
1220 if not match:
1215 match = matchmod.always(self.root, '')
1221 match = matchmod.always(self.root, '')
1216
1222
1217 if not force:
1223 if not force:
1218 vdirs = []
1224 vdirs = []
1219 match.explicitdir = vdirs.append
1225 match.explicitdir = vdirs.append
1220 match.bad = fail
1226 match.bad = fail
1221
1227
1222 wlock = self.wlock()
1228 wlock = self.wlock()
1223 try:
1229 try:
1224 wctx = self[None]
1230 wctx = self[None]
1225 merge = len(wctx.parents()) > 1
1231 merge = len(wctx.parents()) > 1
1226
1232
1227 if (not force and merge and match and
1233 if (not force and merge and match and
1228 (match.files() or match.anypats())):
1234 (match.files() or match.anypats())):
1229 raise util.Abort(_('cannot partially commit a merge '
1235 raise util.Abort(_('cannot partially commit a merge '
1230 '(do not specify files or patterns)'))
1236 '(do not specify files or patterns)'))
1231
1237
1232 changes = self.status(match=match, clean=force)
1238 changes = self.status(match=match, clean=force)
1233 if force:
1239 if force:
1234 changes[0].extend(changes[6]) # mq may commit unchanged files
1240 changes[0].extend(changes[6]) # mq may commit unchanged files
1235
1241
1236 # check subrepos
1242 # check subrepos
1237 subs = []
1243 subs = []
1238 commitsubs = set()
1244 commitsubs = set()
1239 newstate = wctx.substate.copy()
1245 newstate = wctx.substate.copy()
1240 # only manage subrepos and .hgsubstate if .hgsub is present
1246 # only manage subrepos and .hgsubstate if .hgsub is present
1241 if '.hgsub' in wctx:
1247 if '.hgsub' in wctx:
1242 # we'll decide whether to track this ourselves, thanks
1248 # we'll decide whether to track this ourselves, thanks
1243 for c in changes[:3]:
1249 for c in changes[:3]:
1244 if '.hgsubstate' in c:
1250 if '.hgsubstate' in c:
1245 c.remove('.hgsubstate')
1251 c.remove('.hgsubstate')
1246
1252
1247 # compare current state to last committed state
1253 # compare current state to last committed state
1248 # build new substate based on last committed state
1254 # build new substate based on last committed state
1249 oldstate = wctx.p1().substate
1255 oldstate = wctx.p1().substate
1250 for s in sorted(newstate.keys()):
1256 for s in sorted(newstate.keys()):
1251 if not match(s):
1257 if not match(s):
1252 # ignore working copy, use old state if present
1258 # ignore working copy, use old state if present
1253 if s in oldstate:
1259 if s in oldstate:
1254 newstate[s] = oldstate[s]
1260 newstate[s] = oldstate[s]
1255 continue
1261 continue
1256 if not force:
1262 if not force:
1257 raise util.Abort(
1263 raise util.Abort(
1258 _("commit with new subrepo %s excluded") % s)
1264 _("commit with new subrepo %s excluded") % s)
1259 if wctx.sub(s).dirty(True):
1265 if wctx.sub(s).dirty(True):
1260 if not self.ui.configbool('ui', 'commitsubrepos'):
1266 if not self.ui.configbool('ui', 'commitsubrepos'):
1261 raise util.Abort(
1267 raise util.Abort(
1262 _("uncommitted changes in subrepo %s") % s,
1268 _("uncommitted changes in subrepo %s") % s,
1263 hint=_("use --subrepos for recursive commit"))
1269 hint=_("use --subrepos for recursive commit"))
1264 subs.append(s)
1270 subs.append(s)
1265 commitsubs.add(s)
1271 commitsubs.add(s)
1266 else:
1272 else:
1267 bs = wctx.sub(s).basestate()
1273 bs = wctx.sub(s).basestate()
1268 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1274 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1269 if oldstate.get(s, (None, None, None))[1] != bs:
1275 if oldstate.get(s, (None, None, None))[1] != bs:
1270 subs.append(s)
1276 subs.append(s)
1271
1277
1272 # check for removed subrepos
1278 # check for removed subrepos
1273 for p in wctx.parents():
1279 for p in wctx.parents():
1274 r = [s for s in p.substate if s not in newstate]
1280 r = [s for s in p.substate if s not in newstate]
1275 subs += [s for s in r if match(s)]
1281 subs += [s for s in r if match(s)]
1276 if subs:
1282 if subs:
1277 if (not match('.hgsub') and
1283 if (not match('.hgsub') and
1278 '.hgsub' in (wctx.modified() + wctx.added())):
1284 '.hgsub' in (wctx.modified() + wctx.added())):
1279 raise util.Abort(
1285 raise util.Abort(
1280 _("can't commit subrepos without .hgsub"))
1286 _("can't commit subrepos without .hgsub"))
1281 changes[0].insert(0, '.hgsubstate')
1287 changes[0].insert(0, '.hgsubstate')
1282
1288
1283 elif '.hgsub' in changes[2]:
1289 elif '.hgsub' in changes[2]:
1284 # clean up .hgsubstate when .hgsub is removed
1290 # clean up .hgsubstate when .hgsub is removed
1285 if ('.hgsubstate' in wctx and
1291 if ('.hgsubstate' in wctx and
1286 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1292 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1287 changes[2].insert(0, '.hgsubstate')
1293 changes[2].insert(0, '.hgsubstate')
1288
1294
1289 # make sure all explicit patterns are matched
1295 # make sure all explicit patterns are matched
1290 if not force and match.files():
1296 if not force and match.files():
1291 matched = set(changes[0] + changes[1] + changes[2])
1297 matched = set(changes[0] + changes[1] + changes[2])
1292
1298
1293 for f in match.files():
1299 for f in match.files():
1294 f = self.dirstate.normalize(f)
1300 f = self.dirstate.normalize(f)
1295 if f == '.' or f in matched or f in wctx.substate:
1301 if f == '.' or f in matched or f in wctx.substate:
1296 continue
1302 continue
1297 if f in changes[3]: # missing
1303 if f in changes[3]: # missing
1298 fail(f, _('file not found!'))
1304 fail(f, _('file not found!'))
1299 if f in vdirs: # visited directory
1305 if f in vdirs: # visited directory
1300 d = f + '/'
1306 d = f + '/'
1301 for mf in matched:
1307 for mf in matched:
1302 if mf.startswith(d):
1308 if mf.startswith(d):
1303 break
1309 break
1304 else:
1310 else:
1305 fail(f, _("no match under directory!"))
1311 fail(f, _("no match under directory!"))
1306 elif f not in self.dirstate:
1312 elif f not in self.dirstate:
1307 fail(f, _("file not tracked!"))
1313 fail(f, _("file not tracked!"))
1308
1314
1309 cctx = context.workingctx(self, text, user, date, extra, changes)
1315 cctx = context.workingctx(self, text, user, date, extra, changes)
1310
1316
1311 if (not force and not extra.get("close") and not merge
1317 if (not force and not extra.get("close") and not merge
1312 and not cctx.files()
1318 and not cctx.files()
1313 and wctx.branch() == wctx.p1().branch()):
1319 and wctx.branch() == wctx.p1().branch()):
1314 return None
1320 return None
1315
1321
1316 if merge and cctx.deleted():
1322 if merge and cctx.deleted():
1317 raise util.Abort(_("cannot commit merge with missing files"))
1323 raise util.Abort(_("cannot commit merge with missing files"))
1318
1324
1319 ms = mergemod.mergestate(self)
1325 ms = mergemod.mergestate(self)
1320 for f in changes[0]:
1326 for f in changes[0]:
1321 if f in ms and ms[f] == 'u':
1327 if f in ms and ms[f] == 'u':
1322 raise util.Abort(_("unresolved merge conflicts "
1328 raise util.Abort(_("unresolved merge conflicts "
1323 "(see hg help resolve)"))
1329 "(see hg help resolve)"))
1324
1330
1325 if editor:
1331 if editor:
1326 cctx._text = editor(self, cctx, subs)
1332 cctx._text = editor(self, cctx, subs)
1327 edited = (text != cctx._text)
1333 edited = (text != cctx._text)
1328
1334
1329 # Save commit message in case this transaction gets rolled back
1335 # Save commit message in case this transaction gets rolled back
1330 # (e.g. by a pretxncommit hook). Leave the content alone on
1336 # (e.g. by a pretxncommit hook). Leave the content alone on
1331 # the assumption that the user will use the same editor again.
1337 # the assumption that the user will use the same editor again.
1332 msgfn = self.savecommitmessage(cctx._text)
1338 msgfn = self.savecommitmessage(cctx._text)
1333
1339
1334 # commit subs and write new state
1340 # commit subs and write new state
1335 if subs:
1341 if subs:
1336 for s in sorted(commitsubs):
1342 for s in sorted(commitsubs):
1337 sub = wctx.sub(s)
1343 sub = wctx.sub(s)
1338 self.ui.status(_('committing subrepository %s\n') %
1344 self.ui.status(_('committing subrepository %s\n') %
1339 subrepo.subrelpath(sub))
1345 subrepo.subrelpath(sub))
1340 sr = sub.commit(cctx._text, user, date)
1346 sr = sub.commit(cctx._text, user, date)
1341 newstate[s] = (newstate[s][0], sr)
1347 newstate[s] = (newstate[s][0], sr)
1342 subrepo.writestate(self, newstate)
1348 subrepo.writestate(self, newstate)
1343
1349
1344 p1, p2 = self.dirstate.parents()
1350 p1, p2 = self.dirstate.parents()
1345 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1351 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1346 try:
1352 try:
1347 self.hook("precommit", throw=True, parent1=hookp1,
1353 self.hook("precommit", throw=True, parent1=hookp1,
1348 parent2=hookp2)
1354 parent2=hookp2)
1349 ret = self.commitctx(cctx, True)
1355 ret = self.commitctx(cctx, True)
1350 except: # re-raises
1356 except: # re-raises
1351 if edited:
1357 if edited:
1352 self.ui.write(
1358 self.ui.write(
1353 _('note: commit message saved in %s\n') % msgfn)
1359 _('note: commit message saved in %s\n') % msgfn)
1354 raise
1360 raise
1355
1361
1356 # update bookmarks, dirstate and mergestate
1362 # update bookmarks, dirstate and mergestate
1357 bookmarks.update(self, [p1, p2], ret)
1363 bookmarks.update(self, [p1, p2], ret)
1358 cctx.markcommitted(ret)
1364 cctx.markcommitted(ret)
1359 ms.reset()
1365 ms.reset()
1360 finally:
1366 finally:
1361 wlock.release()
1367 wlock.release()
1362
1368
1363 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1369 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1364 self.hook("commit", node=node, parent1=parent1, parent2=parent2)
1370 self.hook("commit", node=node, parent1=parent1, parent2=parent2)
1365 self._afterlock(commithook)
1371 self._afterlock(commithook)
1366 return ret
1372 return ret
1367
1373
1368 @unfilteredmethod
1374 @unfilteredmethod
1369 def commitctx(self, ctx, error=False):
1375 def commitctx(self, ctx, error=False):
1370 """Add a new revision to current repository.
1376 """Add a new revision to current repository.
1371 Revision information is passed via the context argument.
1377 Revision information is passed via the context argument.
1372 """
1378 """
1373
1379
1374 tr = lock = None
1380 tr = lock = None
1375 removed = list(ctx.removed())
1381 removed = list(ctx.removed())
1376 p1, p2 = ctx.p1(), ctx.p2()
1382 p1, p2 = ctx.p1(), ctx.p2()
1377 user = ctx.user()
1383 user = ctx.user()
1378
1384
1379 lock = self.lock()
1385 lock = self.lock()
1380 try:
1386 try:
1381 tr = self.transaction("commit")
1387 tr = self.transaction("commit")
1382 trp = weakref.proxy(tr)
1388 trp = weakref.proxy(tr)
1383
1389
1384 if ctx.files():
1390 if ctx.files():
1385 m1 = p1.manifest().copy()
1391 m1 = p1.manifest().copy()
1386 m2 = p2.manifest()
1392 m2 = p2.manifest()
1387
1393
1388 # check in files
1394 # check in files
1389 new = {}
1395 new = {}
1390 changed = []
1396 changed = []
1391 linkrev = len(self)
1397 linkrev = len(self)
1392 for f in sorted(ctx.modified() + ctx.added()):
1398 for f in sorted(ctx.modified() + ctx.added()):
1393 self.ui.note(f + "\n")
1399 self.ui.note(f + "\n")
1394 try:
1400 try:
1395 fctx = ctx[f]
1401 fctx = ctx[f]
1396 if fctx is None:
1402 if fctx is None:
1397 removed.append(f)
1403 removed.append(f)
1398 else:
1404 else:
1399 new[f] = self._filecommit(fctx, m1, m2, linkrev,
1405 new[f] = self._filecommit(fctx, m1, m2, linkrev,
1400 trp, changed)
1406 trp, changed)
1401 m1.set(f, fctx.flags())
1407 m1.set(f, fctx.flags())
1402 except OSError, inst:
1408 except OSError, inst:
1403 self.ui.warn(_("trouble committing %s!\n") % f)
1409 self.ui.warn(_("trouble committing %s!\n") % f)
1404 raise
1410 raise
1405 except IOError, inst:
1411 except IOError, inst:
1406 errcode = getattr(inst, 'errno', errno.ENOENT)
1412 errcode = getattr(inst, 'errno', errno.ENOENT)
1407 if error or errcode and errcode != errno.ENOENT:
1413 if error or errcode and errcode != errno.ENOENT:
1408 self.ui.warn(_("trouble committing %s!\n") % f)
1414 self.ui.warn(_("trouble committing %s!\n") % f)
1409 raise
1415 raise
1410
1416
1411 # update manifest
1417 # update manifest
1412 m1.update(new)
1418 m1.update(new)
1413 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1419 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1414 drop = [f for f in removed if f in m1]
1420 drop = [f for f in removed if f in m1]
1415 for f in drop:
1421 for f in drop:
1416 del m1[f]
1422 del m1[f]
1417 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1423 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1418 p2.manifestnode(), new, drop)
1424 p2.manifestnode(), new, drop)
1419 files = changed + removed
1425 files = changed + removed
1420 else:
1426 else:
1421 mn = p1.manifestnode()
1427 mn = p1.manifestnode()
1422 files = []
1428 files = []
1423
1429
1424 # update changelog
1430 # update changelog
1425 self.changelog.delayupdate()
1431 self.changelog.delayupdate()
1426 n = self.changelog.add(mn, files, ctx.description(),
1432 n = self.changelog.add(mn, files, ctx.description(),
1427 trp, p1.node(), p2.node(),
1433 trp, p1.node(), p2.node(),
1428 user, ctx.date(), ctx.extra().copy())
1434 user, ctx.date(), ctx.extra().copy())
1429 p = lambda: self.changelog.writepending() and self.root or ""
1435 p = lambda: self.changelog.writepending() and self.root or ""
1430 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1436 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1431 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1437 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1432 parent2=xp2, pending=p)
1438 parent2=xp2, pending=p)
1433 self.changelog.finalize(trp)
1439 self.changelog.finalize(trp)
1434 # set the new commit is proper phase
1440 # set the new commit is proper phase
1435 targetphase = subrepo.newcommitphase(self.ui, ctx)
1441 targetphase = subrepo.newcommitphase(self.ui, ctx)
1436 if targetphase:
1442 if targetphase:
1437 # retract boundary do not alter parent changeset.
1443 # retract boundary do not alter parent changeset.
1438 # if a parent have higher the resulting phase will
1444 # if a parent have higher the resulting phase will
1439 # be compliant anyway
1445 # be compliant anyway
1440 #
1446 #
1441 # if minimal phase was 0 we don't need to retract anything
1447 # if minimal phase was 0 we don't need to retract anything
1442 phases.retractboundary(self, tr, targetphase, [n])
1448 phases.retractboundary(self, tr, targetphase, [n])
1443 tr.close()
1449 tr.close()
1444 branchmap.updatecache(self.filtered('served'))
1450 branchmap.updatecache(self.filtered('served'))
1445 return n
1451 return n
1446 finally:
1452 finally:
1447 if tr:
1453 if tr:
1448 tr.release()
1454 tr.release()
1449 lock.release()
1455 lock.release()
1450
1456
1451 @unfilteredmethod
1457 @unfilteredmethod
1452 def destroying(self):
1458 def destroying(self):
1453 '''Inform the repository that nodes are about to be destroyed.
1459 '''Inform the repository that nodes are about to be destroyed.
1454 Intended for use by strip and rollback, so there's a common
1460 Intended for use by strip and rollback, so there's a common
1455 place for anything that has to be done before destroying history.
1461 place for anything that has to be done before destroying history.
1456
1462
1457 This is mostly useful for saving state that is in memory and waiting
1463 This is mostly useful for saving state that is in memory and waiting
1458 to be flushed when the current lock is released. Because a call to
1464 to be flushed when the current lock is released. Because a call to
1459 destroyed is imminent, the repo will be invalidated causing those
1465 destroyed is imminent, the repo will be invalidated causing those
1460 changes to stay in memory (waiting for the next unlock), or vanish
1466 changes to stay in memory (waiting for the next unlock), or vanish
1461 completely.
1467 completely.
1462 '''
1468 '''
1463 # When using the same lock to commit and strip, the phasecache is left
1469 # When using the same lock to commit and strip, the phasecache is left
1464 # dirty after committing. Then when we strip, the repo is invalidated,
1470 # dirty after committing. Then when we strip, the repo is invalidated,
1465 # causing those changes to disappear.
1471 # causing those changes to disappear.
1466 if '_phasecache' in vars(self):
1472 if '_phasecache' in vars(self):
1467 self._phasecache.write()
1473 self._phasecache.write()
1468
1474
1469 @unfilteredmethod
1475 @unfilteredmethod
1470 def destroyed(self):
1476 def destroyed(self):
1471 '''Inform the repository that nodes have been destroyed.
1477 '''Inform the repository that nodes have been destroyed.
1472 Intended for use by strip and rollback, so there's a common
1478 Intended for use by strip and rollback, so there's a common
1473 place for anything that has to be done after destroying history.
1479 place for anything that has to be done after destroying history.
1474 '''
1480 '''
1475 # When one tries to:
1481 # When one tries to:
1476 # 1) destroy nodes thus calling this method (e.g. strip)
1482 # 1) destroy nodes thus calling this method (e.g. strip)
1477 # 2) use phasecache somewhere (e.g. commit)
1483 # 2) use phasecache somewhere (e.g. commit)
1478 #
1484 #
1479 # then 2) will fail because the phasecache contains nodes that were
1485 # then 2) will fail because the phasecache contains nodes that were
1480 # removed. We can either remove phasecache from the filecache,
1486 # removed. We can either remove phasecache from the filecache,
1481 # causing it to reload next time it is accessed, or simply filter
1487 # causing it to reload next time it is accessed, or simply filter
1482 # the removed nodes now and write the updated cache.
1488 # the removed nodes now and write the updated cache.
1483 self._phasecache.filterunknown(self)
1489 self._phasecache.filterunknown(self)
1484 self._phasecache.write()
1490 self._phasecache.write()
1485
1491
1486 # update the 'served' branch cache to help read only server process
1492 # update the 'served' branch cache to help read only server process
1487 # Thanks to branchcache collaboration this is done from the nearest
1493 # Thanks to branchcache collaboration this is done from the nearest
1488 # filtered subset and it is expected to be fast.
1494 # filtered subset and it is expected to be fast.
1489 branchmap.updatecache(self.filtered('served'))
1495 branchmap.updatecache(self.filtered('served'))
1490
1496
1491 # Ensure the persistent tag cache is updated. Doing it now
1497 # Ensure the persistent tag cache is updated. Doing it now
1492 # means that the tag cache only has to worry about destroyed
1498 # means that the tag cache only has to worry about destroyed
1493 # heads immediately after a strip/rollback. That in turn
1499 # heads immediately after a strip/rollback. That in turn
1494 # guarantees that "cachetip == currenttip" (comparing both rev
1500 # guarantees that "cachetip == currenttip" (comparing both rev
1495 # and node) always means no nodes have been added or destroyed.
1501 # and node) always means no nodes have been added or destroyed.
1496
1502
1497 # XXX this is suboptimal when qrefresh'ing: we strip the current
1503 # XXX this is suboptimal when qrefresh'ing: we strip the current
1498 # head, refresh the tag cache, then immediately add a new head.
1504 # head, refresh the tag cache, then immediately add a new head.
1499 # But I think doing it this way is necessary for the "instant
1505 # But I think doing it this way is necessary for the "instant
1500 # tag cache retrieval" case to work.
1506 # tag cache retrieval" case to work.
1501 self.invalidate()
1507 self.invalidate()
1502
1508
1503 def walk(self, match, node=None):
1509 def walk(self, match, node=None):
1504 '''
1510 '''
1505 walk recursively through the directory tree or a given
1511 walk recursively through the directory tree or a given
1506 changeset, finding all files matched by the match
1512 changeset, finding all files matched by the match
1507 function
1513 function
1508 '''
1514 '''
1509 return self[node].walk(match)
1515 return self[node].walk(match)
1510
1516
1511 def status(self, node1='.', node2=None, match=None,
1517 def status(self, node1='.', node2=None, match=None,
1512 ignored=False, clean=False, unknown=False,
1518 ignored=False, clean=False, unknown=False,
1513 listsubrepos=False):
1519 listsubrepos=False):
1514 '''a convenience method that calls node1.status(node2)'''
1520 '''a convenience method that calls node1.status(node2)'''
1515 return self[node1].status(node2, match, ignored, clean, unknown,
1521 return self[node1].status(node2, match, ignored, clean, unknown,
1516 listsubrepos)
1522 listsubrepos)
1517
1523
1518 def heads(self, start=None):
1524 def heads(self, start=None):
1519 heads = self.changelog.heads(start)
1525 heads = self.changelog.heads(start)
1520 # sort the output in rev descending order
1526 # sort the output in rev descending order
1521 return sorted(heads, key=self.changelog.rev, reverse=True)
1527 return sorted(heads, key=self.changelog.rev, reverse=True)
1522
1528
1523 def branchheads(self, branch=None, start=None, closed=False):
1529 def branchheads(self, branch=None, start=None, closed=False):
1524 '''return a (possibly filtered) list of heads for the given branch
1530 '''return a (possibly filtered) list of heads for the given branch
1525
1531
1526 Heads are returned in topological order, from newest to oldest.
1532 Heads are returned in topological order, from newest to oldest.
1527 If branch is None, use the dirstate branch.
1533 If branch is None, use the dirstate branch.
1528 If start is not None, return only heads reachable from start.
1534 If start is not None, return only heads reachable from start.
1529 If closed is True, return heads that are marked as closed as well.
1535 If closed is True, return heads that are marked as closed as well.
1530 '''
1536 '''
1531 if branch is None:
1537 if branch is None:
1532 branch = self[None].branch()
1538 branch = self[None].branch()
1533 branches = self.branchmap()
1539 branches = self.branchmap()
1534 if branch not in branches:
1540 if branch not in branches:
1535 return []
1541 return []
1536 # the cache returns heads ordered lowest to highest
1542 # the cache returns heads ordered lowest to highest
1537 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1543 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1538 if start is not None:
1544 if start is not None:
1539 # filter out the heads that cannot be reached from startrev
1545 # filter out the heads that cannot be reached from startrev
1540 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1546 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1541 bheads = [h for h in bheads if h in fbheads]
1547 bheads = [h for h in bheads if h in fbheads]
1542 return bheads
1548 return bheads
1543
1549
1544 def branches(self, nodes):
1550 def branches(self, nodes):
1545 if not nodes:
1551 if not nodes:
1546 nodes = [self.changelog.tip()]
1552 nodes = [self.changelog.tip()]
1547 b = []
1553 b = []
1548 for n in nodes:
1554 for n in nodes:
1549 t = n
1555 t = n
1550 while True:
1556 while True:
1551 p = self.changelog.parents(n)
1557 p = self.changelog.parents(n)
1552 if p[1] != nullid or p[0] == nullid:
1558 if p[1] != nullid or p[0] == nullid:
1553 b.append((t, n, p[0], p[1]))
1559 b.append((t, n, p[0], p[1]))
1554 break
1560 break
1555 n = p[0]
1561 n = p[0]
1556 return b
1562 return b
1557
1563
1558 def between(self, pairs):
1564 def between(self, pairs):
1559 r = []
1565 r = []
1560
1566
1561 for top, bottom in pairs:
1567 for top, bottom in pairs:
1562 n, l, i = top, [], 0
1568 n, l, i = top, [], 0
1563 f = 1
1569 f = 1
1564
1570
1565 while n != bottom and n != nullid:
1571 while n != bottom and n != nullid:
1566 p = self.changelog.parents(n)[0]
1572 p = self.changelog.parents(n)[0]
1567 if i == f:
1573 if i == f:
1568 l.append(n)
1574 l.append(n)
1569 f = f * 2
1575 f = f * 2
1570 n = p
1576 n = p
1571 i += 1
1577 i += 1
1572
1578
1573 r.append(l)
1579 r.append(l)
1574
1580
1575 return r
1581 return r
1576
1582
1577 def checkpush(self, pushop):
1583 def checkpush(self, pushop):
1578 """Extensions can override this function if additional checks have
1584 """Extensions can override this function if additional checks have
1579 to be performed before pushing, or call it if they override push
1585 to be performed before pushing, or call it if they override push
1580 command.
1586 command.
1581 """
1587 """
1582 pass
1588 pass
1583
1589
1584 @unfilteredpropertycache
1590 @unfilteredpropertycache
1585 def prepushoutgoinghooks(self):
1591 def prepushoutgoinghooks(self):
1586 """Return util.hooks consists of "(repo, remote, outgoing)"
1592 """Return util.hooks consists of "(repo, remote, outgoing)"
1587 functions, which are called before pushing changesets.
1593 functions, which are called before pushing changesets.
1588 """
1594 """
1589 return util.hooks()
1595 return util.hooks()
1590
1596
1591 def stream_in(self, remote, requirements):
1597 def stream_in(self, remote, requirements):
1592 lock = self.lock()
1598 lock = self.lock()
1593 try:
1599 try:
1594 # Save remote branchmap. We will use it later
1600 # Save remote branchmap. We will use it later
1595 # to speed up branchcache creation
1601 # to speed up branchcache creation
1596 rbranchmap = None
1602 rbranchmap = None
1597 if remote.capable("branchmap"):
1603 if remote.capable("branchmap"):
1598 rbranchmap = remote.branchmap()
1604 rbranchmap = remote.branchmap()
1599
1605
1600 fp = remote.stream_out()
1606 fp = remote.stream_out()
1601 l = fp.readline()
1607 l = fp.readline()
1602 try:
1608 try:
1603 resp = int(l)
1609 resp = int(l)
1604 except ValueError:
1610 except ValueError:
1605 raise error.ResponseError(
1611 raise error.ResponseError(
1606 _('unexpected response from remote server:'), l)
1612 _('unexpected response from remote server:'), l)
1607 if resp == 1:
1613 if resp == 1:
1608 raise util.Abort(_('operation forbidden by server'))
1614 raise util.Abort(_('operation forbidden by server'))
1609 elif resp == 2:
1615 elif resp == 2:
1610 raise util.Abort(_('locking the remote repository failed'))
1616 raise util.Abort(_('locking the remote repository failed'))
1611 elif resp != 0:
1617 elif resp != 0:
1612 raise util.Abort(_('the server sent an unknown error code'))
1618 raise util.Abort(_('the server sent an unknown error code'))
1613 self.ui.status(_('streaming all changes\n'))
1619 self.ui.status(_('streaming all changes\n'))
1614 l = fp.readline()
1620 l = fp.readline()
1615 try:
1621 try:
1616 total_files, total_bytes = map(int, l.split(' ', 1))
1622 total_files, total_bytes = map(int, l.split(' ', 1))
1617 except (ValueError, TypeError):
1623 except (ValueError, TypeError):
1618 raise error.ResponseError(
1624 raise error.ResponseError(
1619 _('unexpected response from remote server:'), l)
1625 _('unexpected response from remote server:'), l)
1620 self.ui.status(_('%d files to transfer, %s of data\n') %
1626 self.ui.status(_('%d files to transfer, %s of data\n') %
1621 (total_files, util.bytecount(total_bytes)))
1627 (total_files, util.bytecount(total_bytes)))
1622 handled_bytes = 0
1628 handled_bytes = 0
1623 self.ui.progress(_('clone'), 0, total=total_bytes)
1629 self.ui.progress(_('clone'), 0, total=total_bytes)
1624 start = time.time()
1630 start = time.time()
1625
1631
1626 tr = self.transaction(_('clone'))
1632 tr = self.transaction(_('clone'))
1627 try:
1633 try:
1628 for i in xrange(total_files):
1634 for i in xrange(total_files):
1629 # XXX doesn't support '\n' or '\r' in filenames
1635 # XXX doesn't support '\n' or '\r' in filenames
1630 l = fp.readline()
1636 l = fp.readline()
1631 try:
1637 try:
1632 name, size = l.split('\0', 1)
1638 name, size = l.split('\0', 1)
1633 size = int(size)
1639 size = int(size)
1634 except (ValueError, TypeError):
1640 except (ValueError, TypeError):
1635 raise error.ResponseError(
1641 raise error.ResponseError(
1636 _('unexpected response from remote server:'), l)
1642 _('unexpected response from remote server:'), l)
1637 if self.ui.debugflag:
1643 if self.ui.debugflag:
1638 self.ui.debug('adding %s (%s)\n' %
1644 self.ui.debug('adding %s (%s)\n' %
1639 (name, util.bytecount(size)))
1645 (name, util.bytecount(size)))
1640 # for backwards compat, name was partially encoded
1646 # for backwards compat, name was partially encoded
1641 ofp = self.sopener(store.decodedir(name), 'w')
1647 ofp = self.sopener(store.decodedir(name), 'w')
1642 for chunk in util.filechunkiter(fp, limit=size):
1648 for chunk in util.filechunkiter(fp, limit=size):
1643 handled_bytes += len(chunk)
1649 handled_bytes += len(chunk)
1644 self.ui.progress(_('clone'), handled_bytes,
1650 self.ui.progress(_('clone'), handled_bytes,
1645 total=total_bytes)
1651 total=total_bytes)
1646 ofp.write(chunk)
1652 ofp.write(chunk)
1647 ofp.close()
1653 ofp.close()
1648 tr.close()
1654 tr.close()
1649 finally:
1655 finally:
1650 tr.release()
1656 tr.release()
1651
1657
1652 # Writing straight to files circumvented the inmemory caches
1658 # Writing straight to files circumvented the inmemory caches
1653 self.invalidate()
1659 self.invalidate()
1654
1660
1655 elapsed = time.time() - start
1661 elapsed = time.time() - start
1656 if elapsed <= 0:
1662 if elapsed <= 0:
1657 elapsed = 0.001
1663 elapsed = 0.001
1658 self.ui.progress(_('clone'), None)
1664 self.ui.progress(_('clone'), None)
1659 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1665 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1660 (util.bytecount(total_bytes), elapsed,
1666 (util.bytecount(total_bytes), elapsed,
1661 util.bytecount(total_bytes / elapsed)))
1667 util.bytecount(total_bytes / elapsed)))
1662
1668
1663 # new requirements = old non-format requirements +
1669 # new requirements = old non-format requirements +
1664 # new format-related
1670 # new format-related
1665 # requirements from the streamed-in repository
1671 # requirements from the streamed-in repository
1666 requirements.update(set(self.requirements) - self.supportedformats)
1672 requirements.update(set(self.requirements) - self.supportedformats)
1667 self._applyrequirements(requirements)
1673 self._applyrequirements(requirements)
1668 self._writerequirements()
1674 self._writerequirements()
1669
1675
1670 if rbranchmap:
1676 if rbranchmap:
1671 rbheads = []
1677 rbheads = []
1672 for bheads in rbranchmap.itervalues():
1678 for bheads in rbranchmap.itervalues():
1673 rbheads.extend(bheads)
1679 rbheads.extend(bheads)
1674
1680
1675 if rbheads:
1681 if rbheads:
1676 rtiprev = max((int(self.changelog.rev(node))
1682 rtiprev = max((int(self.changelog.rev(node))
1677 for node in rbheads))
1683 for node in rbheads))
1678 cache = branchmap.branchcache(rbranchmap,
1684 cache = branchmap.branchcache(rbranchmap,
1679 self[rtiprev].node(),
1685 self[rtiprev].node(),
1680 rtiprev)
1686 rtiprev)
1681 # Try to stick it as low as possible
1687 # Try to stick it as low as possible
1682 # filter above served are unlikely to be fetch from a clone
1688 # filter above served are unlikely to be fetch from a clone
1683 for candidate in ('base', 'immutable', 'served'):
1689 for candidate in ('base', 'immutable', 'served'):
1684 rview = self.filtered(candidate)
1690 rview = self.filtered(candidate)
1685 if cache.validfor(rview):
1691 if cache.validfor(rview):
1686 self._branchcaches[candidate] = cache
1692 self._branchcaches[candidate] = cache
1687 cache.write(rview)
1693 cache.write(rview)
1688 break
1694 break
1689 self.invalidate()
1695 self.invalidate()
1690 return len(self.heads()) + 1
1696 return len(self.heads()) + 1
1691 finally:
1697 finally:
1692 lock.release()
1698 lock.release()
1693
1699
1694 def clone(self, remote, heads=[], stream=False):
1700 def clone(self, remote, heads=[], stream=False):
1695 '''clone remote repository.
1701 '''clone remote repository.
1696
1702
1697 keyword arguments:
1703 keyword arguments:
1698 heads: list of revs to clone (forces use of pull)
1704 heads: list of revs to clone (forces use of pull)
1699 stream: use streaming clone if possible'''
1705 stream: use streaming clone if possible'''
1700
1706
1701 # now, all clients that can request uncompressed clones can
1707 # now, all clients that can request uncompressed clones can
1702 # read repo formats supported by all servers that can serve
1708 # read repo formats supported by all servers that can serve
1703 # them.
1709 # them.
1704
1710
1705 # if revlog format changes, client will have to check version
1711 # if revlog format changes, client will have to check version
1706 # and format flags on "stream" capability, and use
1712 # and format flags on "stream" capability, and use
1707 # uncompressed only if compatible.
1713 # uncompressed only if compatible.
1708
1714
1709 if not stream:
1715 if not stream:
1710 # if the server explicitly prefers to stream (for fast LANs)
1716 # if the server explicitly prefers to stream (for fast LANs)
1711 stream = remote.capable('stream-preferred')
1717 stream = remote.capable('stream-preferred')
1712
1718
1713 if stream and not heads:
1719 if stream and not heads:
1714 # 'stream' means remote revlog format is revlogv1 only
1720 # 'stream' means remote revlog format is revlogv1 only
1715 if remote.capable('stream'):
1721 if remote.capable('stream'):
1716 return self.stream_in(remote, set(('revlogv1',)))
1722 return self.stream_in(remote, set(('revlogv1',)))
1717 # otherwise, 'streamreqs' contains the remote revlog format
1723 # otherwise, 'streamreqs' contains the remote revlog format
1718 streamreqs = remote.capable('streamreqs')
1724 streamreqs = remote.capable('streamreqs')
1719 if streamreqs:
1725 if streamreqs:
1720 streamreqs = set(streamreqs.split(','))
1726 streamreqs = set(streamreqs.split(','))
1721 # if we support it, stream in and adjust our requirements
1727 # if we support it, stream in and adjust our requirements
1722 if not streamreqs - self.supportedformats:
1728 if not streamreqs - self.supportedformats:
1723 return self.stream_in(remote, streamreqs)
1729 return self.stream_in(remote, streamreqs)
1724
1730
1725 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1731 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1726 try:
1732 try:
1727 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1733 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1728 ret = exchange.pull(self, remote, heads).cgresult
1734 ret = exchange.pull(self, remote, heads).cgresult
1729 finally:
1735 finally:
1730 self.ui.restoreconfig(quiet)
1736 self.ui.restoreconfig(quiet)
1731 return ret
1737 return ret
1732
1738
1733 def pushkey(self, namespace, key, old, new):
1739 def pushkey(self, namespace, key, old, new):
1734 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1740 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1735 old=old, new=new)
1741 old=old, new=new)
1736 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1742 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1737 ret = pushkey.push(self, namespace, key, old, new)
1743 ret = pushkey.push(self, namespace, key, old, new)
1738 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1744 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1739 ret=ret)
1745 ret=ret)
1740 return ret
1746 return ret
1741
1747
1742 def listkeys(self, namespace):
1748 def listkeys(self, namespace):
1743 self.hook('prelistkeys', throw=True, namespace=namespace)
1749 self.hook('prelistkeys', throw=True, namespace=namespace)
1744 self.ui.debug('listing keys for "%s"\n' % namespace)
1750 self.ui.debug('listing keys for "%s"\n' % namespace)
1745 values = pushkey.list(self, namespace)
1751 values = pushkey.list(self, namespace)
1746 self.hook('listkeys', namespace=namespace, values=values)
1752 self.hook('listkeys', namespace=namespace, values=values)
1747 return values
1753 return values
1748
1754
1749 def debugwireargs(self, one, two, three=None, four=None, five=None):
1755 def debugwireargs(self, one, two, three=None, four=None, five=None):
1750 '''used to test argument passing over the wire'''
1756 '''used to test argument passing over the wire'''
1751 return "%s %s %s %s %s" % (one, two, three, four, five)
1757 return "%s %s %s %s %s" % (one, two, three, four, five)
1752
1758
1753 def savecommitmessage(self, text):
1759 def savecommitmessage(self, text):
1754 fp = self.opener('last-message.txt', 'wb')
1760 fp = self.opener('last-message.txt', 'wb')
1755 try:
1761 try:
1756 fp.write(text)
1762 fp.write(text)
1757 finally:
1763 finally:
1758 fp.close()
1764 fp.close()
1759 return self.pathto(fp.name[len(self.root) + 1:])
1765 return self.pathto(fp.name[len(self.root) + 1:])
1760
1766
1761 # used to avoid circular references so destructors work
1767 # used to avoid circular references so destructors work
1762 def aftertrans(files):
1768 def aftertrans(files):
1763 renamefiles = [tuple(t) for t in files]
1769 renamefiles = [tuple(t) for t in files]
1764 def a():
1770 def a():
1765 for vfs, src, dest in renamefiles:
1771 for vfs, src, dest in renamefiles:
1766 try:
1772 try:
1767 vfs.rename(src, dest)
1773 vfs.rename(src, dest)
1768 except OSError: # journal file does not yet exist
1774 except OSError: # journal file does not yet exist
1769 pass
1775 pass
1770 return a
1776 return a
1771
1777
1772 def undoname(fn):
1778 def undoname(fn):
1773 base, name = os.path.split(fn)
1779 base, name = os.path.split(fn)
1774 assert name.startswith('journal')
1780 assert name.startswith('journal')
1775 return os.path.join(base, name.replace('journal', 'undo', 1))
1781 return os.path.join(base, name.replace('journal', 'undo', 1))
1776
1782
1777 def instance(ui, path, create):
1783 def instance(ui, path, create):
1778 return localrepository(ui, util.urllocalpath(path), create)
1784 return localrepository(ui, util.urllocalpath(path), create)
1779
1785
1780 def islocal(path):
1786 def islocal(path):
1781 return True
1787 return True
@@ -1,1146 +1,1146
1 # obsolete.py - obsolete markers handling
1 # obsolete.py - obsolete markers handling
2 #
2 #
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
4 # Logilab SA <contact@logilab.fr>
4 # Logilab SA <contact@logilab.fr>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 """Obsolete marker handling
9 """Obsolete marker handling
10
10
11 An obsolete marker maps an old changeset to a list of new
11 An obsolete marker maps an old changeset to a list of new
12 changesets. If the list of new changesets is empty, the old changeset
12 changesets. If the list of new changesets is empty, the old changeset
13 is said to be "killed". Otherwise, the old changeset is being
13 is said to be "killed". Otherwise, the old changeset is being
14 "replaced" by the new changesets.
14 "replaced" by the new changesets.
15
15
16 Obsolete markers can be used to record and distribute changeset graph
16 Obsolete markers can be used to record and distribute changeset graph
17 transformations performed by history rewrite operations, and help
17 transformations performed by history rewrite operations, and help
18 building new tools to reconcile conflicting rewrite actions. To
18 building new tools to reconcile conflicting rewrite actions. To
19 facilitate conflict resolution, markers include various annotations
19 facilitate conflict resolution, markers include various annotations
20 besides old and news changeset identifiers, such as creation date or
20 besides old and news changeset identifiers, such as creation date or
21 author name.
21 author name.
22
22
23 The old obsoleted changeset is called a "precursor" and possible
23 The old obsoleted changeset is called a "precursor" and possible
24 replacements are called "successors". Markers that used changeset X as
24 replacements are called "successors". Markers that used changeset X as
25 a precursor are called "successor markers of X" because they hold
25 a precursor are called "successor markers of X" because they hold
26 information about the successors of X. Markers that use changeset Y as
26 information about the successors of X. Markers that use changeset Y as
27 a successors are call "precursor markers of Y" because they hold
27 a successors are call "precursor markers of Y" because they hold
28 information about the precursors of Y.
28 information about the precursors of Y.
29
29
30 Examples:
30 Examples:
31
31
32 - When changeset A is replaced by changeset A', one marker is stored:
32 - When changeset A is replaced by changeset A', one marker is stored:
33
33
34 (A, (A',))
34 (A, (A',))
35
35
36 - When changesets A and B are folded into a new changeset C, two markers are
36 - When changesets A and B are folded into a new changeset C, two markers are
37 stored:
37 stored:
38
38
39 (A, (C,)) and (B, (C,))
39 (A, (C,)) and (B, (C,))
40
40
41 - When changeset A is simply "pruned" from the graph, a marker is created:
41 - When changeset A is simply "pruned" from the graph, a marker is created:
42
42
43 (A, ())
43 (A, ())
44
44
45 - When changeset A is split into B and C, a single marker are used:
45 - When changeset A is split into B and C, a single marker are used:
46
46
47 (A, (C, C))
47 (A, (C, C))
48
48
49 We use a single marker to distinguish the "split" case from the "divergence"
49 We use a single marker to distinguish the "split" case from the "divergence"
50 case. If two independent operations rewrite the same changeset A in to A' and
50 case. If two independent operations rewrite the same changeset A in to A' and
51 A'', we have an error case: divergent rewriting. We can detect it because
51 A'', we have an error case: divergent rewriting. We can detect it because
52 two markers will be created independently:
52 two markers will be created independently:
53
53
54 (A, (B,)) and (A, (C,))
54 (A, (B,)) and (A, (C,))
55
55
56 Format
56 Format
57 ------
57 ------
58
58
59 Markers are stored in an append-only file stored in
59 Markers are stored in an append-only file stored in
60 '.hg/store/obsstore'.
60 '.hg/store/obsstore'.
61
61
62 The file starts with a version header:
62 The file starts with a version header:
63
63
64 - 1 unsigned byte: version number, starting at zero.
64 - 1 unsigned byte: version number, starting at zero.
65
65
66 The header is followed by the markers. Marker format depend of the version. See
66 The header is followed by the markers. Marker format depend of the version. See
67 comment associated with each format for details.
67 comment associated with each format for details.
68
68
69 """
69 """
70 import struct
70 import struct
71 import util, base85, node
71 import util, base85, node
72 import phases
72 import phases
73 from i18n import _
73 from i18n import _
74
74
75 _pack = struct.pack
75 _pack = struct.pack
76 _unpack = struct.unpack
76 _unpack = struct.unpack
77
77
78 _SEEK_END = 2 # os.SEEK_END was introduced in Python 2.5
78 _SEEK_END = 2 # os.SEEK_END was introduced in Python 2.5
79
79
80 # the obsolete feature is not mature enough to be enabled by default.
80 # the obsolete feature is not mature enough to be enabled by default.
81 # you have to rely on third party extension extension to enable this.
81 # you have to rely on third party extension extension to enable this.
82 _enabled = False
82 _enabled = False
83
83
84 ### obsolescence marker flag
84 ### obsolescence marker flag
85
85
86 ## bumpedfix flag
86 ## bumpedfix flag
87 #
87 #
88 # When a changeset A' succeed to a changeset A which became public, we call A'
88 # When a changeset A' succeed to a changeset A which became public, we call A'
89 # "bumped" because it's a successors of a public changesets
89 # "bumped" because it's a successors of a public changesets
90 #
90 #
91 # o A' (bumped)
91 # o A' (bumped)
92 # |`:
92 # |`:
93 # | o A
93 # | o A
94 # |/
94 # |/
95 # o Z
95 # o Z
96 #
96 #
97 # The way to solve this situation is to create a new changeset Ad as children
97 # The way to solve this situation is to create a new changeset Ad as children
98 # of A. This changeset have the same content than A'. So the diff from A to A'
98 # of A. This changeset have the same content than A'. So the diff from A to A'
99 # is the same than the diff from A to Ad. Ad is marked as a successors of A'
99 # is the same than the diff from A to Ad. Ad is marked as a successors of A'
100 #
100 #
101 # o Ad
101 # o Ad
102 # |`:
102 # |`:
103 # | x A'
103 # | x A'
104 # |'|
104 # |'|
105 # o | A
105 # o | A
106 # |/
106 # |/
107 # o Z
107 # o Z
108 #
108 #
109 # But by transitivity Ad is also a successors of A. To avoid having Ad marked
109 # But by transitivity Ad is also a successors of A. To avoid having Ad marked
110 # as bumped too, we add the `bumpedfix` flag to the marker. <A', (Ad,)>.
110 # as bumped too, we add the `bumpedfix` flag to the marker. <A', (Ad,)>.
111 # This flag mean that the successors express the changes between the public and
111 # This flag mean that the successors express the changes between the public and
112 # bumped version and fix the situation, breaking the transitivity of
112 # bumped version and fix the situation, breaking the transitivity of
113 # "bumped" here.
113 # "bumped" here.
114 bumpedfix = 1
114 bumpedfix = 1
115 usingsha256 = 2
115 usingsha256 = 2
116
116
117 ## Parsing and writing of version "0"
117 ## Parsing and writing of version "0"
118 #
118 #
119 # The header is followed by the markers. Each marker is made of:
119 # The header is followed by the markers. Each marker is made of:
120 #
120 #
121 # - 1 uint8 : number of new changesets "N", can be zero.
121 # - 1 uint8 : number of new changesets "N", can be zero.
122 #
122 #
123 # - 1 uint32: metadata size "M" in bytes.
123 # - 1 uint32: metadata size "M" in bytes.
124 #
124 #
125 # - 1 byte: a bit field. It is reserved for flags used in common
125 # - 1 byte: a bit field. It is reserved for flags used in common
126 # obsolete marker operations, to avoid repeated decoding of metadata
126 # obsolete marker operations, to avoid repeated decoding of metadata
127 # entries.
127 # entries.
128 #
128 #
129 # - 20 bytes: obsoleted changeset identifier.
129 # - 20 bytes: obsoleted changeset identifier.
130 #
130 #
131 # - N*20 bytes: new changesets identifiers.
131 # - N*20 bytes: new changesets identifiers.
132 #
132 #
133 # - M bytes: metadata as a sequence of nul-terminated strings. Each
133 # - M bytes: metadata as a sequence of nul-terminated strings. Each
134 # string contains a key and a value, separated by a colon ':', without
134 # string contains a key and a value, separated by a colon ':', without
135 # additional encoding. Keys cannot contain '\0' or ':' and values
135 # additional encoding. Keys cannot contain '\0' or ':' and values
136 # cannot contain '\0'.
136 # cannot contain '\0'.
137 _fm0version = 0
137 _fm0version = 0
138 _fm0fixed = '>BIB20s'
138 _fm0fixed = '>BIB20s'
139 _fm0node = '20s'
139 _fm0node = '20s'
140 _fm0fsize = struct.calcsize(_fm0fixed)
140 _fm0fsize = struct.calcsize(_fm0fixed)
141 _fm0fnodesize = struct.calcsize(_fm0node)
141 _fm0fnodesize = struct.calcsize(_fm0node)
142
142
143 def _fm0readmarkers(data, off=0):
143 def _fm0readmarkers(data, off=0):
144 # Loop on markers
144 # Loop on markers
145 l = len(data)
145 l = len(data)
146 while off + _fm0fsize <= l:
146 while off + _fm0fsize <= l:
147 # read fixed part
147 # read fixed part
148 cur = data[off:off + _fm0fsize]
148 cur = data[off:off + _fm0fsize]
149 off += _fm0fsize
149 off += _fm0fsize
150 numsuc, mdsize, flags, pre = _unpack(_fm0fixed, cur)
150 numsuc, mdsize, flags, pre = _unpack(_fm0fixed, cur)
151 # read replacement
151 # read replacement
152 sucs = ()
152 sucs = ()
153 if numsuc:
153 if numsuc:
154 s = (_fm0fnodesize * numsuc)
154 s = (_fm0fnodesize * numsuc)
155 cur = data[off:off + s]
155 cur = data[off:off + s]
156 sucs = _unpack(_fm0node * numsuc, cur)
156 sucs = _unpack(_fm0node * numsuc, cur)
157 off += s
157 off += s
158 # read metadata
158 # read metadata
159 # (metadata will be decoded on demand)
159 # (metadata will be decoded on demand)
160 metadata = data[off:off + mdsize]
160 metadata = data[off:off + mdsize]
161 if len(metadata) != mdsize:
161 if len(metadata) != mdsize:
162 raise util.Abort(_('parsing obsolete marker: metadata is too '
162 raise util.Abort(_('parsing obsolete marker: metadata is too '
163 'short, %d bytes expected, got %d')
163 'short, %d bytes expected, got %d')
164 % (mdsize, len(metadata)))
164 % (mdsize, len(metadata)))
165 off += mdsize
165 off += mdsize
166 metadata = _fm0decodemeta(metadata)
166 metadata = _fm0decodemeta(metadata)
167 try:
167 try:
168 when, offset = metadata.pop('date', '0 0').split(' ')
168 when, offset = metadata.pop('date', '0 0').split(' ')
169 date = float(when), int(offset)
169 date = float(when), int(offset)
170 except ValueError:
170 except ValueError:
171 date = (0., 0)
171 date = (0., 0)
172 parents = None
172 parents = None
173 if 'p2' in metadata:
173 if 'p2' in metadata:
174 parents = (metadata.pop('p1', None), metadata.pop('p2', None))
174 parents = (metadata.pop('p1', None), metadata.pop('p2', None))
175 elif 'p1' in metadata:
175 elif 'p1' in metadata:
176 parents = (metadata.pop('p1', None),)
176 parents = (metadata.pop('p1', None),)
177 elif 'p0' in metadata:
177 elif 'p0' in metadata:
178 parents = ()
178 parents = ()
179 if parents is not None:
179 if parents is not None:
180 try:
180 try:
181 parents = tuple(node.bin(p) for p in parents)
181 parents = tuple(node.bin(p) for p in parents)
182 # if parent content is not a nodeid, drop the data
182 # if parent content is not a nodeid, drop the data
183 for p in parents:
183 for p in parents:
184 if len(p) != 20:
184 if len(p) != 20:
185 parents = None
185 parents = None
186 break
186 break
187 except TypeError:
187 except TypeError:
188 # if content cannot be translated to nodeid drop the data.
188 # if content cannot be translated to nodeid drop the data.
189 parents = None
189 parents = None
190
190
191 metadata = tuple(sorted(metadata.iteritems()))
191 metadata = tuple(sorted(metadata.iteritems()))
192
192
193 yield (pre, sucs, flags, metadata, date, parents)
193 yield (pre, sucs, flags, metadata, date, parents)
194
194
195 def _fm0encodeonemarker(marker):
195 def _fm0encodeonemarker(marker):
196 pre, sucs, flags, metadata, date, parents = marker
196 pre, sucs, flags, metadata, date, parents = marker
197 if flags & usingsha256:
197 if flags & usingsha256:
198 raise util.Abort(_('cannot handle sha256 with old obsstore format'))
198 raise util.Abort(_('cannot handle sha256 with old obsstore format'))
199 metadata = dict(metadata)
199 metadata = dict(metadata)
200 metadata['date'] = '%d %i' % date
200 metadata['date'] = '%d %i' % date
201 if parents is not None:
201 if parents is not None:
202 if not parents:
202 if not parents:
203 # mark that we explicitly recorded no parents
203 # mark that we explicitly recorded no parents
204 metadata['p0'] = ''
204 metadata['p0'] = ''
205 for i, p in enumerate(parents):
205 for i, p in enumerate(parents):
206 metadata['p%i' % (i + 1)] = node.hex(p)
206 metadata['p%i' % (i + 1)] = node.hex(p)
207 metadata = _fm0encodemeta(metadata)
207 metadata = _fm0encodemeta(metadata)
208 numsuc = len(sucs)
208 numsuc = len(sucs)
209 format = _fm0fixed + (_fm0node * numsuc)
209 format = _fm0fixed + (_fm0node * numsuc)
210 data = [numsuc, len(metadata), flags, pre]
210 data = [numsuc, len(metadata), flags, pre]
211 data.extend(sucs)
211 data.extend(sucs)
212 return _pack(format, *data) + metadata
212 return _pack(format, *data) + metadata
213
213
214 def _fm0encodemeta(meta):
214 def _fm0encodemeta(meta):
215 """Return encoded metadata string to string mapping.
215 """Return encoded metadata string to string mapping.
216
216
217 Assume no ':' in key and no '\0' in both key and value."""
217 Assume no ':' in key and no '\0' in both key and value."""
218 for key, value in meta.iteritems():
218 for key, value in meta.iteritems():
219 if ':' in key or '\0' in key:
219 if ':' in key or '\0' in key:
220 raise ValueError("':' and '\0' are forbidden in metadata key'")
220 raise ValueError("':' and '\0' are forbidden in metadata key'")
221 if '\0' in value:
221 if '\0' in value:
222 raise ValueError("':' is forbidden in metadata value'")
222 raise ValueError("':' is forbidden in metadata value'")
223 return '\0'.join(['%s:%s' % (k, meta[k]) for k in sorted(meta)])
223 return '\0'.join(['%s:%s' % (k, meta[k]) for k in sorted(meta)])
224
224
225 def _fm0decodemeta(data):
225 def _fm0decodemeta(data):
226 """Return string to string dictionary from encoded version."""
226 """Return string to string dictionary from encoded version."""
227 d = {}
227 d = {}
228 for l in data.split('\0'):
228 for l in data.split('\0'):
229 if l:
229 if l:
230 key, value = l.split(':')
230 key, value = l.split(':')
231 d[key] = value
231 d[key] = value
232 return d
232 return d
233
233
234 ## Parsing and writing of version "1"
234 ## Parsing and writing of version "1"
235 #
235 #
236 # The header is followed by the markers. Each marker is made of:
236 # The header is followed by the markers. Each marker is made of:
237 #
237 #
238 # - uint32: total size of the marker (including this field)
238 # - uint32: total size of the marker (including this field)
239 #
239 #
240 # - float64: date in seconds since epoch
240 # - float64: date in seconds since epoch
241 #
241 #
242 # - int16: timezone offset in minutes
242 # - int16: timezone offset in minutes
243 #
243 #
244 # - uint16: a bit field. It is reserved for flags used in common
244 # - uint16: a bit field. It is reserved for flags used in common
245 # obsolete marker operations, to avoid repeated decoding of metadata
245 # obsolete marker operations, to avoid repeated decoding of metadata
246 # entries.
246 # entries.
247 #
247 #
248 # - uint8: number of successors "N", can be zero.
248 # - uint8: number of successors "N", can be zero.
249 #
249 #
250 # - uint8: number of parents "P", can be zero.
250 # - uint8: number of parents "P", can be zero.
251 #
251 #
252 # 0: parents data stored but no parent,
252 # 0: parents data stored but no parent,
253 # 1: one parent stored,
253 # 1: one parent stored,
254 # 2: two parents stored,
254 # 2: two parents stored,
255 # 3: no parent data stored
255 # 3: no parent data stored
256 #
256 #
257 # - uint8: number of metadata entries M
257 # - uint8: number of metadata entries M
258 #
258 #
259 # - 20 or 32 bytes: precursor changeset identifier.
259 # - 20 or 32 bytes: precursor changeset identifier.
260 #
260 #
261 # - N*(20 or 32) bytes: successors changesets identifiers.
261 # - N*(20 or 32) bytes: successors changesets identifiers.
262 #
262 #
263 # - P*(20 or 32) bytes: parents of the precursors changesets.
263 # - P*(20 or 32) bytes: parents of the precursors changesets.
264 #
264 #
265 # - M*(uint8, uint8): size of all metadata entries (key and value)
265 # - M*(uint8, uint8): size of all metadata entries (key and value)
266 #
266 #
267 # - remaining bytes: the metadata, each (key, value) pair after the other.
267 # - remaining bytes: the metadata, each (key, value) pair after the other.
268 _fm1version = 1
268 _fm1version = 1
269 _fm1fixed = '>IdhHBBB20s'
269 _fm1fixed = '>IdhHBBB20s'
270 _fm1nodesha1 = '20s'
270 _fm1nodesha1 = '20s'
271 _fm1nodesha256 = '32s'
271 _fm1nodesha256 = '32s'
272 _fm1fsize = struct.calcsize(_fm1fixed)
272 _fm1fsize = struct.calcsize(_fm1fixed)
273 _fm1parentnone = 3
273 _fm1parentnone = 3
274 _fm1parentshift = 14
274 _fm1parentshift = 14
275 _fm1parentmask = (_fm1parentnone << _fm1parentshift)
275 _fm1parentmask = (_fm1parentnone << _fm1parentshift)
276 _fm1metapair = 'BB'
276 _fm1metapair = 'BB'
277 _fm1metapairsize = struct.calcsize('BB')
277 _fm1metapairsize = struct.calcsize('BB')
278
278
279 def _fm1readmarkers(data, off=0):
279 def _fm1readmarkers(data, off=0):
280 # Loop on markers
280 # Loop on markers
281 l = len(data)
281 l = len(data)
282 while off + _fm1fsize <= l:
282 while off + _fm1fsize <= l:
283 # read fixed part
283 # read fixed part
284 cur = data[off:off + _fm1fsize]
284 cur = data[off:off + _fm1fsize]
285 off += _fm1fsize
285 off += _fm1fsize
286 fixeddata = _unpack(_fm1fixed, cur)
286 fixeddata = _unpack(_fm1fixed, cur)
287 ttsize, seconds, tz, flags, numsuc, numpar, nummeta, prec = fixeddata
287 ttsize, seconds, tz, flags, numsuc, numpar, nummeta, prec = fixeddata
288 # extract the number of parents information
288 # extract the number of parents information
289 if numpar == _fm1parentnone:
289 if numpar == _fm1parentnone:
290 numpar = None
290 numpar = None
291 # build the date tuple (upgrade tz minutes to seconds)
291 # build the date tuple (upgrade tz minutes to seconds)
292 date = (seconds, tz * 60)
292 date = (seconds, tz * 60)
293 _fm1node = _fm1nodesha1
293 _fm1node = _fm1nodesha1
294 if flags & usingsha256:
294 if flags & usingsha256:
295 _fm1node = _fm1nodesha256
295 _fm1node = _fm1nodesha256
296 fnodesize = struct.calcsize(_fm1node)
296 fnodesize = struct.calcsize(_fm1node)
297 # read replacement
297 # read replacement
298 sucs = ()
298 sucs = ()
299 if numsuc:
299 if numsuc:
300 s = (fnodesize * numsuc)
300 s = (fnodesize * numsuc)
301 cur = data[off:off + s]
301 cur = data[off:off + s]
302 sucs = _unpack(_fm1node * numsuc, cur)
302 sucs = _unpack(_fm1node * numsuc, cur)
303 off += s
303 off += s
304 # read parents
304 # read parents
305 if numpar is None:
305 if numpar is None:
306 parents = None
306 parents = None
307 elif numpar == 0:
307 elif numpar == 0:
308 parents = ()
308 parents = ()
309 elif numpar: # neither None nor zero
309 elif numpar: # neither None nor zero
310 s = (fnodesize * numpar)
310 s = (fnodesize * numpar)
311 cur = data[off:off + s]
311 cur = data[off:off + s]
312 parents = _unpack(_fm1node * numpar, cur)
312 parents = _unpack(_fm1node * numpar, cur)
313 off += s
313 off += s
314 # read metadata
314 # read metadata
315 metaformat = '>' + (_fm1metapair * nummeta)
315 metaformat = '>' + (_fm1metapair * nummeta)
316 s = _fm1metapairsize * nummeta
316 s = _fm1metapairsize * nummeta
317 metapairsize = _unpack(metaformat, data[off:off + s])
317 metapairsize = _unpack(metaformat, data[off:off + s])
318 off += s
318 off += s
319 metadata = []
319 metadata = []
320 for idx in xrange(0, len(metapairsize), 2):
320 for idx in xrange(0, len(metapairsize), 2):
321 sk = metapairsize[idx]
321 sk = metapairsize[idx]
322 sv = metapairsize[idx + 1]
322 sv = metapairsize[idx + 1]
323 key = data[off:off + sk]
323 key = data[off:off + sk]
324 value = data[off + sk:off + sk + sv]
324 value = data[off + sk:off + sk + sv]
325 assert len(key) == sk
325 assert len(key) == sk
326 assert len(value) == sv
326 assert len(value) == sv
327 metadata.append((key, value))
327 metadata.append((key, value))
328 off += sk + sv
328 off += sk + sv
329 metadata = tuple(metadata)
329 metadata = tuple(metadata)
330
330
331 yield (prec, sucs, flags, metadata, date, parents)
331 yield (prec, sucs, flags, metadata, date, parents)
332
332
333 def _fm1encodeonemarker(marker):
333 def _fm1encodeonemarker(marker):
334 pre, sucs, flags, metadata, date, parents = marker
334 pre, sucs, flags, metadata, date, parents = marker
335 # determine node size
335 # determine node size
336 _fm1node = _fm1nodesha1
336 _fm1node = _fm1nodesha1
337 if flags & usingsha256:
337 if flags & usingsha256:
338 _fm1node = _fm1nodesha256
338 _fm1node = _fm1nodesha256
339 numsuc = len(sucs)
339 numsuc = len(sucs)
340 numextranodes = numsuc
340 numextranodes = numsuc
341 if parents is None:
341 if parents is None:
342 numpar = _fm1parentnone
342 numpar = _fm1parentnone
343 else:
343 else:
344 numpar = len(parents)
344 numpar = len(parents)
345 numextranodes += numpar
345 numextranodes += numpar
346 formatnodes = _fm1node * numextranodes
346 formatnodes = _fm1node * numextranodes
347 formatmeta = _fm1metapair * len(metadata)
347 formatmeta = _fm1metapair * len(metadata)
348 format = _fm1fixed + formatnodes + formatmeta
348 format = _fm1fixed + formatnodes + formatmeta
349 # tz is stored in minutes so we divide by 60
349 # tz is stored in minutes so we divide by 60
350 tz = date[1]//60
350 tz = date[1]//60
351 data = [None, date[0], tz, flags, numsuc, numpar, len(metadata), pre]
351 data = [None, date[0], tz, flags, numsuc, numpar, len(metadata), pre]
352 data.extend(sucs)
352 data.extend(sucs)
353 if parents is not None:
353 if parents is not None:
354 data.extend(parents)
354 data.extend(parents)
355 totalsize = struct.calcsize(format)
355 totalsize = struct.calcsize(format)
356 for key, value in metadata:
356 for key, value in metadata:
357 lk = len(key)
357 lk = len(key)
358 lv = len(value)
358 lv = len(value)
359 data.append(lk)
359 data.append(lk)
360 data.append(lv)
360 data.append(lv)
361 totalsize += lk + lv
361 totalsize += lk + lv
362 data[0] = totalsize
362 data[0] = totalsize
363 data = [_pack(format, *data)]
363 data = [_pack(format, *data)]
364 for key, value in metadata:
364 for key, value in metadata:
365 data.append(key)
365 data.append(key)
366 data.append(value)
366 data.append(value)
367 return ''.join(data)
367 return ''.join(data)
368
368
369 # mapping to read/write various marker formats
369 # mapping to read/write various marker formats
370 # <version> -> (decoder, encoder)
370 # <version> -> (decoder, encoder)
371 formats = {_fm0version: (_fm0readmarkers, _fm0encodeonemarker),
371 formats = {_fm0version: (_fm0readmarkers, _fm0encodeonemarker),
372 _fm1version: (_fm1readmarkers, _fm1encodeonemarker)}
372 _fm1version: (_fm1readmarkers, _fm1encodeonemarker)}
373
373
374 def _readmarkers(data):
374 def _readmarkers(data):
375 """Read and enumerate markers from raw data"""
375 """Read and enumerate markers from raw data"""
376 off = 0
376 off = 0
377 diskversion = _unpack('>B', data[off:off + 1])[0]
377 diskversion = _unpack('>B', data[off:off + 1])[0]
378 off += 1
378 off += 1
379 if diskversion not in formats:
379 if diskversion not in formats:
380 raise util.Abort(_('parsing obsolete marker: unknown version %r')
380 raise util.Abort(_('parsing obsolete marker: unknown version %r')
381 % diskversion)
381 % diskversion)
382 return diskversion, formats[diskversion][0](data, off)
382 return diskversion, formats[diskversion][0](data, off)
383
383
384 def encodemarkers(markers, addheader=False, version=_fm0version):
384 def encodemarkers(markers, addheader=False, version=_fm0version):
385 # Kept separate from flushmarkers(), it will be reused for
385 # Kept separate from flushmarkers(), it will be reused for
386 # markers exchange.
386 # markers exchange.
387 encodeone = formats[version][1]
387 encodeone = formats[version][1]
388 if addheader:
388 if addheader:
389 yield _pack('>B', version)
389 yield _pack('>B', version)
390 for marker in markers:
390 for marker in markers:
391 yield encodeone(marker)
391 yield encodeone(marker)
392
392
393
393
394 class marker(object):
394 class marker(object):
395 """Wrap obsolete marker raw data"""
395 """Wrap obsolete marker raw data"""
396
396
397 def __init__(self, repo, data):
397 def __init__(self, repo, data):
398 # the repo argument will be used to create changectx in later version
398 # the repo argument will be used to create changectx in later version
399 self._repo = repo
399 self._repo = repo
400 self._data = data
400 self._data = data
401 self._decodedmeta = None
401 self._decodedmeta = None
402
402
403 def __hash__(self):
403 def __hash__(self):
404 return hash(self._data)
404 return hash(self._data)
405
405
406 def __eq__(self, other):
406 def __eq__(self, other):
407 if type(other) != type(self):
407 if type(other) != type(self):
408 return False
408 return False
409 return self._data == other._data
409 return self._data == other._data
410
410
411 def precnode(self):
411 def precnode(self):
412 """Precursor changeset node identifier"""
412 """Precursor changeset node identifier"""
413 return self._data[0]
413 return self._data[0]
414
414
415 def succnodes(self):
415 def succnodes(self):
416 """List of successor changesets node identifiers"""
416 """List of successor changesets node identifiers"""
417 return self._data[1]
417 return self._data[1]
418
418
419 def parentnodes(self):
419 def parentnodes(self):
420 """Parents of the precursors (None if not recorded)"""
420 """Parents of the precursors (None if not recorded)"""
421 return self._data[5]
421 return self._data[5]
422
422
423 def metadata(self):
423 def metadata(self):
424 """Decoded metadata dictionary"""
424 """Decoded metadata dictionary"""
425 return dict(self._data[3])
425 return dict(self._data[3])
426
426
427 def date(self):
427 def date(self):
428 """Creation date as (unixtime, offset)"""
428 """Creation date as (unixtime, offset)"""
429 return self._data[4]
429 return self._data[4]
430
430
431 def flags(self):
431 def flags(self):
432 """The flags field of the marker"""
432 """The flags field of the marker"""
433 return self._data[2]
433 return self._data[2]
434
434
435 class obsstore(object):
435 class obsstore(object):
436 """Store obsolete markers
436 """Store obsolete markers
437
437
438 Markers can be accessed with two mappings:
438 Markers can be accessed with two mappings:
439 - precursors[x] -> set(markers on precursors edges of x)
439 - precursors[x] -> set(markers on precursors edges of x)
440 - successors[x] -> set(markers on successors edges of x)
440 - successors[x] -> set(markers on successors edges of x)
441 - children[x] -> set(markers on precursors edges of children(x)
441 - children[x] -> set(markers on precursors edges of children(x)
442 """
442 """
443
443
444 fields = ('prec', 'succs', 'flag', 'meta', 'date', 'parents')
444 fields = ('prec', 'succs', 'flag', 'meta', 'date', 'parents')
445 # prec: nodeid, precursor changesets
445 # prec: nodeid, precursor changesets
446 # succs: tuple of nodeid, successor changesets (0-N length)
446 # succs: tuple of nodeid, successor changesets (0-N length)
447 # flag: integer, flag field carrying modifier for the markers (see doc)
447 # flag: integer, flag field carrying modifier for the markers (see doc)
448 # meta: binary blob, encoded metadata dictionary
448 # meta: binary blob, encoded metadata dictionary
449 # date: (float, int) tuple, date of marker creation
449 # date: (float, int) tuple, date of marker creation
450 # parents: (tuple of nodeid) or None, parents of precursors
450 # parents: (tuple of nodeid) or None, parents of precursors
451 # None is used when no data has been recorded
451 # None is used when no data has been recorded
452
452
453 def __init__(self, sopener):
453 def __init__(self, sopener, defaultformat=_fm0version):
454 # caches for various obsolescence related cache
454 # caches for various obsolescence related cache
455 self.caches = {}
455 self.caches = {}
456 self._all = []
456 self._all = []
457 self.precursors = {}
457 self.precursors = {}
458 self.successors = {}
458 self.successors = {}
459 self.children = {}
459 self.children = {}
460 self.sopener = sopener
460 self.sopener = sopener
461 data = sopener.tryread('obsstore')
461 data = sopener.tryread('obsstore')
462 self._version = _fm0version
462 self._version = defaultformat
463 if data:
463 if data:
464 self._version, markers = _readmarkers(data)
464 self._version, markers = _readmarkers(data)
465 self._load(markers)
465 self._load(markers)
466
466
467 def __iter__(self):
467 def __iter__(self):
468 return iter(self._all)
468 return iter(self._all)
469
469
470 def __len__(self):
470 def __len__(self):
471 return len(self._all)
471 return len(self._all)
472
472
473 def __nonzero__(self):
473 def __nonzero__(self):
474 return bool(self._all)
474 return bool(self._all)
475
475
476 def create(self, transaction, prec, succs=(), flag=0, parents=None,
476 def create(self, transaction, prec, succs=(), flag=0, parents=None,
477 date=None, metadata=None):
477 date=None, metadata=None):
478 """obsolete: add a new obsolete marker
478 """obsolete: add a new obsolete marker
479
479
480 * ensuring it is hashable
480 * ensuring it is hashable
481 * check mandatory metadata
481 * check mandatory metadata
482 * encode metadata
482 * encode metadata
483
483
484 If you are a human writing code creating marker you want to use the
484 If you are a human writing code creating marker you want to use the
485 `createmarkers` function in this module instead.
485 `createmarkers` function in this module instead.
486
486
487 return True if a new marker have been added, False if the markers
487 return True if a new marker have been added, False if the markers
488 already existed (no op).
488 already existed (no op).
489 """
489 """
490 if metadata is None:
490 if metadata is None:
491 metadata = {}
491 metadata = {}
492 if date is None:
492 if date is None:
493 if 'date' in metadata:
493 if 'date' in metadata:
494 # as a courtesy for out-of-tree extensions
494 # as a courtesy for out-of-tree extensions
495 date = util.parsedate(metadata.pop('date'))
495 date = util.parsedate(metadata.pop('date'))
496 else:
496 else:
497 date = util.makedate()
497 date = util.makedate()
498 if len(prec) != 20:
498 if len(prec) != 20:
499 raise ValueError(prec)
499 raise ValueError(prec)
500 for succ in succs:
500 for succ in succs:
501 if len(succ) != 20:
501 if len(succ) != 20:
502 raise ValueError(succ)
502 raise ValueError(succ)
503 if prec in succs:
503 if prec in succs:
504 raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
504 raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
505
505
506 metadata = tuple(sorted(metadata.iteritems()))
506 metadata = tuple(sorted(metadata.iteritems()))
507
507
508 marker = (str(prec), tuple(succs), int(flag), metadata, date, parents)
508 marker = (str(prec), tuple(succs), int(flag), metadata, date, parents)
509 return bool(self.add(transaction, [marker]))
509 return bool(self.add(transaction, [marker]))
510
510
511 def add(self, transaction, markers):
511 def add(self, transaction, markers):
512 """Add new markers to the store
512 """Add new markers to the store
513
513
514 Take care of filtering duplicate.
514 Take care of filtering duplicate.
515 Return the number of new marker."""
515 Return the number of new marker."""
516 if not _enabled:
516 if not _enabled:
517 raise util.Abort('obsolete feature is not enabled on this repo')
517 raise util.Abort('obsolete feature is not enabled on this repo')
518 known = set(self._all)
518 known = set(self._all)
519 new = []
519 new = []
520 for m in markers:
520 for m in markers:
521 if m not in known:
521 if m not in known:
522 known.add(m)
522 known.add(m)
523 new.append(m)
523 new.append(m)
524 if new:
524 if new:
525 f = self.sopener('obsstore', 'ab')
525 f = self.sopener('obsstore', 'ab')
526 try:
526 try:
527 # Whether the file's current position is at the begin or at
527 # Whether the file's current position is at the begin or at
528 # the end after opening a file for appending is implementation
528 # the end after opening a file for appending is implementation
529 # defined. So we must seek to the end before calling tell(),
529 # defined. So we must seek to the end before calling tell(),
530 # or we may get a zero offset for non-zero sized files on
530 # or we may get a zero offset for non-zero sized files on
531 # some platforms (issue3543).
531 # some platforms (issue3543).
532 f.seek(0, _SEEK_END)
532 f.seek(0, _SEEK_END)
533 offset = f.tell()
533 offset = f.tell()
534 transaction.add('obsstore', offset)
534 transaction.add('obsstore', offset)
535 # offset == 0: new file - add the version header
535 # offset == 0: new file - add the version header
536 for bytes in encodemarkers(new, offset == 0, self._version):
536 for bytes in encodemarkers(new, offset == 0, self._version):
537 f.write(bytes)
537 f.write(bytes)
538 finally:
538 finally:
539 # XXX: f.close() == filecache invalidation == obsstore rebuilt.
539 # XXX: f.close() == filecache invalidation == obsstore rebuilt.
540 # call 'filecacheentry.refresh()' here
540 # call 'filecacheentry.refresh()' here
541 f.close()
541 f.close()
542 self._load(new)
542 self._load(new)
543 # new marker *may* have changed several set. invalidate the cache.
543 # new marker *may* have changed several set. invalidate the cache.
544 self.caches.clear()
544 self.caches.clear()
545 # records the number of new markers for the transaction hooks
545 # records the number of new markers for the transaction hooks
546 previous = int(transaction.hookargs.get('new_obsmarkers', '0'))
546 previous = int(transaction.hookargs.get('new_obsmarkers', '0'))
547 transaction.hookargs['new_obsmarkers'] = str(previous + len(new))
547 transaction.hookargs['new_obsmarkers'] = str(previous + len(new))
548 return len(new)
548 return len(new)
549
549
550 def mergemarkers(self, transaction, data):
550 def mergemarkers(self, transaction, data):
551 """merge a binary stream of markers inside the obsstore
551 """merge a binary stream of markers inside the obsstore
552
552
553 Returns the number of new markers added."""
553 Returns the number of new markers added."""
554 version, markers = _readmarkers(data)
554 version, markers = _readmarkers(data)
555 return self.add(transaction, markers)
555 return self.add(transaction, markers)
556
556
557 def _load(self, markers):
557 def _load(self, markers):
558 for mark in markers:
558 for mark in markers:
559 self._all.append(mark)
559 self._all.append(mark)
560 pre, sucs = mark[:2]
560 pre, sucs = mark[:2]
561 self.successors.setdefault(pre, set()).add(mark)
561 self.successors.setdefault(pre, set()).add(mark)
562 for suc in sucs:
562 for suc in sucs:
563 self.precursors.setdefault(suc, set()).add(mark)
563 self.precursors.setdefault(suc, set()).add(mark)
564 parents = mark[5]
564 parents = mark[5]
565 if parents is not None:
565 if parents is not None:
566 for p in parents:
566 for p in parents:
567 self.children.setdefault(p, set()).add(mark)
567 self.children.setdefault(p, set()).add(mark)
568 if node.nullid in self.precursors:
568 if node.nullid in self.precursors:
569 raise util.Abort(_('bad obsolescence marker detected: '
569 raise util.Abort(_('bad obsolescence marker detected: '
570 'invalid successors nullid'))
570 'invalid successors nullid'))
571 def relevantmarkers(self, nodes):
571 def relevantmarkers(self, nodes):
572 """return a set of all obsolescence markers relevant to a set of nodes.
572 """return a set of all obsolescence markers relevant to a set of nodes.
573
573
574 "relevant" to a set of nodes mean:
574 "relevant" to a set of nodes mean:
575
575
576 - marker that use this changeset as successor
576 - marker that use this changeset as successor
577 - prune marker of direct children on this changeset
577 - prune marker of direct children on this changeset
578 - recursive application of the two rules on precursors of these markers
578 - recursive application of the two rules on precursors of these markers
579
579
580 It is a set so you cannot rely on order."""
580 It is a set so you cannot rely on order."""
581
581
582 pendingnodes = set(nodes)
582 pendingnodes = set(nodes)
583 seenmarkers = set()
583 seenmarkers = set()
584 seennodes = set(pendingnodes)
584 seennodes = set(pendingnodes)
585 precursorsmarkers = self.precursors
585 precursorsmarkers = self.precursors
586 children = self.children
586 children = self.children
587 while pendingnodes:
587 while pendingnodes:
588 direct = set()
588 direct = set()
589 for current in pendingnodes:
589 for current in pendingnodes:
590 direct.update(precursorsmarkers.get(current, ()))
590 direct.update(precursorsmarkers.get(current, ()))
591 pruned = [m for m in children.get(current, ()) if not m[1]]
591 pruned = [m for m in children.get(current, ()) if not m[1]]
592 direct.update(pruned)
592 direct.update(pruned)
593 direct -= seenmarkers
593 direct -= seenmarkers
594 pendingnodes = set([m[0] for m in direct])
594 pendingnodes = set([m[0] for m in direct])
595 seenmarkers |= direct
595 seenmarkers |= direct
596 pendingnodes -= seennodes
596 pendingnodes -= seennodes
597 seennodes |= pendingnodes
597 seennodes |= pendingnodes
598 return seenmarkers
598 return seenmarkers
599
599
600 def commonversion(versions):
600 def commonversion(versions):
601 """Return the newest version listed in both versions and our local formats.
601 """Return the newest version listed in both versions and our local formats.
602
602
603 Returns None if no common version exists.
603 Returns None if no common version exists.
604 """
604 """
605 versions.sort(reverse=True)
605 versions.sort(reverse=True)
606 # search for highest version known on both side
606 # search for highest version known on both side
607 for v in versions:
607 for v in versions:
608 if v in formats:
608 if v in formats:
609 return v
609 return v
610 return None
610 return None
611
611
612 # arbitrary picked to fit into 8K limit from HTTP server
612 # arbitrary picked to fit into 8K limit from HTTP server
613 # you have to take in account:
613 # you have to take in account:
614 # - the version header
614 # - the version header
615 # - the base85 encoding
615 # - the base85 encoding
616 _maxpayload = 5300
616 _maxpayload = 5300
617
617
618 def _pushkeyescape(markers):
618 def _pushkeyescape(markers):
619 """encode markers into a dict suitable for pushkey exchange
619 """encode markers into a dict suitable for pushkey exchange
620
620
621 - binary data is base85 encoded
621 - binary data is base85 encoded
622 - split in chunks smaller than 5300 bytes"""
622 - split in chunks smaller than 5300 bytes"""
623 keys = {}
623 keys = {}
624 parts = []
624 parts = []
625 currentlen = _maxpayload * 2 # ensure we create a new part
625 currentlen = _maxpayload * 2 # ensure we create a new part
626 for marker in markers:
626 for marker in markers:
627 nextdata = _fm0encodeonemarker(marker)
627 nextdata = _fm0encodeonemarker(marker)
628 if (len(nextdata) + currentlen > _maxpayload):
628 if (len(nextdata) + currentlen > _maxpayload):
629 currentpart = []
629 currentpart = []
630 currentlen = 0
630 currentlen = 0
631 parts.append(currentpart)
631 parts.append(currentpart)
632 currentpart.append(nextdata)
632 currentpart.append(nextdata)
633 currentlen += len(nextdata)
633 currentlen += len(nextdata)
634 for idx, part in enumerate(reversed(parts)):
634 for idx, part in enumerate(reversed(parts)):
635 data = ''.join([_pack('>B', _fm0version)] + part)
635 data = ''.join([_pack('>B', _fm0version)] + part)
636 keys['dump%i' % idx] = base85.b85encode(data)
636 keys['dump%i' % idx] = base85.b85encode(data)
637 return keys
637 return keys
638
638
639 def listmarkers(repo):
639 def listmarkers(repo):
640 """List markers over pushkey"""
640 """List markers over pushkey"""
641 if not repo.obsstore:
641 if not repo.obsstore:
642 return {}
642 return {}
643 return _pushkeyescape(repo.obsstore)
643 return _pushkeyescape(repo.obsstore)
644
644
645 def pushmarker(repo, key, old, new):
645 def pushmarker(repo, key, old, new):
646 """Push markers over pushkey"""
646 """Push markers over pushkey"""
647 if not key.startswith('dump'):
647 if not key.startswith('dump'):
648 repo.ui.warn(_('unknown key: %r') % key)
648 repo.ui.warn(_('unknown key: %r') % key)
649 return 0
649 return 0
650 if old:
650 if old:
651 repo.ui.warn(_('unexpected old value for %r') % key)
651 repo.ui.warn(_('unexpected old value for %r') % key)
652 return 0
652 return 0
653 data = base85.b85decode(new)
653 data = base85.b85decode(new)
654 lock = repo.lock()
654 lock = repo.lock()
655 try:
655 try:
656 tr = repo.transaction('pushkey: obsolete markers')
656 tr = repo.transaction('pushkey: obsolete markers')
657 try:
657 try:
658 repo.obsstore.mergemarkers(tr, data)
658 repo.obsstore.mergemarkers(tr, data)
659 tr.close()
659 tr.close()
660 return 1
660 return 1
661 finally:
661 finally:
662 tr.release()
662 tr.release()
663 finally:
663 finally:
664 lock.release()
664 lock.release()
665
665
666 def getmarkers(repo, nodes=None):
666 def getmarkers(repo, nodes=None):
667 """returns markers known in a repository
667 """returns markers known in a repository
668
668
669 If <nodes> is specified, only markers "relevant" to those nodes are are
669 If <nodes> is specified, only markers "relevant" to those nodes are are
670 returned"""
670 returned"""
671 if nodes is None:
671 if nodes is None:
672 rawmarkers = repo.obsstore
672 rawmarkers = repo.obsstore
673 else:
673 else:
674 rawmarkers = repo.obsstore.relevantmarkers(nodes)
674 rawmarkers = repo.obsstore.relevantmarkers(nodes)
675
675
676 for markerdata in rawmarkers:
676 for markerdata in rawmarkers:
677 yield marker(repo, markerdata)
677 yield marker(repo, markerdata)
678
678
679 def relevantmarkers(repo, node):
679 def relevantmarkers(repo, node):
680 """all obsolete markers relevant to some revision"""
680 """all obsolete markers relevant to some revision"""
681 for markerdata in repo.obsstore.relevantmarkers(node):
681 for markerdata in repo.obsstore.relevantmarkers(node):
682 yield marker(repo, markerdata)
682 yield marker(repo, markerdata)
683
683
684
684
685 def precursormarkers(ctx):
685 def precursormarkers(ctx):
686 """obsolete marker marking this changeset as a successors"""
686 """obsolete marker marking this changeset as a successors"""
687 for data in ctx._repo.obsstore.precursors.get(ctx.node(), ()):
687 for data in ctx._repo.obsstore.precursors.get(ctx.node(), ()):
688 yield marker(ctx._repo, data)
688 yield marker(ctx._repo, data)
689
689
690 def successormarkers(ctx):
690 def successormarkers(ctx):
691 """obsolete marker making this changeset obsolete"""
691 """obsolete marker making this changeset obsolete"""
692 for data in ctx._repo.obsstore.successors.get(ctx.node(), ()):
692 for data in ctx._repo.obsstore.successors.get(ctx.node(), ()):
693 yield marker(ctx._repo, data)
693 yield marker(ctx._repo, data)
694
694
695 def allsuccessors(obsstore, nodes, ignoreflags=0):
695 def allsuccessors(obsstore, nodes, ignoreflags=0):
696 """Yield node for every successor of <nodes>.
696 """Yield node for every successor of <nodes>.
697
697
698 Some successors may be unknown locally.
698 Some successors may be unknown locally.
699
699
700 This is a linear yield unsuited to detecting split changesets. It includes
700 This is a linear yield unsuited to detecting split changesets. It includes
701 initial nodes too."""
701 initial nodes too."""
702 remaining = set(nodes)
702 remaining = set(nodes)
703 seen = set(remaining)
703 seen = set(remaining)
704 while remaining:
704 while remaining:
705 current = remaining.pop()
705 current = remaining.pop()
706 yield current
706 yield current
707 for mark in obsstore.successors.get(current, ()):
707 for mark in obsstore.successors.get(current, ()):
708 # ignore marker flagged with specified flag
708 # ignore marker flagged with specified flag
709 if mark[2] & ignoreflags:
709 if mark[2] & ignoreflags:
710 continue
710 continue
711 for suc in mark[1]:
711 for suc in mark[1]:
712 if suc not in seen:
712 if suc not in seen:
713 seen.add(suc)
713 seen.add(suc)
714 remaining.add(suc)
714 remaining.add(suc)
715
715
716 def allprecursors(obsstore, nodes, ignoreflags=0):
716 def allprecursors(obsstore, nodes, ignoreflags=0):
717 """Yield node for every precursors of <nodes>.
717 """Yield node for every precursors of <nodes>.
718
718
719 Some precursors may be unknown locally.
719 Some precursors may be unknown locally.
720
720
721 This is a linear yield unsuited to detecting folded changesets. It includes
721 This is a linear yield unsuited to detecting folded changesets. It includes
722 initial nodes too."""
722 initial nodes too."""
723
723
724 remaining = set(nodes)
724 remaining = set(nodes)
725 seen = set(remaining)
725 seen = set(remaining)
726 while remaining:
726 while remaining:
727 current = remaining.pop()
727 current = remaining.pop()
728 yield current
728 yield current
729 for mark in obsstore.precursors.get(current, ()):
729 for mark in obsstore.precursors.get(current, ()):
730 # ignore marker flagged with specified flag
730 # ignore marker flagged with specified flag
731 if mark[2] & ignoreflags:
731 if mark[2] & ignoreflags:
732 continue
732 continue
733 suc = mark[0]
733 suc = mark[0]
734 if suc not in seen:
734 if suc not in seen:
735 seen.add(suc)
735 seen.add(suc)
736 remaining.add(suc)
736 remaining.add(suc)
737
737
738 def foreground(repo, nodes):
738 def foreground(repo, nodes):
739 """return all nodes in the "foreground" of other node
739 """return all nodes in the "foreground" of other node
740
740
741 The foreground of a revision is anything reachable using parent -> children
741 The foreground of a revision is anything reachable using parent -> children
742 or precursor -> successor relation. It is very similar to "descendant" but
742 or precursor -> successor relation. It is very similar to "descendant" but
743 augmented with obsolescence information.
743 augmented with obsolescence information.
744
744
745 Beware that possible obsolescence cycle may result if complex situation.
745 Beware that possible obsolescence cycle may result if complex situation.
746 """
746 """
747 repo = repo.unfiltered()
747 repo = repo.unfiltered()
748 foreground = set(repo.set('%ln::', nodes))
748 foreground = set(repo.set('%ln::', nodes))
749 if repo.obsstore:
749 if repo.obsstore:
750 # We only need this complicated logic if there is obsolescence
750 # We only need this complicated logic if there is obsolescence
751 # XXX will probably deserve an optimised revset.
751 # XXX will probably deserve an optimised revset.
752 nm = repo.changelog.nodemap
752 nm = repo.changelog.nodemap
753 plen = -1
753 plen = -1
754 # compute the whole set of successors or descendants
754 # compute the whole set of successors or descendants
755 while len(foreground) != plen:
755 while len(foreground) != plen:
756 plen = len(foreground)
756 plen = len(foreground)
757 succs = set(c.node() for c in foreground)
757 succs = set(c.node() for c in foreground)
758 mutable = [c.node() for c in foreground if c.mutable()]
758 mutable = [c.node() for c in foreground if c.mutable()]
759 succs.update(allsuccessors(repo.obsstore, mutable))
759 succs.update(allsuccessors(repo.obsstore, mutable))
760 known = (n for n in succs if n in nm)
760 known = (n for n in succs if n in nm)
761 foreground = set(repo.set('%ln::', known))
761 foreground = set(repo.set('%ln::', known))
762 return set(c.node() for c in foreground)
762 return set(c.node() for c in foreground)
763
763
764
764
765 def successorssets(repo, initialnode, cache=None):
765 def successorssets(repo, initialnode, cache=None):
766 """Return all set of successors of initial nodes
766 """Return all set of successors of initial nodes
767
767
768 The successors set of a changeset A are a group of revisions that succeed
768 The successors set of a changeset A are a group of revisions that succeed
769 A. It succeeds A as a consistent whole, each revision being only a partial
769 A. It succeeds A as a consistent whole, each revision being only a partial
770 replacement. The successors set contains non-obsolete changesets only.
770 replacement. The successors set contains non-obsolete changesets only.
771
771
772 This function returns the full list of successor sets which is why it
772 This function returns the full list of successor sets which is why it
773 returns a list of tuples and not just a single tuple. Each tuple is a valid
773 returns a list of tuples and not just a single tuple. Each tuple is a valid
774 successors set. Not that (A,) may be a valid successors set for changeset A
774 successors set. Not that (A,) may be a valid successors set for changeset A
775 (see below).
775 (see below).
776
776
777 In most cases, a changeset A will have a single element (e.g. the changeset
777 In most cases, a changeset A will have a single element (e.g. the changeset
778 A is replaced by A') in its successors set. Though, it is also common for a
778 A is replaced by A') in its successors set. Though, it is also common for a
779 changeset A to have no elements in its successor set (e.g. the changeset
779 changeset A to have no elements in its successor set (e.g. the changeset
780 has been pruned). Therefore, the returned list of successors sets will be
780 has been pruned). Therefore, the returned list of successors sets will be
781 [(A',)] or [], respectively.
781 [(A',)] or [], respectively.
782
782
783 When a changeset A is split into A' and B', however, it will result in a
783 When a changeset A is split into A' and B', however, it will result in a
784 successors set containing more than a single element, i.e. [(A',B')].
784 successors set containing more than a single element, i.e. [(A',B')].
785 Divergent changesets will result in multiple successors sets, i.e. [(A',),
785 Divergent changesets will result in multiple successors sets, i.e. [(A',),
786 (A'')].
786 (A'')].
787
787
788 If a changeset A is not obsolete, then it will conceptually have no
788 If a changeset A is not obsolete, then it will conceptually have no
789 successors set. To distinguish this from a pruned changeset, the successor
789 successors set. To distinguish this from a pruned changeset, the successor
790 set will only contain itself, i.e. [(A,)].
790 set will only contain itself, i.e. [(A,)].
791
791
792 Finally, successors unknown locally are considered to be pruned (obsoleted
792 Finally, successors unknown locally are considered to be pruned (obsoleted
793 without any successors).
793 without any successors).
794
794
795 The optional `cache` parameter is a dictionary that may contain precomputed
795 The optional `cache` parameter is a dictionary that may contain precomputed
796 successors sets. It is meant to reuse the computation of a previous call to
796 successors sets. It is meant to reuse the computation of a previous call to
797 `successorssets` when multiple calls are made at the same time. The cache
797 `successorssets` when multiple calls are made at the same time. The cache
798 dictionary is updated in place. The caller is responsible for its live
798 dictionary is updated in place. The caller is responsible for its live
799 spawn. Code that makes multiple calls to `successorssets` *must* use this
799 spawn. Code that makes multiple calls to `successorssets` *must* use this
800 cache mechanism or suffer terrible performances.
800 cache mechanism or suffer terrible performances.
801
801
802 """
802 """
803
803
804 succmarkers = repo.obsstore.successors
804 succmarkers = repo.obsstore.successors
805
805
806 # Stack of nodes we search successors sets for
806 # Stack of nodes we search successors sets for
807 toproceed = [initialnode]
807 toproceed = [initialnode]
808 # set version of above list for fast loop detection
808 # set version of above list for fast loop detection
809 # element added to "toproceed" must be added here
809 # element added to "toproceed" must be added here
810 stackedset = set(toproceed)
810 stackedset = set(toproceed)
811 if cache is None:
811 if cache is None:
812 cache = {}
812 cache = {}
813
813
814 # This while loop is the flattened version of a recursive search for
814 # This while loop is the flattened version of a recursive search for
815 # successors sets
815 # successors sets
816 #
816 #
817 # def successorssets(x):
817 # def successorssets(x):
818 # successors = directsuccessors(x)
818 # successors = directsuccessors(x)
819 # ss = [[]]
819 # ss = [[]]
820 # for succ in directsuccessors(x):
820 # for succ in directsuccessors(x):
821 # # product as in itertools cartesian product
821 # # product as in itertools cartesian product
822 # ss = product(ss, successorssets(succ))
822 # ss = product(ss, successorssets(succ))
823 # return ss
823 # return ss
824 #
824 #
825 # But we can not use plain recursive calls here:
825 # But we can not use plain recursive calls here:
826 # - that would blow the python call stack
826 # - that would blow the python call stack
827 # - obsolescence markers may have cycles, we need to handle them.
827 # - obsolescence markers may have cycles, we need to handle them.
828 #
828 #
829 # The `toproceed` list act as our call stack. Every node we search
829 # The `toproceed` list act as our call stack. Every node we search
830 # successors set for are stacked there.
830 # successors set for are stacked there.
831 #
831 #
832 # The `stackedset` is set version of this stack used to check if a node is
832 # The `stackedset` is set version of this stack used to check if a node is
833 # already stacked. This check is used to detect cycles and prevent infinite
833 # already stacked. This check is used to detect cycles and prevent infinite
834 # loop.
834 # loop.
835 #
835 #
836 # successors set of all nodes are stored in the `cache` dictionary.
836 # successors set of all nodes are stored in the `cache` dictionary.
837 #
837 #
838 # After this while loop ends we use the cache to return the successors sets
838 # After this while loop ends we use the cache to return the successors sets
839 # for the node requested by the caller.
839 # for the node requested by the caller.
840 while toproceed:
840 while toproceed:
841 # Every iteration tries to compute the successors sets of the topmost
841 # Every iteration tries to compute the successors sets of the topmost
842 # node of the stack: CURRENT.
842 # node of the stack: CURRENT.
843 #
843 #
844 # There are four possible outcomes:
844 # There are four possible outcomes:
845 #
845 #
846 # 1) We already know the successors sets of CURRENT:
846 # 1) We already know the successors sets of CURRENT:
847 # -> mission accomplished, pop it from the stack.
847 # -> mission accomplished, pop it from the stack.
848 # 2) Node is not obsolete:
848 # 2) Node is not obsolete:
849 # -> the node is its own successors sets. Add it to the cache.
849 # -> the node is its own successors sets. Add it to the cache.
850 # 3) We do not know successors set of direct successors of CURRENT:
850 # 3) We do not know successors set of direct successors of CURRENT:
851 # -> We add those successors to the stack.
851 # -> We add those successors to the stack.
852 # 4) We know successors sets of all direct successors of CURRENT:
852 # 4) We know successors sets of all direct successors of CURRENT:
853 # -> We can compute CURRENT successors set and add it to the
853 # -> We can compute CURRENT successors set and add it to the
854 # cache.
854 # cache.
855 #
855 #
856 current = toproceed[-1]
856 current = toproceed[-1]
857 if current in cache:
857 if current in cache:
858 # case (1): We already know the successors sets
858 # case (1): We already know the successors sets
859 stackedset.remove(toproceed.pop())
859 stackedset.remove(toproceed.pop())
860 elif current not in succmarkers:
860 elif current not in succmarkers:
861 # case (2): The node is not obsolete.
861 # case (2): The node is not obsolete.
862 if current in repo:
862 if current in repo:
863 # We have a valid last successors.
863 # We have a valid last successors.
864 cache[current] = [(current,)]
864 cache[current] = [(current,)]
865 else:
865 else:
866 # Final obsolete version is unknown locally.
866 # Final obsolete version is unknown locally.
867 # Do not count that as a valid successors
867 # Do not count that as a valid successors
868 cache[current] = []
868 cache[current] = []
869 else:
869 else:
870 # cases (3) and (4)
870 # cases (3) and (4)
871 #
871 #
872 # We proceed in two phases. Phase 1 aims to distinguish case (3)
872 # We proceed in two phases. Phase 1 aims to distinguish case (3)
873 # from case (4):
873 # from case (4):
874 #
874 #
875 # For each direct successors of CURRENT, we check whether its
875 # For each direct successors of CURRENT, we check whether its
876 # successors sets are known. If they are not, we stack the
876 # successors sets are known. If they are not, we stack the
877 # unknown node and proceed to the next iteration of the while
877 # unknown node and proceed to the next iteration of the while
878 # loop. (case 3)
878 # loop. (case 3)
879 #
879 #
880 # During this step, we may detect obsolescence cycles: a node
880 # During this step, we may detect obsolescence cycles: a node
881 # with unknown successors sets but already in the call stack.
881 # with unknown successors sets but already in the call stack.
882 # In such a situation, we arbitrary set the successors sets of
882 # In such a situation, we arbitrary set the successors sets of
883 # the node to nothing (node pruned) to break the cycle.
883 # the node to nothing (node pruned) to break the cycle.
884 #
884 #
885 # If no break was encountered we proceed to phase 2.
885 # If no break was encountered we proceed to phase 2.
886 #
886 #
887 # Phase 2 computes successors sets of CURRENT (case 4); see details
887 # Phase 2 computes successors sets of CURRENT (case 4); see details
888 # in phase 2 itself.
888 # in phase 2 itself.
889 #
889 #
890 # Note the two levels of iteration in each phase.
890 # Note the two levels of iteration in each phase.
891 # - The first one handles obsolescence markers using CURRENT as
891 # - The first one handles obsolescence markers using CURRENT as
892 # precursor (successors markers of CURRENT).
892 # precursor (successors markers of CURRENT).
893 #
893 #
894 # Having multiple entry here means divergence.
894 # Having multiple entry here means divergence.
895 #
895 #
896 # - The second one handles successors defined in each marker.
896 # - The second one handles successors defined in each marker.
897 #
897 #
898 # Having none means pruned node, multiple successors means split,
898 # Having none means pruned node, multiple successors means split,
899 # single successors are standard replacement.
899 # single successors are standard replacement.
900 #
900 #
901 for mark in sorted(succmarkers[current]):
901 for mark in sorted(succmarkers[current]):
902 for suc in mark[1]:
902 for suc in mark[1]:
903 if suc not in cache:
903 if suc not in cache:
904 if suc in stackedset:
904 if suc in stackedset:
905 # cycle breaking
905 # cycle breaking
906 cache[suc] = []
906 cache[suc] = []
907 else:
907 else:
908 # case (3) If we have not computed successors sets
908 # case (3) If we have not computed successors sets
909 # of one of those successors we add it to the
909 # of one of those successors we add it to the
910 # `toproceed` stack and stop all work for this
910 # `toproceed` stack and stop all work for this
911 # iteration.
911 # iteration.
912 toproceed.append(suc)
912 toproceed.append(suc)
913 stackedset.add(suc)
913 stackedset.add(suc)
914 break
914 break
915 else:
915 else:
916 continue
916 continue
917 break
917 break
918 else:
918 else:
919 # case (4): we know all successors sets of all direct
919 # case (4): we know all successors sets of all direct
920 # successors
920 # successors
921 #
921 #
922 # Successors set contributed by each marker depends on the
922 # Successors set contributed by each marker depends on the
923 # successors sets of all its "successors" node.
923 # successors sets of all its "successors" node.
924 #
924 #
925 # Each different marker is a divergence in the obsolescence
925 # Each different marker is a divergence in the obsolescence
926 # history. It contributes successors sets distinct from other
926 # history. It contributes successors sets distinct from other
927 # markers.
927 # markers.
928 #
928 #
929 # Within a marker, a successor may have divergent successors
929 # Within a marker, a successor may have divergent successors
930 # sets. In such a case, the marker will contribute multiple
930 # sets. In such a case, the marker will contribute multiple
931 # divergent successors sets. If multiple successors have
931 # divergent successors sets. If multiple successors have
932 # divergent successors sets, a Cartesian product is used.
932 # divergent successors sets, a Cartesian product is used.
933 #
933 #
934 # At the end we post-process successors sets to remove
934 # At the end we post-process successors sets to remove
935 # duplicated entry and successors set that are strict subset of
935 # duplicated entry and successors set that are strict subset of
936 # another one.
936 # another one.
937 succssets = []
937 succssets = []
938 for mark in sorted(succmarkers[current]):
938 for mark in sorted(succmarkers[current]):
939 # successors sets contributed by this marker
939 # successors sets contributed by this marker
940 markss = [[]]
940 markss = [[]]
941 for suc in mark[1]:
941 for suc in mark[1]:
942 # cardinal product with previous successors
942 # cardinal product with previous successors
943 productresult = []
943 productresult = []
944 for prefix in markss:
944 for prefix in markss:
945 for suffix in cache[suc]:
945 for suffix in cache[suc]:
946 newss = list(prefix)
946 newss = list(prefix)
947 for part in suffix:
947 for part in suffix:
948 # do not duplicated entry in successors set
948 # do not duplicated entry in successors set
949 # first entry wins.
949 # first entry wins.
950 if part not in newss:
950 if part not in newss:
951 newss.append(part)
951 newss.append(part)
952 productresult.append(newss)
952 productresult.append(newss)
953 markss = productresult
953 markss = productresult
954 succssets.extend(markss)
954 succssets.extend(markss)
955 # remove duplicated and subset
955 # remove duplicated and subset
956 seen = []
956 seen = []
957 final = []
957 final = []
958 candidate = sorted(((set(s), s) for s in succssets if s),
958 candidate = sorted(((set(s), s) for s in succssets if s),
959 key=lambda x: len(x[1]), reverse=True)
959 key=lambda x: len(x[1]), reverse=True)
960 for setversion, listversion in candidate:
960 for setversion, listversion in candidate:
961 for seenset in seen:
961 for seenset in seen:
962 if setversion.issubset(seenset):
962 if setversion.issubset(seenset):
963 break
963 break
964 else:
964 else:
965 final.append(listversion)
965 final.append(listversion)
966 seen.append(setversion)
966 seen.append(setversion)
967 final.reverse() # put small successors set first
967 final.reverse() # put small successors set first
968 cache[current] = final
968 cache[current] = final
969 return cache[initialnode]
969 return cache[initialnode]
970
970
971 def _knownrevs(repo, nodes):
971 def _knownrevs(repo, nodes):
972 """yield revision numbers of known nodes passed in parameters
972 """yield revision numbers of known nodes passed in parameters
973
973
974 Unknown revisions are silently ignored."""
974 Unknown revisions are silently ignored."""
975 torev = repo.changelog.nodemap.get
975 torev = repo.changelog.nodemap.get
976 for n in nodes:
976 for n in nodes:
977 rev = torev(n)
977 rev = torev(n)
978 if rev is not None:
978 if rev is not None:
979 yield rev
979 yield rev
980
980
981 # mapping of 'set-name' -> <function to compute this set>
981 # mapping of 'set-name' -> <function to compute this set>
982 cachefuncs = {}
982 cachefuncs = {}
983 def cachefor(name):
983 def cachefor(name):
984 """Decorator to register a function as computing the cache for a set"""
984 """Decorator to register a function as computing the cache for a set"""
985 def decorator(func):
985 def decorator(func):
986 assert name not in cachefuncs
986 assert name not in cachefuncs
987 cachefuncs[name] = func
987 cachefuncs[name] = func
988 return func
988 return func
989 return decorator
989 return decorator
990
990
991 def getrevs(repo, name):
991 def getrevs(repo, name):
992 """Return the set of revision that belong to the <name> set
992 """Return the set of revision that belong to the <name> set
993
993
994 Such access may compute the set and cache it for future use"""
994 Such access may compute the set and cache it for future use"""
995 repo = repo.unfiltered()
995 repo = repo.unfiltered()
996 if not repo.obsstore:
996 if not repo.obsstore:
997 return frozenset()
997 return frozenset()
998 if name not in repo.obsstore.caches:
998 if name not in repo.obsstore.caches:
999 repo.obsstore.caches[name] = cachefuncs[name](repo)
999 repo.obsstore.caches[name] = cachefuncs[name](repo)
1000 return repo.obsstore.caches[name]
1000 return repo.obsstore.caches[name]
1001
1001
1002 # To be simple we need to invalidate obsolescence cache when:
1002 # To be simple we need to invalidate obsolescence cache when:
1003 #
1003 #
1004 # - new changeset is added:
1004 # - new changeset is added:
1005 # - public phase is changed
1005 # - public phase is changed
1006 # - obsolescence marker are added
1006 # - obsolescence marker are added
1007 # - strip is used a repo
1007 # - strip is used a repo
1008 def clearobscaches(repo):
1008 def clearobscaches(repo):
1009 """Remove all obsolescence related cache from a repo
1009 """Remove all obsolescence related cache from a repo
1010
1010
1011 This remove all cache in obsstore is the obsstore already exist on the
1011 This remove all cache in obsstore is the obsstore already exist on the
1012 repo.
1012 repo.
1013
1013
1014 (We could be smarter here given the exact event that trigger the cache
1014 (We could be smarter here given the exact event that trigger the cache
1015 clearing)"""
1015 clearing)"""
1016 # only clear cache is there is obsstore data in this repo
1016 # only clear cache is there is obsstore data in this repo
1017 if 'obsstore' in repo._filecache:
1017 if 'obsstore' in repo._filecache:
1018 repo.obsstore.caches.clear()
1018 repo.obsstore.caches.clear()
1019
1019
1020 @cachefor('obsolete')
1020 @cachefor('obsolete')
1021 def _computeobsoleteset(repo):
1021 def _computeobsoleteset(repo):
1022 """the set of obsolete revisions"""
1022 """the set of obsolete revisions"""
1023 obs = set()
1023 obs = set()
1024 getrev = repo.changelog.nodemap.get
1024 getrev = repo.changelog.nodemap.get
1025 getphase = repo._phasecache.phase
1025 getphase = repo._phasecache.phase
1026 for n in repo.obsstore.successors:
1026 for n in repo.obsstore.successors:
1027 rev = getrev(n)
1027 rev = getrev(n)
1028 if rev is not None and getphase(repo, rev):
1028 if rev is not None and getphase(repo, rev):
1029 obs.add(rev)
1029 obs.add(rev)
1030 return obs
1030 return obs
1031
1031
1032 @cachefor('unstable')
1032 @cachefor('unstable')
1033 def _computeunstableset(repo):
1033 def _computeunstableset(repo):
1034 """the set of non obsolete revisions with obsolete parents"""
1034 """the set of non obsolete revisions with obsolete parents"""
1035 # revset is not efficient enough here
1035 # revset is not efficient enough here
1036 # we do (obsolete()::) - obsolete() by hand
1036 # we do (obsolete()::) - obsolete() by hand
1037 obs = getrevs(repo, 'obsolete')
1037 obs = getrevs(repo, 'obsolete')
1038 if not obs:
1038 if not obs:
1039 return set()
1039 return set()
1040 cl = repo.changelog
1040 cl = repo.changelog
1041 return set(r for r in cl.descendants(obs) if r not in obs)
1041 return set(r for r in cl.descendants(obs) if r not in obs)
1042
1042
1043 @cachefor('suspended')
1043 @cachefor('suspended')
1044 def _computesuspendedset(repo):
1044 def _computesuspendedset(repo):
1045 """the set of obsolete parents with non obsolete descendants"""
1045 """the set of obsolete parents with non obsolete descendants"""
1046 suspended = repo.changelog.ancestors(getrevs(repo, 'unstable'))
1046 suspended = repo.changelog.ancestors(getrevs(repo, 'unstable'))
1047 return set(r for r in getrevs(repo, 'obsolete') if r in suspended)
1047 return set(r for r in getrevs(repo, 'obsolete') if r in suspended)
1048
1048
1049 @cachefor('extinct')
1049 @cachefor('extinct')
1050 def _computeextinctset(repo):
1050 def _computeextinctset(repo):
1051 """the set of obsolete parents without non obsolete descendants"""
1051 """the set of obsolete parents without non obsolete descendants"""
1052 return getrevs(repo, 'obsolete') - getrevs(repo, 'suspended')
1052 return getrevs(repo, 'obsolete') - getrevs(repo, 'suspended')
1053
1053
1054
1054
1055 @cachefor('bumped')
1055 @cachefor('bumped')
1056 def _computebumpedset(repo):
1056 def _computebumpedset(repo):
1057 """the set of revs trying to obsolete public revisions"""
1057 """the set of revs trying to obsolete public revisions"""
1058 bumped = set()
1058 bumped = set()
1059 # util function (avoid attribute lookup in the loop)
1059 # util function (avoid attribute lookup in the loop)
1060 phase = repo._phasecache.phase # would be faster to grab the full list
1060 phase = repo._phasecache.phase # would be faster to grab the full list
1061 public = phases.public
1061 public = phases.public
1062 cl = repo.changelog
1062 cl = repo.changelog
1063 torev = cl.nodemap.get
1063 torev = cl.nodemap.get
1064 obs = getrevs(repo, 'obsolete')
1064 obs = getrevs(repo, 'obsolete')
1065 for rev in repo:
1065 for rev in repo:
1066 # We only evaluate mutable, non-obsolete revision
1066 # We only evaluate mutable, non-obsolete revision
1067 if (public < phase(repo, rev)) and (rev not in obs):
1067 if (public < phase(repo, rev)) and (rev not in obs):
1068 node = cl.node(rev)
1068 node = cl.node(rev)
1069 # (future) A cache of precursors may worth if split is very common
1069 # (future) A cache of precursors may worth if split is very common
1070 for pnode in allprecursors(repo.obsstore, [node],
1070 for pnode in allprecursors(repo.obsstore, [node],
1071 ignoreflags=bumpedfix):
1071 ignoreflags=bumpedfix):
1072 prev = torev(pnode) # unfiltered! but so is phasecache
1072 prev = torev(pnode) # unfiltered! but so is phasecache
1073 if (prev is not None) and (phase(repo, prev) <= public):
1073 if (prev is not None) and (phase(repo, prev) <= public):
1074 # we have a public precursors
1074 # we have a public precursors
1075 bumped.add(rev)
1075 bumped.add(rev)
1076 break # Next draft!
1076 break # Next draft!
1077 return bumped
1077 return bumped
1078
1078
1079 @cachefor('divergent')
1079 @cachefor('divergent')
1080 def _computedivergentset(repo):
1080 def _computedivergentset(repo):
1081 """the set of rev that compete to be the final successors of some revision.
1081 """the set of rev that compete to be the final successors of some revision.
1082 """
1082 """
1083 divergent = set()
1083 divergent = set()
1084 obsstore = repo.obsstore
1084 obsstore = repo.obsstore
1085 newermap = {}
1085 newermap = {}
1086 for ctx in repo.set('(not public()) - obsolete()'):
1086 for ctx in repo.set('(not public()) - obsolete()'):
1087 mark = obsstore.precursors.get(ctx.node(), ())
1087 mark = obsstore.precursors.get(ctx.node(), ())
1088 toprocess = set(mark)
1088 toprocess = set(mark)
1089 while toprocess:
1089 while toprocess:
1090 prec = toprocess.pop()[0]
1090 prec = toprocess.pop()[0]
1091 if prec not in newermap:
1091 if prec not in newermap:
1092 successorssets(repo, prec, newermap)
1092 successorssets(repo, prec, newermap)
1093 newer = [n for n in newermap[prec] if n]
1093 newer = [n for n in newermap[prec] if n]
1094 if len(newer) > 1:
1094 if len(newer) > 1:
1095 divergent.add(ctx.rev())
1095 divergent.add(ctx.rev())
1096 break
1096 break
1097 toprocess.update(obsstore.precursors.get(prec, ()))
1097 toprocess.update(obsstore.precursors.get(prec, ()))
1098 return divergent
1098 return divergent
1099
1099
1100
1100
1101 def createmarkers(repo, relations, flag=0, date=None, metadata=None):
1101 def createmarkers(repo, relations, flag=0, date=None, metadata=None):
1102 """Add obsolete markers between changesets in a repo
1102 """Add obsolete markers between changesets in a repo
1103
1103
1104 <relations> must be an iterable of (<old>, (<new>, ...)[,{metadata}])
1104 <relations> must be an iterable of (<old>, (<new>, ...)[,{metadata}])
1105 tuple. `old` and `news` are changectx. metadata is an optional dictionary
1105 tuple. `old` and `news` are changectx. metadata is an optional dictionary
1106 containing metadata for this marker only. It is merged with the global
1106 containing metadata for this marker only. It is merged with the global
1107 metadata specified through the `metadata` argument of this function,
1107 metadata specified through the `metadata` argument of this function,
1108
1108
1109 Trying to obsolete a public changeset will raise an exception.
1109 Trying to obsolete a public changeset will raise an exception.
1110
1110
1111 Current user and date are used except if specified otherwise in the
1111 Current user and date are used except if specified otherwise in the
1112 metadata attribute.
1112 metadata attribute.
1113
1113
1114 This function operates within a transaction of its own, but does
1114 This function operates within a transaction of its own, but does
1115 not take any lock on the repo.
1115 not take any lock on the repo.
1116 """
1116 """
1117 # prepare metadata
1117 # prepare metadata
1118 if metadata is None:
1118 if metadata is None:
1119 metadata = {}
1119 metadata = {}
1120 if 'user' not in metadata:
1120 if 'user' not in metadata:
1121 metadata['user'] = repo.ui.username()
1121 metadata['user'] = repo.ui.username()
1122 tr = repo.transaction('add-obsolescence-marker')
1122 tr = repo.transaction('add-obsolescence-marker')
1123 try:
1123 try:
1124 for rel in relations:
1124 for rel in relations:
1125 prec = rel[0]
1125 prec = rel[0]
1126 sucs = rel[1]
1126 sucs = rel[1]
1127 localmetadata = metadata.copy()
1127 localmetadata = metadata.copy()
1128 if 2 < len(rel):
1128 if 2 < len(rel):
1129 localmetadata.update(rel[2])
1129 localmetadata.update(rel[2])
1130
1130
1131 if not prec.mutable():
1131 if not prec.mutable():
1132 raise util.Abort("cannot obsolete immutable changeset: %s"
1132 raise util.Abort("cannot obsolete immutable changeset: %s"
1133 % prec)
1133 % prec)
1134 nprec = prec.node()
1134 nprec = prec.node()
1135 nsucs = tuple(s.node() for s in sucs)
1135 nsucs = tuple(s.node() for s in sucs)
1136 npare = None
1136 npare = None
1137 if not nsucs:
1137 if not nsucs:
1138 npare = tuple(p.node() for p in prec.parents())
1138 npare = tuple(p.node() for p in prec.parents())
1139 if nprec in nsucs:
1139 if nprec in nsucs:
1140 raise util.Abort("changeset %s cannot obsolete itself" % prec)
1140 raise util.Abort("changeset %s cannot obsolete itself" % prec)
1141 repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
1141 repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
1142 date=date, metadata=localmetadata)
1142 date=date, metadata=localmetadata)
1143 repo.filteredrevcache.clear()
1143 repo.filteredrevcache.clear()
1144 tr.close()
1144 tr.close()
1145 finally:
1145 finally:
1146 tr.release()
1146 tr.release()
General Comments 0
You need to be logged in to leave comments. Login now