##// END OF EJS Templates
copies: write empty entries in changeset when also writing to filelog...
Martin von Zweigbergk -
r42871:278dcb24 default
parent child Browse files
Show More
@@ -1,621 +1,621 b''
1 # changelog.py - changelog class for mercurial
1 # changelog.py - changelog 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
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 from .i18n import _
10 from .i18n import _
11 from .node import (
11 from .node import (
12 bin,
12 bin,
13 hex,
13 hex,
14 nullid,
14 nullid,
15 )
15 )
16 from .thirdparty import (
16 from .thirdparty import (
17 attr,
17 attr,
18 )
18 )
19
19
20 from . import (
20 from . import (
21 encoding,
21 encoding,
22 error,
22 error,
23 pycompat,
23 pycompat,
24 revlog,
24 revlog,
25 util,
25 util,
26 )
26 )
27 from .utils import (
27 from .utils import (
28 dateutil,
28 dateutil,
29 stringutil,
29 stringutil,
30 )
30 )
31
31
32 _defaultextra = {'branch': 'default'}
32 _defaultextra = {'branch': 'default'}
33
33
34 def _string_escape(text):
34 def _string_escape(text):
35 """
35 """
36 >>> from .pycompat import bytechr as chr
36 >>> from .pycompat import bytechr as chr
37 >>> d = {b'nl': chr(10), b'bs': chr(92), b'cr': chr(13), b'nul': chr(0)}
37 >>> d = {b'nl': chr(10), b'bs': chr(92), b'cr': chr(13), b'nul': chr(0)}
38 >>> s = b"ab%(nl)scd%(bs)s%(bs)sn%(nul)s12ab%(cr)scd%(bs)s%(nl)s" % d
38 >>> s = b"ab%(nl)scd%(bs)s%(bs)sn%(nul)s12ab%(cr)scd%(bs)s%(nl)s" % d
39 >>> s
39 >>> s
40 'ab\\ncd\\\\\\\\n\\x0012ab\\rcd\\\\\\n'
40 'ab\\ncd\\\\\\\\n\\x0012ab\\rcd\\\\\\n'
41 >>> res = _string_escape(s)
41 >>> res = _string_escape(s)
42 >>> s == _string_unescape(res)
42 >>> s == _string_unescape(res)
43 True
43 True
44 """
44 """
45 # subset of the string_escape codec
45 # subset of the string_escape codec
46 text = text.replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '\\r')
46 text = text.replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '\\r')
47 return text.replace('\0', '\\0')
47 return text.replace('\0', '\\0')
48
48
49 def _string_unescape(text):
49 def _string_unescape(text):
50 if '\\0' in text:
50 if '\\0' in text:
51 # fix up \0 without getting into trouble with \\0
51 # fix up \0 without getting into trouble with \\0
52 text = text.replace('\\\\', '\\\\\n')
52 text = text.replace('\\\\', '\\\\\n')
53 text = text.replace('\\0', '\0')
53 text = text.replace('\\0', '\0')
54 text = text.replace('\n', '')
54 text = text.replace('\n', '')
55 return stringutil.unescapestr(text)
55 return stringutil.unescapestr(text)
56
56
57 def decodeextra(text):
57 def decodeextra(text):
58 """
58 """
59 >>> from .pycompat import bytechr as chr
59 >>> from .pycompat import bytechr as chr
60 >>> sorted(decodeextra(encodeextra({b'foo': b'bar', b'baz': chr(0) + b'2'})
60 >>> sorted(decodeextra(encodeextra({b'foo': b'bar', b'baz': chr(0) + b'2'})
61 ... ).items())
61 ... ).items())
62 [('baz', '\\x002'), ('branch', 'default'), ('foo', 'bar')]
62 [('baz', '\\x002'), ('branch', 'default'), ('foo', 'bar')]
63 >>> sorted(decodeextra(encodeextra({b'foo': b'bar',
63 >>> sorted(decodeextra(encodeextra({b'foo': b'bar',
64 ... b'baz': chr(92) + chr(0) + b'2'})
64 ... b'baz': chr(92) + chr(0) + b'2'})
65 ... ).items())
65 ... ).items())
66 [('baz', '\\\\\\x002'), ('branch', 'default'), ('foo', 'bar')]
66 [('baz', '\\\\\\x002'), ('branch', 'default'), ('foo', 'bar')]
67 """
67 """
68 extra = _defaultextra.copy()
68 extra = _defaultextra.copy()
69 for l in text.split('\0'):
69 for l in text.split('\0'):
70 if l:
70 if l:
71 k, v = _string_unescape(l).split(':', 1)
71 k, v = _string_unescape(l).split(':', 1)
72 extra[k] = v
72 extra[k] = v
73 return extra
73 return extra
74
74
75 def encodeextra(d):
75 def encodeextra(d):
76 # keys must be sorted to produce a deterministic changelog entry
76 # keys must be sorted to produce a deterministic changelog entry
77 items = [
77 items = [
78 _string_escape('%s:%s' % (k, pycompat.bytestr(d[k])))
78 _string_escape('%s:%s' % (k, pycompat.bytestr(d[k])))
79 for k in sorted(d)
79 for k in sorted(d)
80 ]
80 ]
81 return "\0".join(items)
81 return "\0".join(items)
82
82
83 def encodecopies(copies):
83 def encodecopies(copies):
84 items = [
84 items = [
85 '%s\0%s' % (k, copies[k])
85 '%s\0%s' % (k, copies[k])
86 for k in sorted(copies)
86 for k in sorted(copies)
87 ]
87 ]
88 return "\n".join(items)
88 return "\n".join(items)
89
89
90 def decodecopies(data):
90 def decodecopies(data):
91 try:
91 try:
92 copies = {}
92 copies = {}
93 for l in data.split('\n'):
93 for l in data.split('\n'):
94 k, v = l.split('\0')
94 k, v = l.split('\0')
95 copies[k] = v
95 copies[k] = v
96 return copies
96 return copies
97 except ValueError:
97 except ValueError:
98 # Perhaps someone had chosen the same key name (e.g. "p1copies") and
98 # Perhaps someone had chosen the same key name (e.g. "p1copies") and
99 # used different syntax for the value.
99 # used different syntax for the value.
100 return None
100 return None
101
101
102 def stripdesc(desc):
102 def stripdesc(desc):
103 """strip trailing whitespace and leading and trailing empty lines"""
103 """strip trailing whitespace and leading and trailing empty lines"""
104 return '\n'.join([l.rstrip() for l in desc.splitlines()]).strip('\n')
104 return '\n'.join([l.rstrip() for l in desc.splitlines()]).strip('\n')
105
105
106 class appender(object):
106 class appender(object):
107 '''the changelog index must be updated last on disk, so we use this class
107 '''the changelog index must be updated last on disk, so we use this class
108 to delay writes to it'''
108 to delay writes to it'''
109 def __init__(self, vfs, name, mode, buf):
109 def __init__(self, vfs, name, mode, buf):
110 self.data = buf
110 self.data = buf
111 fp = vfs(name, mode)
111 fp = vfs(name, mode)
112 self.fp = fp
112 self.fp = fp
113 self.offset = fp.tell()
113 self.offset = fp.tell()
114 self.size = vfs.fstat(fp).st_size
114 self.size = vfs.fstat(fp).st_size
115 self._end = self.size
115 self._end = self.size
116
116
117 def end(self):
117 def end(self):
118 return self._end
118 return self._end
119 def tell(self):
119 def tell(self):
120 return self.offset
120 return self.offset
121 def flush(self):
121 def flush(self):
122 pass
122 pass
123
123
124 @property
124 @property
125 def closed(self):
125 def closed(self):
126 return self.fp.closed
126 return self.fp.closed
127
127
128 def close(self):
128 def close(self):
129 self.fp.close()
129 self.fp.close()
130
130
131 def seek(self, offset, whence=0):
131 def seek(self, offset, whence=0):
132 '''virtual file offset spans real file and data'''
132 '''virtual file offset spans real file and data'''
133 if whence == 0:
133 if whence == 0:
134 self.offset = offset
134 self.offset = offset
135 elif whence == 1:
135 elif whence == 1:
136 self.offset += offset
136 self.offset += offset
137 elif whence == 2:
137 elif whence == 2:
138 self.offset = self.end() + offset
138 self.offset = self.end() + offset
139 if self.offset < self.size:
139 if self.offset < self.size:
140 self.fp.seek(self.offset)
140 self.fp.seek(self.offset)
141
141
142 def read(self, count=-1):
142 def read(self, count=-1):
143 '''only trick here is reads that span real file and data'''
143 '''only trick here is reads that span real file and data'''
144 ret = ""
144 ret = ""
145 if self.offset < self.size:
145 if self.offset < self.size:
146 s = self.fp.read(count)
146 s = self.fp.read(count)
147 ret = s
147 ret = s
148 self.offset += len(s)
148 self.offset += len(s)
149 if count > 0:
149 if count > 0:
150 count -= len(s)
150 count -= len(s)
151 if count != 0:
151 if count != 0:
152 doff = self.offset - self.size
152 doff = self.offset - self.size
153 self.data.insert(0, "".join(self.data))
153 self.data.insert(0, "".join(self.data))
154 del self.data[1:]
154 del self.data[1:]
155 s = self.data[0][doff:doff + count]
155 s = self.data[0][doff:doff + count]
156 self.offset += len(s)
156 self.offset += len(s)
157 ret += s
157 ret += s
158 return ret
158 return ret
159
159
160 def write(self, s):
160 def write(self, s):
161 self.data.append(bytes(s))
161 self.data.append(bytes(s))
162 self.offset += len(s)
162 self.offset += len(s)
163 self._end += len(s)
163 self._end += len(s)
164
164
165 def __enter__(self):
165 def __enter__(self):
166 self.fp.__enter__()
166 self.fp.__enter__()
167 return self
167 return self
168
168
169 def __exit__(self, *args):
169 def __exit__(self, *args):
170 return self.fp.__exit__(*args)
170 return self.fp.__exit__(*args)
171
171
172 def _divertopener(opener, target):
172 def _divertopener(opener, target):
173 """build an opener that writes in 'target.a' instead of 'target'"""
173 """build an opener that writes in 'target.a' instead of 'target'"""
174 def _divert(name, mode='r', checkambig=False):
174 def _divert(name, mode='r', checkambig=False):
175 if name != target:
175 if name != target:
176 return opener(name, mode)
176 return opener(name, mode)
177 return opener(name + ".a", mode)
177 return opener(name + ".a", mode)
178 return _divert
178 return _divert
179
179
180 def _delayopener(opener, target, buf):
180 def _delayopener(opener, target, buf):
181 """build an opener that stores chunks in 'buf' instead of 'target'"""
181 """build an opener that stores chunks in 'buf' instead of 'target'"""
182 def _delay(name, mode='r', checkambig=False):
182 def _delay(name, mode='r', checkambig=False):
183 if name != target:
183 if name != target:
184 return opener(name, mode)
184 return opener(name, mode)
185 return appender(opener, name, mode, buf)
185 return appender(opener, name, mode, buf)
186 return _delay
186 return _delay
187
187
188 @attr.s
188 @attr.s
189 class _changelogrevision(object):
189 class _changelogrevision(object):
190 # Extensions might modify _defaultextra, so let the constructor below pass
190 # Extensions might modify _defaultextra, so let the constructor below pass
191 # it in
191 # it in
192 extra = attr.ib()
192 extra = attr.ib()
193 manifest = attr.ib(default=nullid)
193 manifest = attr.ib(default=nullid)
194 user = attr.ib(default='')
194 user = attr.ib(default='')
195 date = attr.ib(default=(0, 0))
195 date = attr.ib(default=(0, 0))
196 files = attr.ib(default=attr.Factory(list))
196 files = attr.ib(default=attr.Factory(list))
197 description = attr.ib(default='')
197 description = attr.ib(default='')
198
198
199 class changelogrevision(object):
199 class changelogrevision(object):
200 """Holds results of a parsed changelog revision.
200 """Holds results of a parsed changelog revision.
201
201
202 Changelog revisions consist of multiple pieces of data, including
202 Changelog revisions consist of multiple pieces of data, including
203 the manifest node, user, and date. This object exposes a view into
203 the manifest node, user, and date. This object exposes a view into
204 the parsed object.
204 the parsed object.
205 """
205 """
206
206
207 __slots__ = (
207 __slots__ = (
208 r'_offsets',
208 r'_offsets',
209 r'_text',
209 r'_text',
210 )
210 )
211
211
212 def __new__(cls, text):
212 def __new__(cls, text):
213 if not text:
213 if not text:
214 return _changelogrevision(extra=_defaultextra)
214 return _changelogrevision(extra=_defaultextra)
215
215
216 self = super(changelogrevision, cls).__new__(cls)
216 self = super(changelogrevision, cls).__new__(cls)
217 # We could return here and implement the following as an __init__.
217 # We could return here and implement the following as an __init__.
218 # But doing it here is equivalent and saves an extra function call.
218 # But doing it here is equivalent and saves an extra function call.
219
219
220 # format used:
220 # format used:
221 # nodeid\n : manifest node in ascii
221 # nodeid\n : manifest node in ascii
222 # user\n : user, no \n or \r allowed
222 # user\n : user, no \n or \r allowed
223 # time tz extra\n : date (time is int or float, timezone is int)
223 # time tz extra\n : date (time is int or float, timezone is int)
224 # : extra is metadata, encoded and separated by '\0'
224 # : extra is metadata, encoded and separated by '\0'
225 # : older versions ignore it
225 # : older versions ignore it
226 # files\n\n : files modified by the cset, no \n or \r allowed
226 # files\n\n : files modified by the cset, no \n or \r allowed
227 # (.*) : comment (free text, ideally utf-8)
227 # (.*) : comment (free text, ideally utf-8)
228 #
228 #
229 # changelog v0 doesn't use extra
229 # changelog v0 doesn't use extra
230
230
231 nl1 = text.index('\n')
231 nl1 = text.index('\n')
232 nl2 = text.index('\n', nl1 + 1)
232 nl2 = text.index('\n', nl1 + 1)
233 nl3 = text.index('\n', nl2 + 1)
233 nl3 = text.index('\n', nl2 + 1)
234
234
235 # The list of files may be empty. Which means nl3 is the first of the
235 # The list of files may be empty. Which means nl3 is the first of the
236 # double newline that precedes the description.
236 # double newline that precedes the description.
237 if text[nl3 + 1:nl3 + 2] == '\n':
237 if text[nl3 + 1:nl3 + 2] == '\n':
238 doublenl = nl3
238 doublenl = nl3
239 else:
239 else:
240 doublenl = text.index('\n\n', nl3 + 1)
240 doublenl = text.index('\n\n', nl3 + 1)
241
241
242 self._offsets = (nl1, nl2, nl3, doublenl)
242 self._offsets = (nl1, nl2, nl3, doublenl)
243 self._text = text
243 self._text = text
244
244
245 return self
245 return self
246
246
247 @property
247 @property
248 def manifest(self):
248 def manifest(self):
249 return bin(self._text[0:self._offsets[0]])
249 return bin(self._text[0:self._offsets[0]])
250
250
251 @property
251 @property
252 def user(self):
252 def user(self):
253 off = self._offsets
253 off = self._offsets
254 return encoding.tolocal(self._text[off[0] + 1:off[1]])
254 return encoding.tolocal(self._text[off[0] + 1:off[1]])
255
255
256 @property
256 @property
257 def _rawdate(self):
257 def _rawdate(self):
258 off = self._offsets
258 off = self._offsets
259 dateextra = self._text[off[1] + 1:off[2]]
259 dateextra = self._text[off[1] + 1:off[2]]
260 return dateextra.split(' ', 2)[0:2]
260 return dateextra.split(' ', 2)[0:2]
261
261
262 @property
262 @property
263 def _rawextra(self):
263 def _rawextra(self):
264 off = self._offsets
264 off = self._offsets
265 dateextra = self._text[off[1] + 1:off[2]]
265 dateextra = self._text[off[1] + 1:off[2]]
266 fields = dateextra.split(' ', 2)
266 fields = dateextra.split(' ', 2)
267 if len(fields) != 3:
267 if len(fields) != 3:
268 return None
268 return None
269
269
270 return fields[2]
270 return fields[2]
271
271
272 @property
272 @property
273 def date(self):
273 def date(self):
274 raw = self._rawdate
274 raw = self._rawdate
275 time = float(raw[0])
275 time = float(raw[0])
276 # Various tools did silly things with the timezone.
276 # Various tools did silly things with the timezone.
277 try:
277 try:
278 timezone = int(raw[1])
278 timezone = int(raw[1])
279 except ValueError:
279 except ValueError:
280 timezone = 0
280 timezone = 0
281
281
282 return time, timezone
282 return time, timezone
283
283
284 @property
284 @property
285 def extra(self):
285 def extra(self):
286 raw = self._rawextra
286 raw = self._rawextra
287 if raw is None:
287 if raw is None:
288 return _defaultextra
288 return _defaultextra
289
289
290 return decodeextra(raw)
290 return decodeextra(raw)
291
291
292 @property
292 @property
293 def files(self):
293 def files(self):
294 off = self._offsets
294 off = self._offsets
295 if off[2] == off[3]:
295 if off[2] == off[3]:
296 return []
296 return []
297
297
298 return self._text[off[2] + 1:off[3]].split('\n')
298 return self._text[off[2] + 1:off[3]].split('\n')
299
299
300 @property
300 @property
301 def p1copies(self):
301 def p1copies(self):
302 rawcopies = self.extra.get('p1copies')
302 rawcopies = self.extra.get('p1copies')
303 return rawcopies and decodecopies(rawcopies)
303 return rawcopies and decodecopies(rawcopies)
304
304
305 @property
305 @property
306 def p2copies(self):
306 def p2copies(self):
307 rawcopies = self.extra.get('p2copies')
307 rawcopies = self.extra.get('p2copies')
308 return rawcopies and decodecopies(rawcopies)
308 return rawcopies and decodecopies(rawcopies)
309
309
310 @property
310 @property
311 def description(self):
311 def description(self):
312 return encoding.tolocal(self._text[self._offsets[3] + 2:])
312 return encoding.tolocal(self._text[self._offsets[3] + 2:])
313
313
314 class changelog(revlog.revlog):
314 class changelog(revlog.revlog):
315 def __init__(self, opener, trypending=False):
315 def __init__(self, opener, trypending=False):
316 """Load a changelog revlog using an opener.
316 """Load a changelog revlog using an opener.
317
317
318 If ``trypending`` is true, we attempt to load the index from a
318 If ``trypending`` is true, we attempt to load the index from a
319 ``00changelog.i.a`` file instead of the default ``00changelog.i``.
319 ``00changelog.i.a`` file instead of the default ``00changelog.i``.
320 The ``00changelog.i.a`` file contains index (and possibly inline
320 The ``00changelog.i.a`` file contains index (and possibly inline
321 revision) data for a transaction that hasn't been finalized yet.
321 revision) data for a transaction that hasn't been finalized yet.
322 It exists in a separate file to facilitate readers (such as
322 It exists in a separate file to facilitate readers (such as
323 hooks processes) accessing data before a transaction is finalized.
323 hooks processes) accessing data before a transaction is finalized.
324 """
324 """
325 if trypending and opener.exists('00changelog.i.a'):
325 if trypending and opener.exists('00changelog.i.a'):
326 indexfile = '00changelog.i.a'
326 indexfile = '00changelog.i.a'
327 else:
327 else:
328 indexfile = '00changelog.i'
328 indexfile = '00changelog.i'
329
329
330 datafile = '00changelog.d'
330 datafile = '00changelog.d'
331 revlog.revlog.__init__(self, opener, indexfile, datafile=datafile,
331 revlog.revlog.__init__(self, opener, indexfile, datafile=datafile,
332 checkambig=True, mmaplargeindex=True)
332 checkambig=True, mmaplargeindex=True)
333
333
334 if self._initempty and (self.version & 0xFFFF == revlog.REVLOGV1):
334 if self._initempty and (self.version & 0xFFFF == revlog.REVLOGV1):
335 # changelogs don't benefit from generaldelta.
335 # changelogs don't benefit from generaldelta.
336
336
337 self.version &= ~revlog.FLAG_GENERALDELTA
337 self.version &= ~revlog.FLAG_GENERALDELTA
338 self._generaldelta = False
338 self._generaldelta = False
339
339
340 # Delta chains for changelogs tend to be very small because entries
340 # Delta chains for changelogs tend to be very small because entries
341 # tend to be small and don't delta well with each. So disable delta
341 # tend to be small and don't delta well with each. So disable delta
342 # chains.
342 # chains.
343 self._storedeltachains = False
343 self._storedeltachains = False
344
344
345 self._realopener = opener
345 self._realopener = opener
346 self._delayed = False
346 self._delayed = False
347 self._delaybuf = None
347 self._delaybuf = None
348 self._divert = False
348 self._divert = False
349 self.filteredrevs = frozenset()
349 self.filteredrevs = frozenset()
350
350
351 def tiprev(self):
351 def tiprev(self):
352 for i in pycompat.xrange(len(self) -1, -2, -1):
352 for i in pycompat.xrange(len(self) -1, -2, -1):
353 if i not in self.filteredrevs:
353 if i not in self.filteredrevs:
354 return i
354 return i
355
355
356 def tip(self):
356 def tip(self):
357 """filtered version of revlog.tip"""
357 """filtered version of revlog.tip"""
358 return self.node(self.tiprev())
358 return self.node(self.tiprev())
359
359
360 def __contains__(self, rev):
360 def __contains__(self, rev):
361 """filtered version of revlog.__contains__"""
361 """filtered version of revlog.__contains__"""
362 return (0 <= rev < len(self)
362 return (0 <= rev < len(self)
363 and rev not in self.filteredrevs)
363 and rev not in self.filteredrevs)
364
364
365 def __iter__(self):
365 def __iter__(self):
366 """filtered version of revlog.__iter__"""
366 """filtered version of revlog.__iter__"""
367 if len(self.filteredrevs) == 0:
367 if len(self.filteredrevs) == 0:
368 return revlog.revlog.__iter__(self)
368 return revlog.revlog.__iter__(self)
369
369
370 def filterediter():
370 def filterediter():
371 for i in pycompat.xrange(len(self)):
371 for i in pycompat.xrange(len(self)):
372 if i not in self.filteredrevs:
372 if i not in self.filteredrevs:
373 yield i
373 yield i
374
374
375 return filterediter()
375 return filterediter()
376
376
377 def revs(self, start=0, stop=None):
377 def revs(self, start=0, stop=None):
378 """filtered version of revlog.revs"""
378 """filtered version of revlog.revs"""
379 for i in super(changelog, self).revs(start, stop):
379 for i in super(changelog, self).revs(start, stop):
380 if i not in self.filteredrevs:
380 if i not in self.filteredrevs:
381 yield i
381 yield i
382
382
383 def reachableroots(self, minroot, heads, roots, includepath=False):
383 def reachableroots(self, minroot, heads, roots, includepath=False):
384 return self.index.reachableroots2(minroot, heads, roots, includepath)
384 return self.index.reachableroots2(minroot, heads, roots, includepath)
385
385
386 def _checknofilteredinrevs(self, revs):
386 def _checknofilteredinrevs(self, revs):
387 """raise the appropriate error if 'revs' contains a filtered revision
387 """raise the appropriate error if 'revs' contains a filtered revision
388
388
389 This returns a version of 'revs' to be used thereafter by the caller.
389 This returns a version of 'revs' to be used thereafter by the caller.
390 In particular, if revs is an iterator, it is converted into a set.
390 In particular, if revs is an iterator, it is converted into a set.
391 """
391 """
392 safehasattr = util.safehasattr
392 safehasattr = util.safehasattr
393 if safehasattr(revs, '__next__'):
393 if safehasattr(revs, '__next__'):
394 # Note that inspect.isgenerator() is not true for iterators,
394 # Note that inspect.isgenerator() is not true for iterators,
395 revs = set(revs)
395 revs = set(revs)
396
396
397 filteredrevs = self.filteredrevs
397 filteredrevs = self.filteredrevs
398 if safehasattr(revs, 'first'): # smartset
398 if safehasattr(revs, 'first'): # smartset
399 offenders = revs & filteredrevs
399 offenders = revs & filteredrevs
400 else:
400 else:
401 offenders = filteredrevs.intersection(revs)
401 offenders = filteredrevs.intersection(revs)
402
402
403 for rev in offenders:
403 for rev in offenders:
404 raise error.FilteredIndexError(rev)
404 raise error.FilteredIndexError(rev)
405 return revs
405 return revs
406
406
407 def headrevs(self, revs=None):
407 def headrevs(self, revs=None):
408 if revs is None and self.filteredrevs:
408 if revs is None and self.filteredrevs:
409 try:
409 try:
410 return self.index.headrevsfiltered(self.filteredrevs)
410 return self.index.headrevsfiltered(self.filteredrevs)
411 # AttributeError covers non-c-extension environments and
411 # AttributeError covers non-c-extension environments and
412 # old c extensions without filter handling.
412 # old c extensions without filter handling.
413 except AttributeError:
413 except AttributeError:
414 return self._headrevs()
414 return self._headrevs()
415
415
416 if self.filteredrevs:
416 if self.filteredrevs:
417 revs = self._checknofilteredinrevs(revs)
417 revs = self._checknofilteredinrevs(revs)
418 return super(changelog, self).headrevs(revs)
418 return super(changelog, self).headrevs(revs)
419
419
420 def strip(self, *args, **kwargs):
420 def strip(self, *args, **kwargs):
421 # XXX make something better than assert
421 # XXX make something better than assert
422 # We can't expect proper strip behavior if we are filtered.
422 # We can't expect proper strip behavior if we are filtered.
423 assert not self.filteredrevs
423 assert not self.filteredrevs
424 super(changelog, self).strip(*args, **kwargs)
424 super(changelog, self).strip(*args, **kwargs)
425
425
426 def rev(self, node):
426 def rev(self, node):
427 """filtered version of revlog.rev"""
427 """filtered version of revlog.rev"""
428 r = super(changelog, self).rev(node)
428 r = super(changelog, self).rev(node)
429 if r in self.filteredrevs:
429 if r in self.filteredrevs:
430 raise error.FilteredLookupError(hex(node), self.indexfile,
430 raise error.FilteredLookupError(hex(node), self.indexfile,
431 _('filtered node'))
431 _('filtered node'))
432 return r
432 return r
433
433
434 def node(self, rev):
434 def node(self, rev):
435 """filtered version of revlog.node"""
435 """filtered version of revlog.node"""
436 if rev in self.filteredrevs:
436 if rev in self.filteredrevs:
437 raise error.FilteredIndexError(rev)
437 raise error.FilteredIndexError(rev)
438 return super(changelog, self).node(rev)
438 return super(changelog, self).node(rev)
439
439
440 def linkrev(self, rev):
440 def linkrev(self, rev):
441 """filtered version of revlog.linkrev"""
441 """filtered version of revlog.linkrev"""
442 if rev in self.filteredrevs:
442 if rev in self.filteredrevs:
443 raise error.FilteredIndexError(rev)
443 raise error.FilteredIndexError(rev)
444 return super(changelog, self).linkrev(rev)
444 return super(changelog, self).linkrev(rev)
445
445
446 def parentrevs(self, rev):
446 def parentrevs(self, rev):
447 """filtered version of revlog.parentrevs"""
447 """filtered version of revlog.parentrevs"""
448 if rev in self.filteredrevs:
448 if rev in self.filteredrevs:
449 raise error.FilteredIndexError(rev)
449 raise error.FilteredIndexError(rev)
450 return super(changelog, self).parentrevs(rev)
450 return super(changelog, self).parentrevs(rev)
451
451
452 def flags(self, rev):
452 def flags(self, rev):
453 """filtered version of revlog.flags"""
453 """filtered version of revlog.flags"""
454 if rev in self.filteredrevs:
454 if rev in self.filteredrevs:
455 raise error.FilteredIndexError(rev)
455 raise error.FilteredIndexError(rev)
456 return super(changelog, self).flags(rev)
456 return super(changelog, self).flags(rev)
457
457
458 def delayupdate(self, tr):
458 def delayupdate(self, tr):
459 "delay visibility of index updates to other readers"
459 "delay visibility of index updates to other readers"
460
460
461 if not self._delayed:
461 if not self._delayed:
462 if len(self) == 0:
462 if len(self) == 0:
463 self._divert = True
463 self._divert = True
464 if self._realopener.exists(self.indexfile + '.a'):
464 if self._realopener.exists(self.indexfile + '.a'):
465 self._realopener.unlink(self.indexfile + '.a')
465 self._realopener.unlink(self.indexfile + '.a')
466 self.opener = _divertopener(self._realopener, self.indexfile)
466 self.opener = _divertopener(self._realopener, self.indexfile)
467 else:
467 else:
468 self._delaybuf = []
468 self._delaybuf = []
469 self.opener = _delayopener(self._realopener, self.indexfile,
469 self.opener = _delayopener(self._realopener, self.indexfile,
470 self._delaybuf)
470 self._delaybuf)
471 self._delayed = True
471 self._delayed = True
472 tr.addpending('cl-%i' % id(self), self._writepending)
472 tr.addpending('cl-%i' % id(self), self._writepending)
473 tr.addfinalize('cl-%i' % id(self), self._finalize)
473 tr.addfinalize('cl-%i' % id(self), self._finalize)
474
474
475 def _finalize(self, tr):
475 def _finalize(self, tr):
476 "finalize index updates"
476 "finalize index updates"
477 self._delayed = False
477 self._delayed = False
478 self.opener = self._realopener
478 self.opener = self._realopener
479 # move redirected index data back into place
479 # move redirected index data back into place
480 if self._divert:
480 if self._divert:
481 assert not self._delaybuf
481 assert not self._delaybuf
482 tmpname = self.indexfile + ".a"
482 tmpname = self.indexfile + ".a"
483 nfile = self.opener.open(tmpname)
483 nfile = self.opener.open(tmpname)
484 nfile.close()
484 nfile.close()
485 self.opener.rename(tmpname, self.indexfile, checkambig=True)
485 self.opener.rename(tmpname, self.indexfile, checkambig=True)
486 elif self._delaybuf:
486 elif self._delaybuf:
487 fp = self.opener(self.indexfile, 'a', checkambig=True)
487 fp = self.opener(self.indexfile, 'a', checkambig=True)
488 fp.write("".join(self._delaybuf))
488 fp.write("".join(self._delaybuf))
489 fp.close()
489 fp.close()
490 self._delaybuf = None
490 self._delaybuf = None
491 self._divert = False
491 self._divert = False
492 # split when we're done
492 # split when we're done
493 self._enforceinlinesize(tr)
493 self._enforceinlinesize(tr)
494
494
495 def _writepending(self, tr):
495 def _writepending(self, tr):
496 "create a file containing the unfinalized state for pretxnchangegroup"
496 "create a file containing the unfinalized state for pretxnchangegroup"
497 if self._delaybuf:
497 if self._delaybuf:
498 # make a temporary copy of the index
498 # make a temporary copy of the index
499 fp1 = self._realopener(self.indexfile)
499 fp1 = self._realopener(self.indexfile)
500 pendingfilename = self.indexfile + ".a"
500 pendingfilename = self.indexfile + ".a"
501 # register as a temp file to ensure cleanup on failure
501 # register as a temp file to ensure cleanup on failure
502 tr.registertmp(pendingfilename)
502 tr.registertmp(pendingfilename)
503 # write existing data
503 # write existing data
504 fp2 = self._realopener(pendingfilename, "w")
504 fp2 = self._realopener(pendingfilename, "w")
505 fp2.write(fp1.read())
505 fp2.write(fp1.read())
506 # add pending data
506 # add pending data
507 fp2.write("".join(self._delaybuf))
507 fp2.write("".join(self._delaybuf))
508 fp2.close()
508 fp2.close()
509 # switch modes so finalize can simply rename
509 # switch modes so finalize can simply rename
510 self._delaybuf = None
510 self._delaybuf = None
511 self._divert = True
511 self._divert = True
512 self.opener = _divertopener(self._realopener, self.indexfile)
512 self.opener = _divertopener(self._realopener, self.indexfile)
513
513
514 if self._divert:
514 if self._divert:
515 return True
515 return True
516
516
517 return False
517 return False
518
518
519 def _enforceinlinesize(self, tr, fp=None):
519 def _enforceinlinesize(self, tr, fp=None):
520 if not self._delayed:
520 if not self._delayed:
521 revlog.revlog._enforceinlinesize(self, tr, fp)
521 revlog.revlog._enforceinlinesize(self, tr, fp)
522
522
523 def read(self, node):
523 def read(self, node):
524 """Obtain data from a parsed changelog revision.
524 """Obtain data from a parsed changelog revision.
525
525
526 Returns a 6-tuple of:
526 Returns a 6-tuple of:
527
527
528 - manifest node in binary
528 - manifest node in binary
529 - author/user as a localstr
529 - author/user as a localstr
530 - date as a 2-tuple of (time, timezone)
530 - date as a 2-tuple of (time, timezone)
531 - list of files
531 - list of files
532 - commit message as a localstr
532 - commit message as a localstr
533 - dict of extra metadata
533 - dict of extra metadata
534
534
535 Unless you need to access all fields, consider calling
535 Unless you need to access all fields, consider calling
536 ``changelogrevision`` instead, as it is faster for partial object
536 ``changelogrevision`` instead, as it is faster for partial object
537 access.
537 access.
538 """
538 """
539 c = changelogrevision(self.revision(node))
539 c = changelogrevision(self.revision(node))
540 return (
540 return (
541 c.manifest,
541 c.manifest,
542 c.user,
542 c.user,
543 c.date,
543 c.date,
544 c.files,
544 c.files,
545 c.description,
545 c.description,
546 c.extra
546 c.extra
547 )
547 )
548
548
549 def changelogrevision(self, nodeorrev):
549 def changelogrevision(self, nodeorrev):
550 """Obtain a ``changelogrevision`` for a node or revision."""
550 """Obtain a ``changelogrevision`` for a node or revision."""
551 return changelogrevision(self.revision(nodeorrev))
551 return changelogrevision(self.revision(nodeorrev))
552
552
553 def readfiles(self, node):
553 def readfiles(self, node):
554 """
554 """
555 short version of read that only returns the files modified by the cset
555 short version of read that only returns the files modified by the cset
556 """
556 """
557 text = self.revision(node)
557 text = self.revision(node)
558 if not text:
558 if not text:
559 return []
559 return []
560 last = text.index("\n\n")
560 last = text.index("\n\n")
561 l = text[:last].split('\n')
561 l = text[:last].split('\n')
562 return l[3:]
562 return l[3:]
563
563
564 def add(self, manifest, files, desc, transaction, p1, p2,
564 def add(self, manifest, files, desc, transaction, p1, p2,
565 user, date=None, extra=None, p1copies=None, p2copies=None):
565 user, date=None, extra=None, p1copies=None, p2copies=None):
566 # Convert to UTF-8 encoded bytestrings as the very first
566 # Convert to UTF-8 encoded bytestrings as the very first
567 # thing: calling any method on a localstr object will turn it
567 # thing: calling any method on a localstr object will turn it
568 # into a str object and the cached UTF-8 string is thus lost.
568 # into a str object and the cached UTF-8 string is thus lost.
569 user, desc = encoding.fromlocal(user), encoding.fromlocal(desc)
569 user, desc = encoding.fromlocal(user), encoding.fromlocal(desc)
570
570
571 user = user.strip()
571 user = user.strip()
572 # An empty username or a username with a "\n" will make the
572 # An empty username or a username with a "\n" will make the
573 # revision text contain two "\n\n" sequences -> corrupt
573 # revision text contain two "\n\n" sequences -> corrupt
574 # repository since read cannot unpack the revision.
574 # repository since read cannot unpack the revision.
575 if not user:
575 if not user:
576 raise error.StorageError(_("empty username"))
576 raise error.StorageError(_("empty username"))
577 if "\n" in user:
577 if "\n" in user:
578 raise error.StorageError(_("username %r contains a newline")
578 raise error.StorageError(_("username %r contains a newline")
579 % pycompat.bytestr(user))
579 % pycompat.bytestr(user))
580
580
581 desc = stripdesc(desc)
581 desc = stripdesc(desc)
582
582
583 if date:
583 if date:
584 parseddate = "%d %d" % dateutil.parsedate(date)
584 parseddate = "%d %d" % dateutil.parsedate(date)
585 else:
585 else:
586 parseddate = "%d %d" % dateutil.makedate()
586 parseddate = "%d %d" % dateutil.makedate()
587 if extra:
587 if extra:
588 branch = extra.get("branch")
588 branch = extra.get("branch")
589 if branch in ("default", ""):
589 if branch in ("default", ""):
590 del extra["branch"]
590 del extra["branch"]
591 elif branch in (".", "null", "tip"):
591 elif branch in (".", "null", "tip"):
592 raise error.StorageError(_('the name \'%s\' is reserved')
592 raise error.StorageError(_('the name \'%s\' is reserved')
593 % branch)
593 % branch)
594 if (p1copies or p2copies) and extra is None:
594 if (p1copies is not None or p2copies is not None) and extra is None:
595 extra = {}
595 extra = {}
596 if p1copies:
596 if p1copies is not None:
597 extra['p1copies'] = encodecopies(p1copies)
597 extra['p1copies'] = encodecopies(p1copies)
598 if p2copies:
598 if p2copies is not None:
599 extra['p2copies'] = encodecopies(p2copies)
599 extra['p2copies'] = encodecopies(p2copies)
600
600
601 if extra:
601 if extra:
602 extra = encodeextra(extra)
602 extra = encodeextra(extra)
603 parseddate = "%s %s" % (parseddate, extra)
603 parseddate = "%s %s" % (parseddate, extra)
604 l = [hex(manifest), user, parseddate] + sorted(files) + ["", desc]
604 l = [hex(manifest), user, parseddate] + sorted(files) + ["", desc]
605 text = "\n".join(l)
605 text = "\n".join(l)
606 return self.addrevision(text, transaction, len(self), p1, p2)
606 return self.addrevision(text, transaction, len(self), p1, p2)
607
607
608 def branchinfo(self, rev):
608 def branchinfo(self, rev):
609 """return the branch name and open/close state of a revision
609 """return the branch name and open/close state of a revision
610
610
611 This function exists because creating a changectx object
611 This function exists because creating a changectx object
612 just to access this is costly."""
612 just to access this is costly."""
613 extra = self.read(rev)[5]
613 extra = self.read(rev)[5]
614 return encoding.tolocal(extra.get("branch")), 'close' in extra
614 return encoding.tolocal(extra.get("branch")), 'close' in extra
615
615
616 def _nodeduplicatecallback(self, transaction, node):
616 def _nodeduplicatecallback(self, transaction, node):
617 # keep track of revisions that got "re-added", eg: unbunde of know rev.
617 # keep track of revisions that got "re-added", eg: unbunde of know rev.
618 #
618 #
619 # We track them in a list to preserve their order from the source bundle
619 # We track them in a list to preserve their order from the source bundle
620 duplicates = transaction.changes.setdefault('revduplicates', [])
620 duplicates = transaction.changes.setdefault('revduplicates', [])
621 duplicates.append(self.rev(node))
621 duplicates.append(self.rev(node))
@@ -1,3143 +1,3151 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import os
12 import os
13 import random
13 import random
14 import sys
14 import sys
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 bin,
20 bin,
21 hex,
21 hex,
22 nullid,
22 nullid,
23 nullrev,
23 nullrev,
24 short,
24 short,
25 )
25 )
26 from . import (
26 from . import (
27 bookmarks,
27 bookmarks,
28 branchmap,
28 branchmap,
29 bundle2,
29 bundle2,
30 changegroup,
30 changegroup,
31 changelog,
31 changelog,
32 color,
32 color,
33 context,
33 context,
34 dirstate,
34 dirstate,
35 dirstateguard,
35 dirstateguard,
36 discovery,
36 discovery,
37 encoding,
37 encoding,
38 error,
38 error,
39 exchange,
39 exchange,
40 extensions,
40 extensions,
41 filelog,
41 filelog,
42 hook,
42 hook,
43 lock as lockmod,
43 lock as lockmod,
44 manifest,
44 manifest,
45 match as matchmod,
45 match as matchmod,
46 merge as mergemod,
46 merge as mergemod,
47 mergeutil,
47 mergeutil,
48 namespaces,
48 namespaces,
49 narrowspec,
49 narrowspec,
50 obsolete,
50 obsolete,
51 pathutil,
51 pathutil,
52 phases,
52 phases,
53 pushkey,
53 pushkey,
54 pycompat,
54 pycompat,
55 repository,
55 repository,
56 repoview,
56 repoview,
57 revset,
57 revset,
58 revsetlang,
58 revsetlang,
59 scmutil,
59 scmutil,
60 sparse,
60 sparse,
61 store as storemod,
61 store as storemod,
62 subrepoutil,
62 subrepoutil,
63 tags as tagsmod,
63 tags as tagsmod,
64 transaction,
64 transaction,
65 txnutil,
65 txnutil,
66 util,
66 util,
67 vfs as vfsmod,
67 vfs as vfsmod,
68 )
68 )
69 from .utils import (
69 from .utils import (
70 interfaceutil,
70 interfaceutil,
71 procutil,
71 procutil,
72 stringutil,
72 stringutil,
73 )
73 )
74
74
75 from .revlogutils import (
75 from .revlogutils import (
76 constants as revlogconst,
76 constants as revlogconst,
77 )
77 )
78
78
79 release = lockmod.release
79 release = lockmod.release
80 urlerr = util.urlerr
80 urlerr = util.urlerr
81 urlreq = util.urlreq
81 urlreq = util.urlreq
82
82
83 # set of (path, vfs-location) tuples. vfs-location is:
83 # set of (path, vfs-location) tuples. vfs-location is:
84 # - 'plain for vfs relative paths
84 # - 'plain for vfs relative paths
85 # - '' for svfs relative paths
85 # - '' for svfs relative paths
86 _cachedfiles = set()
86 _cachedfiles = set()
87
87
88 class _basefilecache(scmutil.filecache):
88 class _basefilecache(scmutil.filecache):
89 """All filecache usage on repo are done for logic that should be unfiltered
89 """All filecache usage on repo are done for logic that should be unfiltered
90 """
90 """
91 def __get__(self, repo, type=None):
91 def __get__(self, repo, type=None):
92 if repo is None:
92 if repo is None:
93 return self
93 return self
94 # proxy to unfiltered __dict__ since filtered repo has no entry
94 # proxy to unfiltered __dict__ since filtered repo has no entry
95 unfi = repo.unfiltered()
95 unfi = repo.unfiltered()
96 try:
96 try:
97 return unfi.__dict__[self.sname]
97 return unfi.__dict__[self.sname]
98 except KeyError:
98 except KeyError:
99 pass
99 pass
100 return super(_basefilecache, self).__get__(unfi, type)
100 return super(_basefilecache, self).__get__(unfi, type)
101
101
102 def set(self, repo, value):
102 def set(self, repo, value):
103 return super(_basefilecache, self).set(repo.unfiltered(), value)
103 return super(_basefilecache, self).set(repo.unfiltered(), value)
104
104
105 class repofilecache(_basefilecache):
105 class repofilecache(_basefilecache):
106 """filecache for files in .hg but outside of .hg/store"""
106 """filecache for files in .hg but outside of .hg/store"""
107 def __init__(self, *paths):
107 def __init__(self, *paths):
108 super(repofilecache, self).__init__(*paths)
108 super(repofilecache, self).__init__(*paths)
109 for path in paths:
109 for path in paths:
110 _cachedfiles.add((path, 'plain'))
110 _cachedfiles.add((path, 'plain'))
111
111
112 def join(self, obj, fname):
112 def join(self, obj, fname):
113 return obj.vfs.join(fname)
113 return obj.vfs.join(fname)
114
114
115 class storecache(_basefilecache):
115 class storecache(_basefilecache):
116 """filecache for files in the store"""
116 """filecache for files in the store"""
117 def __init__(self, *paths):
117 def __init__(self, *paths):
118 super(storecache, self).__init__(*paths)
118 super(storecache, self).__init__(*paths)
119 for path in paths:
119 for path in paths:
120 _cachedfiles.add((path, ''))
120 _cachedfiles.add((path, ''))
121
121
122 def join(self, obj, fname):
122 def join(self, obj, fname):
123 return obj.sjoin(fname)
123 return obj.sjoin(fname)
124
124
125 def isfilecached(repo, name):
125 def isfilecached(repo, name):
126 """check if a repo has already cached "name" filecache-ed property
126 """check if a repo has already cached "name" filecache-ed property
127
127
128 This returns (cachedobj-or-None, iscached) tuple.
128 This returns (cachedobj-or-None, iscached) tuple.
129 """
129 """
130 cacheentry = repo.unfiltered()._filecache.get(name, None)
130 cacheentry = repo.unfiltered()._filecache.get(name, None)
131 if not cacheentry:
131 if not cacheentry:
132 return None, False
132 return None, False
133 return cacheentry.obj, True
133 return cacheentry.obj, True
134
134
135 class unfilteredpropertycache(util.propertycache):
135 class unfilteredpropertycache(util.propertycache):
136 """propertycache that apply to unfiltered repo only"""
136 """propertycache that apply to unfiltered repo only"""
137
137
138 def __get__(self, repo, type=None):
138 def __get__(self, repo, type=None):
139 unfi = repo.unfiltered()
139 unfi = repo.unfiltered()
140 if unfi is repo:
140 if unfi is repo:
141 return super(unfilteredpropertycache, self).__get__(unfi)
141 return super(unfilteredpropertycache, self).__get__(unfi)
142 return getattr(unfi, self.name)
142 return getattr(unfi, self.name)
143
143
144 class filteredpropertycache(util.propertycache):
144 class filteredpropertycache(util.propertycache):
145 """propertycache that must take filtering in account"""
145 """propertycache that must take filtering in account"""
146
146
147 def cachevalue(self, obj, value):
147 def cachevalue(self, obj, value):
148 object.__setattr__(obj, self.name, value)
148 object.__setattr__(obj, self.name, value)
149
149
150
150
151 def hasunfilteredcache(repo, name):
151 def hasunfilteredcache(repo, name):
152 """check if a repo has an unfilteredpropertycache value for <name>"""
152 """check if a repo has an unfilteredpropertycache value for <name>"""
153 return name in vars(repo.unfiltered())
153 return name in vars(repo.unfiltered())
154
154
155 def unfilteredmethod(orig):
155 def unfilteredmethod(orig):
156 """decorate method that always need to be run on unfiltered version"""
156 """decorate method that always need to be run on unfiltered version"""
157 def wrapper(repo, *args, **kwargs):
157 def wrapper(repo, *args, **kwargs):
158 return orig(repo.unfiltered(), *args, **kwargs)
158 return orig(repo.unfiltered(), *args, **kwargs)
159 return wrapper
159 return wrapper
160
160
161 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
161 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
162 'unbundle'}
162 'unbundle'}
163 legacycaps = moderncaps.union({'changegroupsubset'})
163 legacycaps = moderncaps.union({'changegroupsubset'})
164
164
165 @interfaceutil.implementer(repository.ipeercommandexecutor)
165 @interfaceutil.implementer(repository.ipeercommandexecutor)
166 class localcommandexecutor(object):
166 class localcommandexecutor(object):
167 def __init__(self, peer):
167 def __init__(self, peer):
168 self._peer = peer
168 self._peer = peer
169 self._sent = False
169 self._sent = False
170 self._closed = False
170 self._closed = False
171
171
172 def __enter__(self):
172 def __enter__(self):
173 return self
173 return self
174
174
175 def __exit__(self, exctype, excvalue, exctb):
175 def __exit__(self, exctype, excvalue, exctb):
176 self.close()
176 self.close()
177
177
178 def callcommand(self, command, args):
178 def callcommand(self, command, args):
179 if self._sent:
179 if self._sent:
180 raise error.ProgrammingError('callcommand() cannot be used after '
180 raise error.ProgrammingError('callcommand() cannot be used after '
181 'sendcommands()')
181 'sendcommands()')
182
182
183 if self._closed:
183 if self._closed:
184 raise error.ProgrammingError('callcommand() cannot be used after '
184 raise error.ProgrammingError('callcommand() cannot be used after '
185 'close()')
185 'close()')
186
186
187 # We don't need to support anything fancy. Just call the named
187 # We don't need to support anything fancy. Just call the named
188 # method on the peer and return a resolved future.
188 # method on the peer and return a resolved future.
189 fn = getattr(self._peer, pycompat.sysstr(command))
189 fn = getattr(self._peer, pycompat.sysstr(command))
190
190
191 f = pycompat.futures.Future()
191 f = pycompat.futures.Future()
192
192
193 try:
193 try:
194 result = fn(**pycompat.strkwargs(args))
194 result = fn(**pycompat.strkwargs(args))
195 except Exception:
195 except Exception:
196 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
196 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
197 else:
197 else:
198 f.set_result(result)
198 f.set_result(result)
199
199
200 return f
200 return f
201
201
202 def sendcommands(self):
202 def sendcommands(self):
203 self._sent = True
203 self._sent = True
204
204
205 def close(self):
205 def close(self):
206 self._closed = True
206 self._closed = True
207
207
208 @interfaceutil.implementer(repository.ipeercommands)
208 @interfaceutil.implementer(repository.ipeercommands)
209 class localpeer(repository.peer):
209 class localpeer(repository.peer):
210 '''peer for a local repo; reflects only the most recent API'''
210 '''peer for a local repo; reflects only the most recent API'''
211
211
212 def __init__(self, repo, caps=None):
212 def __init__(self, repo, caps=None):
213 super(localpeer, self).__init__()
213 super(localpeer, self).__init__()
214
214
215 if caps is None:
215 if caps is None:
216 caps = moderncaps.copy()
216 caps = moderncaps.copy()
217 self._repo = repo.filtered('served')
217 self._repo = repo.filtered('served')
218 self.ui = repo.ui
218 self.ui = repo.ui
219 self._caps = repo._restrictcapabilities(caps)
219 self._caps = repo._restrictcapabilities(caps)
220
220
221 # Begin of _basepeer interface.
221 # Begin of _basepeer interface.
222
222
223 def url(self):
223 def url(self):
224 return self._repo.url()
224 return self._repo.url()
225
225
226 def local(self):
226 def local(self):
227 return self._repo
227 return self._repo
228
228
229 def peer(self):
229 def peer(self):
230 return self
230 return self
231
231
232 def canpush(self):
232 def canpush(self):
233 return True
233 return True
234
234
235 def close(self):
235 def close(self):
236 self._repo.close()
236 self._repo.close()
237
237
238 # End of _basepeer interface.
238 # End of _basepeer interface.
239
239
240 # Begin of _basewirecommands interface.
240 # Begin of _basewirecommands interface.
241
241
242 def branchmap(self):
242 def branchmap(self):
243 return self._repo.branchmap()
243 return self._repo.branchmap()
244
244
245 def capabilities(self):
245 def capabilities(self):
246 return self._caps
246 return self._caps
247
247
248 def clonebundles(self):
248 def clonebundles(self):
249 return self._repo.tryread('clonebundles.manifest')
249 return self._repo.tryread('clonebundles.manifest')
250
250
251 def debugwireargs(self, one, two, three=None, four=None, five=None):
251 def debugwireargs(self, one, two, three=None, four=None, five=None):
252 """Used to test argument passing over the wire"""
252 """Used to test argument passing over the wire"""
253 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
253 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
254 pycompat.bytestr(four),
254 pycompat.bytestr(four),
255 pycompat.bytestr(five))
255 pycompat.bytestr(five))
256
256
257 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
257 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
258 **kwargs):
258 **kwargs):
259 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
259 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
260 common=common, bundlecaps=bundlecaps,
260 common=common, bundlecaps=bundlecaps,
261 **kwargs)[1]
261 **kwargs)[1]
262 cb = util.chunkbuffer(chunks)
262 cb = util.chunkbuffer(chunks)
263
263
264 if exchange.bundle2requested(bundlecaps):
264 if exchange.bundle2requested(bundlecaps):
265 # When requesting a bundle2, getbundle returns a stream to make the
265 # When requesting a bundle2, getbundle returns a stream to make the
266 # wire level function happier. We need to build a proper object
266 # wire level function happier. We need to build a proper object
267 # from it in local peer.
267 # from it in local peer.
268 return bundle2.getunbundler(self.ui, cb)
268 return bundle2.getunbundler(self.ui, cb)
269 else:
269 else:
270 return changegroup.getunbundler('01', cb, None)
270 return changegroup.getunbundler('01', cb, None)
271
271
272 def heads(self):
272 def heads(self):
273 return self._repo.heads()
273 return self._repo.heads()
274
274
275 def known(self, nodes):
275 def known(self, nodes):
276 return self._repo.known(nodes)
276 return self._repo.known(nodes)
277
277
278 def listkeys(self, namespace):
278 def listkeys(self, namespace):
279 return self._repo.listkeys(namespace)
279 return self._repo.listkeys(namespace)
280
280
281 def lookup(self, key):
281 def lookup(self, key):
282 return self._repo.lookup(key)
282 return self._repo.lookup(key)
283
283
284 def pushkey(self, namespace, key, old, new):
284 def pushkey(self, namespace, key, old, new):
285 return self._repo.pushkey(namespace, key, old, new)
285 return self._repo.pushkey(namespace, key, old, new)
286
286
287 def stream_out(self):
287 def stream_out(self):
288 raise error.Abort(_('cannot perform stream clone against local '
288 raise error.Abort(_('cannot perform stream clone against local '
289 'peer'))
289 'peer'))
290
290
291 def unbundle(self, bundle, heads, url):
291 def unbundle(self, bundle, heads, url):
292 """apply a bundle on a repo
292 """apply a bundle on a repo
293
293
294 This function handles the repo locking itself."""
294 This function handles the repo locking itself."""
295 try:
295 try:
296 try:
296 try:
297 bundle = exchange.readbundle(self.ui, bundle, None)
297 bundle = exchange.readbundle(self.ui, bundle, None)
298 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
298 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
299 if util.safehasattr(ret, 'getchunks'):
299 if util.safehasattr(ret, 'getchunks'):
300 # This is a bundle20 object, turn it into an unbundler.
300 # This is a bundle20 object, turn it into an unbundler.
301 # This little dance should be dropped eventually when the
301 # This little dance should be dropped eventually when the
302 # API is finally improved.
302 # API is finally improved.
303 stream = util.chunkbuffer(ret.getchunks())
303 stream = util.chunkbuffer(ret.getchunks())
304 ret = bundle2.getunbundler(self.ui, stream)
304 ret = bundle2.getunbundler(self.ui, stream)
305 return ret
305 return ret
306 except Exception as exc:
306 except Exception as exc:
307 # If the exception contains output salvaged from a bundle2
307 # If the exception contains output salvaged from a bundle2
308 # reply, we need to make sure it is printed before continuing
308 # reply, we need to make sure it is printed before continuing
309 # to fail. So we build a bundle2 with such output and consume
309 # to fail. So we build a bundle2 with such output and consume
310 # it directly.
310 # it directly.
311 #
311 #
312 # This is not very elegant but allows a "simple" solution for
312 # This is not very elegant but allows a "simple" solution for
313 # issue4594
313 # issue4594
314 output = getattr(exc, '_bundle2salvagedoutput', ())
314 output = getattr(exc, '_bundle2salvagedoutput', ())
315 if output:
315 if output:
316 bundler = bundle2.bundle20(self._repo.ui)
316 bundler = bundle2.bundle20(self._repo.ui)
317 for out in output:
317 for out in output:
318 bundler.addpart(out)
318 bundler.addpart(out)
319 stream = util.chunkbuffer(bundler.getchunks())
319 stream = util.chunkbuffer(bundler.getchunks())
320 b = bundle2.getunbundler(self.ui, stream)
320 b = bundle2.getunbundler(self.ui, stream)
321 bundle2.processbundle(self._repo, b)
321 bundle2.processbundle(self._repo, b)
322 raise
322 raise
323 except error.PushRaced as exc:
323 except error.PushRaced as exc:
324 raise error.ResponseError(_('push failed:'),
324 raise error.ResponseError(_('push failed:'),
325 stringutil.forcebytestr(exc))
325 stringutil.forcebytestr(exc))
326
326
327 # End of _basewirecommands interface.
327 # End of _basewirecommands interface.
328
328
329 # Begin of peer interface.
329 # Begin of peer interface.
330
330
331 def commandexecutor(self):
331 def commandexecutor(self):
332 return localcommandexecutor(self)
332 return localcommandexecutor(self)
333
333
334 # End of peer interface.
334 # End of peer interface.
335
335
336 @interfaceutil.implementer(repository.ipeerlegacycommands)
336 @interfaceutil.implementer(repository.ipeerlegacycommands)
337 class locallegacypeer(localpeer):
337 class locallegacypeer(localpeer):
338 '''peer extension which implements legacy methods too; used for tests with
338 '''peer extension which implements legacy methods too; used for tests with
339 restricted capabilities'''
339 restricted capabilities'''
340
340
341 def __init__(self, repo):
341 def __init__(self, repo):
342 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
342 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
343
343
344 # Begin of baselegacywirecommands interface.
344 # Begin of baselegacywirecommands interface.
345
345
346 def between(self, pairs):
346 def between(self, pairs):
347 return self._repo.between(pairs)
347 return self._repo.between(pairs)
348
348
349 def branches(self, nodes):
349 def branches(self, nodes):
350 return self._repo.branches(nodes)
350 return self._repo.branches(nodes)
351
351
352 def changegroup(self, nodes, source):
352 def changegroup(self, nodes, source):
353 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
353 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
354 missingheads=self._repo.heads())
354 missingheads=self._repo.heads())
355 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
355 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
356
356
357 def changegroupsubset(self, bases, heads, source):
357 def changegroupsubset(self, bases, heads, source):
358 outgoing = discovery.outgoing(self._repo, missingroots=bases,
358 outgoing = discovery.outgoing(self._repo, missingroots=bases,
359 missingheads=heads)
359 missingheads=heads)
360 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
360 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
361
361
362 # End of baselegacywirecommands interface.
362 # End of baselegacywirecommands interface.
363
363
364 # Increment the sub-version when the revlog v2 format changes to lock out old
364 # Increment the sub-version when the revlog v2 format changes to lock out old
365 # clients.
365 # clients.
366 REVLOGV2_REQUIREMENT = 'exp-revlogv2.1'
366 REVLOGV2_REQUIREMENT = 'exp-revlogv2.1'
367
367
368 # A repository with the sparserevlog feature will have delta chains that
368 # A repository with the sparserevlog feature will have delta chains that
369 # can spread over a larger span. Sparse reading cuts these large spans into
369 # can spread over a larger span. Sparse reading cuts these large spans into
370 # pieces, so that each piece isn't too big.
370 # pieces, so that each piece isn't too big.
371 # Without the sparserevlog capability, reading from the repository could use
371 # Without the sparserevlog capability, reading from the repository could use
372 # huge amounts of memory, because the whole span would be read at once,
372 # huge amounts of memory, because the whole span would be read at once,
373 # including all the intermediate revisions that aren't pertinent for the chain.
373 # including all the intermediate revisions that aren't pertinent for the chain.
374 # This is why once a repository has enabled sparse-read, it becomes required.
374 # This is why once a repository has enabled sparse-read, it becomes required.
375 SPARSEREVLOG_REQUIREMENT = 'sparserevlog'
375 SPARSEREVLOG_REQUIREMENT = 'sparserevlog'
376
376
377 # Functions receiving (ui, features) that extensions can register to impact
377 # Functions receiving (ui, features) that extensions can register to impact
378 # the ability to load repositories with custom requirements. Only
378 # the ability to load repositories with custom requirements. Only
379 # functions defined in loaded extensions are called.
379 # functions defined in loaded extensions are called.
380 #
380 #
381 # The function receives a set of requirement strings that the repository
381 # The function receives a set of requirement strings that the repository
382 # is capable of opening. Functions will typically add elements to the
382 # is capable of opening. Functions will typically add elements to the
383 # set to reflect that the extension knows how to handle that requirements.
383 # set to reflect that the extension knows how to handle that requirements.
384 featuresetupfuncs = set()
384 featuresetupfuncs = set()
385
385
386 def makelocalrepository(baseui, path, intents=None):
386 def makelocalrepository(baseui, path, intents=None):
387 """Create a local repository object.
387 """Create a local repository object.
388
388
389 Given arguments needed to construct a local repository, this function
389 Given arguments needed to construct a local repository, this function
390 performs various early repository loading functionality (such as
390 performs various early repository loading functionality (such as
391 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
391 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
392 the repository can be opened, derives a type suitable for representing
392 the repository can be opened, derives a type suitable for representing
393 that repository, and returns an instance of it.
393 that repository, and returns an instance of it.
394
394
395 The returned object conforms to the ``repository.completelocalrepository``
395 The returned object conforms to the ``repository.completelocalrepository``
396 interface.
396 interface.
397
397
398 The repository type is derived by calling a series of factory functions
398 The repository type is derived by calling a series of factory functions
399 for each aspect/interface of the final repository. These are defined by
399 for each aspect/interface of the final repository. These are defined by
400 ``REPO_INTERFACES``.
400 ``REPO_INTERFACES``.
401
401
402 Each factory function is called to produce a type implementing a specific
402 Each factory function is called to produce a type implementing a specific
403 interface. The cumulative list of returned types will be combined into a
403 interface. The cumulative list of returned types will be combined into a
404 new type and that type will be instantiated to represent the local
404 new type and that type will be instantiated to represent the local
405 repository.
405 repository.
406
406
407 The factory functions each receive various state that may be consulted
407 The factory functions each receive various state that may be consulted
408 as part of deriving a type.
408 as part of deriving a type.
409
409
410 Extensions should wrap these factory functions to customize repository type
410 Extensions should wrap these factory functions to customize repository type
411 creation. Note that an extension's wrapped function may be called even if
411 creation. Note that an extension's wrapped function may be called even if
412 that extension is not loaded for the repo being constructed. Extensions
412 that extension is not loaded for the repo being constructed. Extensions
413 should check if their ``__name__`` appears in the
413 should check if their ``__name__`` appears in the
414 ``extensionmodulenames`` set passed to the factory function and no-op if
414 ``extensionmodulenames`` set passed to the factory function and no-op if
415 not.
415 not.
416 """
416 """
417 ui = baseui.copy()
417 ui = baseui.copy()
418 # Prevent copying repo configuration.
418 # Prevent copying repo configuration.
419 ui.copy = baseui.copy
419 ui.copy = baseui.copy
420
420
421 # Working directory VFS rooted at repository root.
421 # Working directory VFS rooted at repository root.
422 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
422 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
423
423
424 # Main VFS for .hg/ directory.
424 # Main VFS for .hg/ directory.
425 hgpath = wdirvfs.join(b'.hg')
425 hgpath = wdirvfs.join(b'.hg')
426 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
426 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
427
427
428 # The .hg/ path should exist and should be a directory. All other
428 # The .hg/ path should exist and should be a directory. All other
429 # cases are errors.
429 # cases are errors.
430 if not hgvfs.isdir():
430 if not hgvfs.isdir():
431 try:
431 try:
432 hgvfs.stat()
432 hgvfs.stat()
433 except OSError as e:
433 except OSError as e:
434 if e.errno != errno.ENOENT:
434 if e.errno != errno.ENOENT:
435 raise
435 raise
436
436
437 raise error.RepoError(_(b'repository %s not found') % path)
437 raise error.RepoError(_(b'repository %s not found') % path)
438
438
439 # .hg/requires file contains a newline-delimited list of
439 # .hg/requires file contains a newline-delimited list of
440 # features/capabilities the opener (us) must have in order to use
440 # features/capabilities the opener (us) must have in order to use
441 # the repository. This file was introduced in Mercurial 0.9.2,
441 # the repository. This file was introduced in Mercurial 0.9.2,
442 # which means very old repositories may not have one. We assume
442 # which means very old repositories may not have one. We assume
443 # a missing file translates to no requirements.
443 # a missing file translates to no requirements.
444 try:
444 try:
445 requirements = set(hgvfs.read(b'requires').splitlines())
445 requirements = set(hgvfs.read(b'requires').splitlines())
446 except IOError as e:
446 except IOError as e:
447 if e.errno != errno.ENOENT:
447 if e.errno != errno.ENOENT:
448 raise
448 raise
449 requirements = set()
449 requirements = set()
450
450
451 # The .hg/hgrc file may load extensions or contain config options
451 # The .hg/hgrc file may load extensions or contain config options
452 # that influence repository construction. Attempt to load it and
452 # that influence repository construction. Attempt to load it and
453 # process any new extensions that it may have pulled in.
453 # process any new extensions that it may have pulled in.
454 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
454 if loadhgrc(ui, wdirvfs, hgvfs, requirements):
455 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
455 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
456 extensions.loadall(ui)
456 extensions.loadall(ui)
457 extensions.populateui(ui)
457 extensions.populateui(ui)
458
458
459 # Set of module names of extensions loaded for this repository.
459 # Set of module names of extensions loaded for this repository.
460 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
460 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
461
461
462 supportedrequirements = gathersupportedrequirements(ui)
462 supportedrequirements = gathersupportedrequirements(ui)
463
463
464 # We first validate the requirements are known.
464 # We first validate the requirements are known.
465 ensurerequirementsrecognized(requirements, supportedrequirements)
465 ensurerequirementsrecognized(requirements, supportedrequirements)
466
466
467 # Then we validate that the known set is reasonable to use together.
467 # Then we validate that the known set is reasonable to use together.
468 ensurerequirementscompatible(ui, requirements)
468 ensurerequirementscompatible(ui, requirements)
469
469
470 # TODO there are unhandled edge cases related to opening repositories with
470 # TODO there are unhandled edge cases related to opening repositories with
471 # shared storage. If storage is shared, we should also test for requirements
471 # shared storage. If storage is shared, we should also test for requirements
472 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
472 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
473 # that repo, as that repo may load extensions needed to open it. This is a
473 # that repo, as that repo may load extensions needed to open it. This is a
474 # bit complicated because we don't want the other hgrc to overwrite settings
474 # bit complicated because we don't want the other hgrc to overwrite settings
475 # in this hgrc.
475 # in this hgrc.
476 #
476 #
477 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
477 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
478 # file when sharing repos. But if a requirement is added after the share is
478 # file when sharing repos. But if a requirement is added after the share is
479 # performed, thereby introducing a new requirement for the opener, we may
479 # performed, thereby introducing a new requirement for the opener, we may
480 # will not see that and could encounter a run-time error interacting with
480 # will not see that and could encounter a run-time error interacting with
481 # that shared store since it has an unknown-to-us requirement.
481 # that shared store since it has an unknown-to-us requirement.
482
482
483 # At this point, we know we should be capable of opening the repository.
483 # At this point, we know we should be capable of opening the repository.
484 # Now get on with doing that.
484 # Now get on with doing that.
485
485
486 features = set()
486 features = set()
487
487
488 # The "store" part of the repository holds versioned data. How it is
488 # The "store" part of the repository holds versioned data. How it is
489 # accessed is determined by various requirements. The ``shared`` or
489 # accessed is determined by various requirements. The ``shared`` or
490 # ``relshared`` requirements indicate the store lives in the path contained
490 # ``relshared`` requirements indicate the store lives in the path contained
491 # in the ``.hg/sharedpath`` file. This is an absolute path for
491 # in the ``.hg/sharedpath`` file. This is an absolute path for
492 # ``shared`` and relative to ``.hg/`` for ``relshared``.
492 # ``shared`` and relative to ``.hg/`` for ``relshared``.
493 if b'shared' in requirements or b'relshared' in requirements:
493 if b'shared' in requirements or b'relshared' in requirements:
494 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
494 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
495 if b'relshared' in requirements:
495 if b'relshared' in requirements:
496 sharedpath = hgvfs.join(sharedpath)
496 sharedpath = hgvfs.join(sharedpath)
497
497
498 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
498 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
499
499
500 if not sharedvfs.exists():
500 if not sharedvfs.exists():
501 raise error.RepoError(_(b'.hg/sharedpath points to nonexistent '
501 raise error.RepoError(_(b'.hg/sharedpath points to nonexistent '
502 b'directory %s') % sharedvfs.base)
502 b'directory %s') % sharedvfs.base)
503
503
504 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
504 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
505
505
506 storebasepath = sharedvfs.base
506 storebasepath = sharedvfs.base
507 cachepath = sharedvfs.join(b'cache')
507 cachepath = sharedvfs.join(b'cache')
508 else:
508 else:
509 storebasepath = hgvfs.base
509 storebasepath = hgvfs.base
510 cachepath = hgvfs.join(b'cache')
510 cachepath = hgvfs.join(b'cache')
511 wcachepath = hgvfs.join(b'wcache')
511 wcachepath = hgvfs.join(b'wcache')
512
512
513
513
514 # The store has changed over time and the exact layout is dictated by
514 # The store has changed over time and the exact layout is dictated by
515 # requirements. The store interface abstracts differences across all
515 # requirements. The store interface abstracts differences across all
516 # of them.
516 # of them.
517 store = makestore(requirements, storebasepath,
517 store = makestore(requirements, storebasepath,
518 lambda base: vfsmod.vfs(base, cacheaudited=True))
518 lambda base: vfsmod.vfs(base, cacheaudited=True))
519 hgvfs.createmode = store.createmode
519 hgvfs.createmode = store.createmode
520
520
521 storevfs = store.vfs
521 storevfs = store.vfs
522 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
522 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
523
523
524 # The cache vfs is used to manage cache files.
524 # The cache vfs is used to manage cache files.
525 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
525 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
526 cachevfs.createmode = store.createmode
526 cachevfs.createmode = store.createmode
527 # The cache vfs is used to manage cache files related to the working copy
527 # The cache vfs is used to manage cache files related to the working copy
528 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
528 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
529 wcachevfs.createmode = store.createmode
529 wcachevfs.createmode = store.createmode
530
530
531 # Now resolve the type for the repository object. We do this by repeatedly
531 # Now resolve the type for the repository object. We do this by repeatedly
532 # calling a factory function to produces types for specific aspects of the
532 # calling a factory function to produces types for specific aspects of the
533 # repo's operation. The aggregate returned types are used as base classes
533 # repo's operation. The aggregate returned types are used as base classes
534 # for a dynamically-derived type, which will represent our new repository.
534 # for a dynamically-derived type, which will represent our new repository.
535
535
536 bases = []
536 bases = []
537 extrastate = {}
537 extrastate = {}
538
538
539 for iface, fn in REPO_INTERFACES:
539 for iface, fn in REPO_INTERFACES:
540 # We pass all potentially useful state to give extensions tons of
540 # We pass all potentially useful state to give extensions tons of
541 # flexibility.
541 # flexibility.
542 typ = fn()(ui=ui,
542 typ = fn()(ui=ui,
543 intents=intents,
543 intents=intents,
544 requirements=requirements,
544 requirements=requirements,
545 features=features,
545 features=features,
546 wdirvfs=wdirvfs,
546 wdirvfs=wdirvfs,
547 hgvfs=hgvfs,
547 hgvfs=hgvfs,
548 store=store,
548 store=store,
549 storevfs=storevfs,
549 storevfs=storevfs,
550 storeoptions=storevfs.options,
550 storeoptions=storevfs.options,
551 cachevfs=cachevfs,
551 cachevfs=cachevfs,
552 wcachevfs=wcachevfs,
552 wcachevfs=wcachevfs,
553 extensionmodulenames=extensionmodulenames,
553 extensionmodulenames=extensionmodulenames,
554 extrastate=extrastate,
554 extrastate=extrastate,
555 baseclasses=bases)
555 baseclasses=bases)
556
556
557 if not isinstance(typ, type):
557 if not isinstance(typ, type):
558 raise error.ProgrammingError('unable to construct type for %s' %
558 raise error.ProgrammingError('unable to construct type for %s' %
559 iface)
559 iface)
560
560
561 bases.append(typ)
561 bases.append(typ)
562
562
563 # type() allows you to use characters in type names that wouldn't be
563 # type() allows you to use characters in type names that wouldn't be
564 # recognized as Python symbols in source code. We abuse that to add
564 # recognized as Python symbols in source code. We abuse that to add
565 # rich information about our constructed repo.
565 # rich information about our constructed repo.
566 name = pycompat.sysstr(b'derivedrepo:%s<%s>' % (
566 name = pycompat.sysstr(b'derivedrepo:%s<%s>' % (
567 wdirvfs.base,
567 wdirvfs.base,
568 b','.join(sorted(requirements))))
568 b','.join(sorted(requirements))))
569
569
570 cls = type(name, tuple(bases), {})
570 cls = type(name, tuple(bases), {})
571
571
572 return cls(
572 return cls(
573 baseui=baseui,
573 baseui=baseui,
574 ui=ui,
574 ui=ui,
575 origroot=path,
575 origroot=path,
576 wdirvfs=wdirvfs,
576 wdirvfs=wdirvfs,
577 hgvfs=hgvfs,
577 hgvfs=hgvfs,
578 requirements=requirements,
578 requirements=requirements,
579 supportedrequirements=supportedrequirements,
579 supportedrequirements=supportedrequirements,
580 sharedpath=storebasepath,
580 sharedpath=storebasepath,
581 store=store,
581 store=store,
582 cachevfs=cachevfs,
582 cachevfs=cachevfs,
583 wcachevfs=wcachevfs,
583 wcachevfs=wcachevfs,
584 features=features,
584 features=features,
585 intents=intents)
585 intents=intents)
586
586
587 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
587 def loadhgrc(ui, wdirvfs, hgvfs, requirements):
588 """Load hgrc files/content into a ui instance.
588 """Load hgrc files/content into a ui instance.
589
589
590 This is called during repository opening to load any additional
590 This is called during repository opening to load any additional
591 config files or settings relevant to the current repository.
591 config files or settings relevant to the current repository.
592
592
593 Returns a bool indicating whether any additional configs were loaded.
593 Returns a bool indicating whether any additional configs were loaded.
594
594
595 Extensions should monkeypatch this function to modify how per-repo
595 Extensions should monkeypatch this function to modify how per-repo
596 configs are loaded. For example, an extension may wish to pull in
596 configs are loaded. For example, an extension may wish to pull in
597 configs from alternate files or sources.
597 configs from alternate files or sources.
598 """
598 """
599 try:
599 try:
600 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
600 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
601 return True
601 return True
602 except IOError:
602 except IOError:
603 return False
603 return False
604
604
605 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
605 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
606 """Perform additional actions after .hg/hgrc is loaded.
606 """Perform additional actions after .hg/hgrc is loaded.
607
607
608 This function is called during repository loading immediately after
608 This function is called during repository loading immediately after
609 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
609 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
610
610
611 The function can be used to validate configs, automatically add
611 The function can be used to validate configs, automatically add
612 options (including extensions) based on requirements, etc.
612 options (including extensions) based on requirements, etc.
613 """
613 """
614
614
615 # Map of requirements to list of extensions to load automatically when
615 # Map of requirements to list of extensions to load automatically when
616 # requirement is present.
616 # requirement is present.
617 autoextensions = {
617 autoextensions = {
618 b'largefiles': [b'largefiles'],
618 b'largefiles': [b'largefiles'],
619 b'lfs': [b'lfs'],
619 b'lfs': [b'lfs'],
620 }
620 }
621
621
622 for requirement, names in sorted(autoextensions.items()):
622 for requirement, names in sorted(autoextensions.items()):
623 if requirement not in requirements:
623 if requirement not in requirements:
624 continue
624 continue
625
625
626 for name in names:
626 for name in names:
627 if not ui.hasconfig(b'extensions', name):
627 if not ui.hasconfig(b'extensions', name):
628 ui.setconfig(b'extensions', name, b'', source='autoload')
628 ui.setconfig(b'extensions', name, b'', source='autoload')
629
629
630 def gathersupportedrequirements(ui):
630 def gathersupportedrequirements(ui):
631 """Determine the complete set of recognized requirements."""
631 """Determine the complete set of recognized requirements."""
632 # Start with all requirements supported by this file.
632 # Start with all requirements supported by this file.
633 supported = set(localrepository._basesupported)
633 supported = set(localrepository._basesupported)
634
634
635 # Execute ``featuresetupfuncs`` entries if they belong to an extension
635 # Execute ``featuresetupfuncs`` entries if they belong to an extension
636 # relevant to this ui instance.
636 # relevant to this ui instance.
637 modules = {m.__name__ for n, m in extensions.extensions(ui)}
637 modules = {m.__name__ for n, m in extensions.extensions(ui)}
638
638
639 for fn in featuresetupfuncs:
639 for fn in featuresetupfuncs:
640 if fn.__module__ in modules:
640 if fn.__module__ in modules:
641 fn(ui, supported)
641 fn(ui, supported)
642
642
643 # Add derived requirements from registered compression engines.
643 # Add derived requirements from registered compression engines.
644 for name in util.compengines:
644 for name in util.compengines:
645 engine = util.compengines[name]
645 engine = util.compengines[name]
646 if engine.available() and engine.revlogheader():
646 if engine.available() and engine.revlogheader():
647 supported.add(b'exp-compression-%s' % name)
647 supported.add(b'exp-compression-%s' % name)
648 if engine.name() == 'zstd':
648 if engine.name() == 'zstd':
649 supported.add(b'revlog-compression-zstd')
649 supported.add(b'revlog-compression-zstd')
650
650
651 return supported
651 return supported
652
652
653 def ensurerequirementsrecognized(requirements, supported):
653 def ensurerequirementsrecognized(requirements, supported):
654 """Validate that a set of local requirements is recognized.
654 """Validate that a set of local requirements is recognized.
655
655
656 Receives a set of requirements. Raises an ``error.RepoError`` if there
656 Receives a set of requirements. Raises an ``error.RepoError`` if there
657 exists any requirement in that set that currently loaded code doesn't
657 exists any requirement in that set that currently loaded code doesn't
658 recognize.
658 recognize.
659
659
660 Returns a set of supported requirements.
660 Returns a set of supported requirements.
661 """
661 """
662 missing = set()
662 missing = set()
663
663
664 for requirement in requirements:
664 for requirement in requirements:
665 if requirement in supported:
665 if requirement in supported:
666 continue
666 continue
667
667
668 if not requirement or not requirement[0:1].isalnum():
668 if not requirement or not requirement[0:1].isalnum():
669 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
669 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
670
670
671 missing.add(requirement)
671 missing.add(requirement)
672
672
673 if missing:
673 if missing:
674 raise error.RequirementError(
674 raise error.RequirementError(
675 _(b'repository requires features unknown to this Mercurial: %s') %
675 _(b'repository requires features unknown to this Mercurial: %s') %
676 b' '.join(sorted(missing)),
676 b' '.join(sorted(missing)),
677 hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement '
677 hint=_(b'see https://mercurial-scm.org/wiki/MissingRequirement '
678 b'for more information'))
678 b'for more information'))
679
679
680 def ensurerequirementscompatible(ui, requirements):
680 def ensurerequirementscompatible(ui, requirements):
681 """Validates that a set of recognized requirements is mutually compatible.
681 """Validates that a set of recognized requirements is mutually compatible.
682
682
683 Some requirements may not be compatible with others or require
683 Some requirements may not be compatible with others or require
684 config options that aren't enabled. This function is called during
684 config options that aren't enabled. This function is called during
685 repository opening to ensure that the set of requirements needed
685 repository opening to ensure that the set of requirements needed
686 to open a repository is sane and compatible with config options.
686 to open a repository is sane and compatible with config options.
687
687
688 Extensions can monkeypatch this function to perform additional
688 Extensions can monkeypatch this function to perform additional
689 checking.
689 checking.
690
690
691 ``error.RepoError`` should be raised on failure.
691 ``error.RepoError`` should be raised on failure.
692 """
692 """
693 if b'exp-sparse' in requirements and not sparse.enabled:
693 if b'exp-sparse' in requirements and not sparse.enabled:
694 raise error.RepoError(_(b'repository is using sparse feature but '
694 raise error.RepoError(_(b'repository is using sparse feature but '
695 b'sparse is not enabled; enable the '
695 b'sparse is not enabled; enable the '
696 b'"sparse" extensions to access'))
696 b'"sparse" extensions to access'))
697
697
698 def makestore(requirements, path, vfstype):
698 def makestore(requirements, path, vfstype):
699 """Construct a storage object for a repository."""
699 """Construct a storage object for a repository."""
700 if b'store' in requirements:
700 if b'store' in requirements:
701 if b'fncache' in requirements:
701 if b'fncache' in requirements:
702 return storemod.fncachestore(path, vfstype,
702 return storemod.fncachestore(path, vfstype,
703 b'dotencode' in requirements)
703 b'dotencode' in requirements)
704
704
705 return storemod.encodedstore(path, vfstype)
705 return storemod.encodedstore(path, vfstype)
706
706
707 return storemod.basicstore(path, vfstype)
707 return storemod.basicstore(path, vfstype)
708
708
709 def resolvestorevfsoptions(ui, requirements, features):
709 def resolvestorevfsoptions(ui, requirements, features):
710 """Resolve the options to pass to the store vfs opener.
710 """Resolve the options to pass to the store vfs opener.
711
711
712 The returned dict is used to influence behavior of the storage layer.
712 The returned dict is used to influence behavior of the storage layer.
713 """
713 """
714 options = {}
714 options = {}
715
715
716 if b'treemanifest' in requirements:
716 if b'treemanifest' in requirements:
717 options[b'treemanifest'] = True
717 options[b'treemanifest'] = True
718
718
719 # experimental config: format.manifestcachesize
719 # experimental config: format.manifestcachesize
720 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
720 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
721 if manifestcachesize is not None:
721 if manifestcachesize is not None:
722 options[b'manifestcachesize'] = manifestcachesize
722 options[b'manifestcachesize'] = manifestcachesize
723
723
724 # In the absence of another requirement superseding a revlog-related
724 # In the absence of another requirement superseding a revlog-related
725 # requirement, we have to assume the repo is using revlog version 0.
725 # requirement, we have to assume the repo is using revlog version 0.
726 # This revlog format is super old and we don't bother trying to parse
726 # This revlog format is super old and we don't bother trying to parse
727 # opener options for it because those options wouldn't do anything
727 # opener options for it because those options wouldn't do anything
728 # meaningful on such old repos.
728 # meaningful on such old repos.
729 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
729 if b'revlogv1' in requirements or REVLOGV2_REQUIREMENT in requirements:
730 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
730 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
731
731
732 return options
732 return options
733
733
734 def resolverevlogstorevfsoptions(ui, requirements, features):
734 def resolverevlogstorevfsoptions(ui, requirements, features):
735 """Resolve opener options specific to revlogs."""
735 """Resolve opener options specific to revlogs."""
736
736
737 options = {}
737 options = {}
738 options[b'flagprocessors'] = {}
738 options[b'flagprocessors'] = {}
739
739
740 if b'revlogv1' in requirements:
740 if b'revlogv1' in requirements:
741 options[b'revlogv1'] = True
741 options[b'revlogv1'] = True
742 if REVLOGV2_REQUIREMENT in requirements:
742 if REVLOGV2_REQUIREMENT in requirements:
743 options[b'revlogv2'] = True
743 options[b'revlogv2'] = True
744
744
745 if b'generaldelta' in requirements:
745 if b'generaldelta' in requirements:
746 options[b'generaldelta'] = True
746 options[b'generaldelta'] = True
747
747
748 # experimental config: format.chunkcachesize
748 # experimental config: format.chunkcachesize
749 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
749 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
750 if chunkcachesize is not None:
750 if chunkcachesize is not None:
751 options[b'chunkcachesize'] = chunkcachesize
751 options[b'chunkcachesize'] = chunkcachesize
752
752
753 deltabothparents = ui.configbool(b'storage',
753 deltabothparents = ui.configbool(b'storage',
754 b'revlog.optimize-delta-parent-choice')
754 b'revlog.optimize-delta-parent-choice')
755 options[b'deltabothparents'] = deltabothparents
755 options[b'deltabothparents'] = deltabothparents
756
756
757 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
757 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
758 lazydeltabase = False
758 lazydeltabase = False
759 if lazydelta:
759 if lazydelta:
760 lazydeltabase = ui.configbool(b'storage',
760 lazydeltabase = ui.configbool(b'storage',
761 b'revlog.reuse-external-delta-parent')
761 b'revlog.reuse-external-delta-parent')
762 if lazydeltabase is None:
762 if lazydeltabase is None:
763 lazydeltabase = not scmutil.gddeltaconfig(ui)
763 lazydeltabase = not scmutil.gddeltaconfig(ui)
764 options[b'lazydelta'] = lazydelta
764 options[b'lazydelta'] = lazydelta
765 options[b'lazydeltabase'] = lazydeltabase
765 options[b'lazydeltabase'] = lazydeltabase
766
766
767 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
767 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
768 if 0 <= chainspan:
768 if 0 <= chainspan:
769 options[b'maxdeltachainspan'] = chainspan
769 options[b'maxdeltachainspan'] = chainspan
770
770
771 mmapindexthreshold = ui.configbytes(b'experimental',
771 mmapindexthreshold = ui.configbytes(b'experimental',
772 b'mmapindexthreshold')
772 b'mmapindexthreshold')
773 if mmapindexthreshold is not None:
773 if mmapindexthreshold is not None:
774 options[b'mmapindexthreshold'] = mmapindexthreshold
774 options[b'mmapindexthreshold'] = mmapindexthreshold
775
775
776 withsparseread = ui.configbool(b'experimental', b'sparse-read')
776 withsparseread = ui.configbool(b'experimental', b'sparse-read')
777 srdensitythres = float(ui.config(b'experimental',
777 srdensitythres = float(ui.config(b'experimental',
778 b'sparse-read.density-threshold'))
778 b'sparse-read.density-threshold'))
779 srmingapsize = ui.configbytes(b'experimental',
779 srmingapsize = ui.configbytes(b'experimental',
780 b'sparse-read.min-gap-size')
780 b'sparse-read.min-gap-size')
781 options[b'with-sparse-read'] = withsparseread
781 options[b'with-sparse-read'] = withsparseread
782 options[b'sparse-read-density-threshold'] = srdensitythres
782 options[b'sparse-read-density-threshold'] = srdensitythres
783 options[b'sparse-read-min-gap-size'] = srmingapsize
783 options[b'sparse-read-min-gap-size'] = srmingapsize
784
784
785 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
785 sparserevlog = SPARSEREVLOG_REQUIREMENT in requirements
786 options[b'sparse-revlog'] = sparserevlog
786 options[b'sparse-revlog'] = sparserevlog
787 if sparserevlog:
787 if sparserevlog:
788 options[b'generaldelta'] = True
788 options[b'generaldelta'] = True
789
789
790 maxchainlen = None
790 maxchainlen = None
791 if sparserevlog:
791 if sparserevlog:
792 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
792 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
793 # experimental config: format.maxchainlen
793 # experimental config: format.maxchainlen
794 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
794 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
795 if maxchainlen is not None:
795 if maxchainlen is not None:
796 options[b'maxchainlen'] = maxchainlen
796 options[b'maxchainlen'] = maxchainlen
797
797
798 for r in requirements:
798 for r in requirements:
799 # we allow multiple compression engine requirement to co-exist because
799 # we allow multiple compression engine requirement to co-exist because
800 # strickly speaking, revlog seems to support mixed compression style.
800 # strickly speaking, revlog seems to support mixed compression style.
801 #
801 #
802 # The compression used for new entries will be "the last one"
802 # The compression used for new entries will be "the last one"
803 prefix = r.startswith
803 prefix = r.startswith
804 if prefix('revlog-compression-') or prefix('exp-compression-'):
804 if prefix('revlog-compression-') or prefix('exp-compression-'):
805 options[b'compengine'] = r.split('-', 2)[2]
805 options[b'compengine'] = r.split('-', 2)[2]
806
806
807 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
807 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
808 if options[b'zlib.level'] is not None:
808 if options[b'zlib.level'] is not None:
809 if not (0 <= options[b'zlib.level'] <= 9):
809 if not (0 <= options[b'zlib.level'] <= 9):
810 msg = _('invalid value for `storage.revlog.zlib.level` config: %d')
810 msg = _('invalid value for `storage.revlog.zlib.level` config: %d')
811 raise error.Abort(msg % options[b'zlib.level'])
811 raise error.Abort(msg % options[b'zlib.level'])
812 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
812 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
813 if options[b'zstd.level'] is not None:
813 if options[b'zstd.level'] is not None:
814 if not (0 <= options[b'zstd.level'] <= 22):
814 if not (0 <= options[b'zstd.level'] <= 22):
815 msg = _('invalid value for `storage.revlog.zstd.level` config: %d')
815 msg = _('invalid value for `storage.revlog.zstd.level` config: %d')
816 raise error.Abort(msg % options[b'zstd.level'])
816 raise error.Abort(msg % options[b'zstd.level'])
817
817
818 if repository.NARROW_REQUIREMENT in requirements:
818 if repository.NARROW_REQUIREMENT in requirements:
819 options[b'enableellipsis'] = True
819 options[b'enableellipsis'] = True
820
820
821 return options
821 return options
822
822
823 def makemain(**kwargs):
823 def makemain(**kwargs):
824 """Produce a type conforming to ``ilocalrepositorymain``."""
824 """Produce a type conforming to ``ilocalrepositorymain``."""
825 return localrepository
825 return localrepository
826
826
827 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
827 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
828 class revlogfilestorage(object):
828 class revlogfilestorage(object):
829 """File storage when using revlogs."""
829 """File storage when using revlogs."""
830
830
831 def file(self, path):
831 def file(self, path):
832 if path[0] == b'/':
832 if path[0] == b'/':
833 path = path[1:]
833 path = path[1:]
834
834
835 return filelog.filelog(self.svfs, path)
835 return filelog.filelog(self.svfs, path)
836
836
837 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
837 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
838 class revlognarrowfilestorage(object):
838 class revlognarrowfilestorage(object):
839 """File storage when using revlogs and narrow files."""
839 """File storage when using revlogs and narrow files."""
840
840
841 def file(self, path):
841 def file(self, path):
842 if path[0] == b'/':
842 if path[0] == b'/':
843 path = path[1:]
843 path = path[1:]
844
844
845 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
845 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
846
846
847 def makefilestorage(requirements, features, **kwargs):
847 def makefilestorage(requirements, features, **kwargs):
848 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
848 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
849 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
849 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
850 features.add(repository.REPO_FEATURE_STREAM_CLONE)
850 features.add(repository.REPO_FEATURE_STREAM_CLONE)
851
851
852 if repository.NARROW_REQUIREMENT in requirements:
852 if repository.NARROW_REQUIREMENT in requirements:
853 return revlognarrowfilestorage
853 return revlognarrowfilestorage
854 else:
854 else:
855 return revlogfilestorage
855 return revlogfilestorage
856
856
857 # List of repository interfaces and factory functions for them. Each
857 # List of repository interfaces and factory functions for them. Each
858 # will be called in order during ``makelocalrepository()`` to iteratively
858 # will be called in order during ``makelocalrepository()`` to iteratively
859 # derive the final type for a local repository instance. We capture the
859 # derive the final type for a local repository instance. We capture the
860 # function as a lambda so we don't hold a reference and the module-level
860 # function as a lambda so we don't hold a reference and the module-level
861 # functions can be wrapped.
861 # functions can be wrapped.
862 REPO_INTERFACES = [
862 REPO_INTERFACES = [
863 (repository.ilocalrepositorymain, lambda: makemain),
863 (repository.ilocalrepositorymain, lambda: makemain),
864 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
864 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
865 ]
865 ]
866
866
867 @interfaceutil.implementer(repository.ilocalrepositorymain)
867 @interfaceutil.implementer(repository.ilocalrepositorymain)
868 class localrepository(object):
868 class localrepository(object):
869 """Main class for representing local repositories.
869 """Main class for representing local repositories.
870
870
871 All local repositories are instances of this class.
871 All local repositories are instances of this class.
872
872
873 Constructed on its own, instances of this class are not usable as
873 Constructed on its own, instances of this class are not usable as
874 repository objects. To obtain a usable repository object, call
874 repository objects. To obtain a usable repository object, call
875 ``hg.repository()``, ``localrepo.instance()``, or
875 ``hg.repository()``, ``localrepo.instance()``, or
876 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
876 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
877 ``instance()`` adds support for creating new repositories.
877 ``instance()`` adds support for creating new repositories.
878 ``hg.repository()`` adds more extension integration, including calling
878 ``hg.repository()`` adds more extension integration, including calling
879 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
879 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
880 used.
880 used.
881 """
881 """
882
882
883 # obsolete experimental requirements:
883 # obsolete experimental requirements:
884 # - manifestv2: An experimental new manifest format that allowed
884 # - manifestv2: An experimental new manifest format that allowed
885 # for stem compression of long paths. Experiment ended up not
885 # for stem compression of long paths. Experiment ended up not
886 # being successful (repository sizes went up due to worse delta
886 # being successful (repository sizes went up due to worse delta
887 # chains), and the code was deleted in 4.6.
887 # chains), and the code was deleted in 4.6.
888 supportedformats = {
888 supportedformats = {
889 'revlogv1',
889 'revlogv1',
890 'generaldelta',
890 'generaldelta',
891 'treemanifest',
891 'treemanifest',
892 REVLOGV2_REQUIREMENT,
892 REVLOGV2_REQUIREMENT,
893 SPARSEREVLOG_REQUIREMENT,
893 SPARSEREVLOG_REQUIREMENT,
894 }
894 }
895 _basesupported = supportedformats | {
895 _basesupported = supportedformats | {
896 'store',
896 'store',
897 'fncache',
897 'fncache',
898 'shared',
898 'shared',
899 'relshared',
899 'relshared',
900 'dotencode',
900 'dotencode',
901 'exp-sparse',
901 'exp-sparse',
902 'internal-phase'
902 'internal-phase'
903 }
903 }
904
904
905 # list of prefix for file which can be written without 'wlock'
905 # list of prefix for file which can be written without 'wlock'
906 # Extensions should extend this list when needed
906 # Extensions should extend this list when needed
907 _wlockfreeprefix = {
907 _wlockfreeprefix = {
908 # We migh consider requiring 'wlock' for the next
908 # We migh consider requiring 'wlock' for the next
909 # two, but pretty much all the existing code assume
909 # two, but pretty much all the existing code assume
910 # wlock is not needed so we keep them excluded for
910 # wlock is not needed so we keep them excluded for
911 # now.
911 # now.
912 'hgrc',
912 'hgrc',
913 'requires',
913 'requires',
914 # XXX cache is a complicatged business someone
914 # XXX cache is a complicatged business someone
915 # should investigate this in depth at some point
915 # should investigate this in depth at some point
916 'cache/',
916 'cache/',
917 # XXX shouldn't be dirstate covered by the wlock?
917 # XXX shouldn't be dirstate covered by the wlock?
918 'dirstate',
918 'dirstate',
919 # XXX bisect was still a bit too messy at the time
919 # XXX bisect was still a bit too messy at the time
920 # this changeset was introduced. Someone should fix
920 # this changeset was introduced. Someone should fix
921 # the remainig bit and drop this line
921 # the remainig bit and drop this line
922 'bisect.state',
922 'bisect.state',
923 }
923 }
924
924
925 def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements,
925 def __init__(self, baseui, ui, origroot, wdirvfs, hgvfs, requirements,
926 supportedrequirements, sharedpath, store, cachevfs, wcachevfs,
926 supportedrequirements, sharedpath, store, cachevfs, wcachevfs,
927 features, intents=None):
927 features, intents=None):
928 """Create a new local repository instance.
928 """Create a new local repository instance.
929
929
930 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
930 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
931 or ``localrepo.makelocalrepository()`` for obtaining a new repository
931 or ``localrepo.makelocalrepository()`` for obtaining a new repository
932 object.
932 object.
933
933
934 Arguments:
934 Arguments:
935
935
936 baseui
936 baseui
937 ``ui.ui`` instance that ``ui`` argument was based off of.
937 ``ui.ui`` instance that ``ui`` argument was based off of.
938
938
939 ui
939 ui
940 ``ui.ui`` instance for use by the repository.
940 ``ui.ui`` instance for use by the repository.
941
941
942 origroot
942 origroot
943 ``bytes`` path to working directory root of this repository.
943 ``bytes`` path to working directory root of this repository.
944
944
945 wdirvfs
945 wdirvfs
946 ``vfs.vfs`` rooted at the working directory.
946 ``vfs.vfs`` rooted at the working directory.
947
947
948 hgvfs
948 hgvfs
949 ``vfs.vfs`` rooted at .hg/
949 ``vfs.vfs`` rooted at .hg/
950
950
951 requirements
951 requirements
952 ``set`` of bytestrings representing repository opening requirements.
952 ``set`` of bytestrings representing repository opening requirements.
953
953
954 supportedrequirements
954 supportedrequirements
955 ``set`` of bytestrings representing repository requirements that we
955 ``set`` of bytestrings representing repository requirements that we
956 know how to open. May be a supetset of ``requirements``.
956 know how to open. May be a supetset of ``requirements``.
957
957
958 sharedpath
958 sharedpath
959 ``bytes`` Defining path to storage base directory. Points to a
959 ``bytes`` Defining path to storage base directory. Points to a
960 ``.hg/`` directory somewhere.
960 ``.hg/`` directory somewhere.
961
961
962 store
962 store
963 ``store.basicstore`` (or derived) instance providing access to
963 ``store.basicstore`` (or derived) instance providing access to
964 versioned storage.
964 versioned storage.
965
965
966 cachevfs
966 cachevfs
967 ``vfs.vfs`` used for cache files.
967 ``vfs.vfs`` used for cache files.
968
968
969 wcachevfs
969 wcachevfs
970 ``vfs.vfs`` used for cache files related to the working copy.
970 ``vfs.vfs`` used for cache files related to the working copy.
971
971
972 features
972 features
973 ``set`` of bytestrings defining features/capabilities of this
973 ``set`` of bytestrings defining features/capabilities of this
974 instance.
974 instance.
975
975
976 intents
976 intents
977 ``set`` of system strings indicating what this repo will be used
977 ``set`` of system strings indicating what this repo will be used
978 for.
978 for.
979 """
979 """
980 self.baseui = baseui
980 self.baseui = baseui
981 self.ui = ui
981 self.ui = ui
982 self.origroot = origroot
982 self.origroot = origroot
983 # vfs rooted at working directory.
983 # vfs rooted at working directory.
984 self.wvfs = wdirvfs
984 self.wvfs = wdirvfs
985 self.root = wdirvfs.base
985 self.root = wdirvfs.base
986 # vfs rooted at .hg/. Used to access most non-store paths.
986 # vfs rooted at .hg/. Used to access most non-store paths.
987 self.vfs = hgvfs
987 self.vfs = hgvfs
988 self.path = hgvfs.base
988 self.path = hgvfs.base
989 self.requirements = requirements
989 self.requirements = requirements
990 self.supported = supportedrequirements
990 self.supported = supportedrequirements
991 self.sharedpath = sharedpath
991 self.sharedpath = sharedpath
992 self.store = store
992 self.store = store
993 self.cachevfs = cachevfs
993 self.cachevfs = cachevfs
994 self.wcachevfs = wcachevfs
994 self.wcachevfs = wcachevfs
995 self.features = features
995 self.features = features
996
996
997 self.filtername = None
997 self.filtername = None
998
998
999 if (self.ui.configbool('devel', 'all-warnings') or
999 if (self.ui.configbool('devel', 'all-warnings') or
1000 self.ui.configbool('devel', 'check-locks')):
1000 self.ui.configbool('devel', 'check-locks')):
1001 self.vfs.audit = self._getvfsward(self.vfs.audit)
1001 self.vfs.audit = self._getvfsward(self.vfs.audit)
1002 # A list of callback to shape the phase if no data were found.
1002 # A list of callback to shape the phase if no data were found.
1003 # Callback are in the form: func(repo, roots) --> processed root.
1003 # Callback are in the form: func(repo, roots) --> processed root.
1004 # This list it to be filled by extension during repo setup
1004 # This list it to be filled by extension during repo setup
1005 self._phasedefaults = []
1005 self._phasedefaults = []
1006
1006
1007 color.setup(self.ui)
1007 color.setup(self.ui)
1008
1008
1009 self.spath = self.store.path
1009 self.spath = self.store.path
1010 self.svfs = self.store.vfs
1010 self.svfs = self.store.vfs
1011 self.sjoin = self.store.join
1011 self.sjoin = self.store.join
1012 if (self.ui.configbool('devel', 'all-warnings') or
1012 if (self.ui.configbool('devel', 'all-warnings') or
1013 self.ui.configbool('devel', 'check-locks')):
1013 self.ui.configbool('devel', 'check-locks')):
1014 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
1014 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
1015 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1015 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1016 else: # standard vfs
1016 else: # standard vfs
1017 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1017 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1018
1018
1019 self._dirstatevalidatewarned = False
1019 self._dirstatevalidatewarned = False
1020
1020
1021 self._branchcaches = branchmap.BranchMapCache()
1021 self._branchcaches = branchmap.BranchMapCache()
1022 self._revbranchcache = None
1022 self._revbranchcache = None
1023 self._filterpats = {}
1023 self._filterpats = {}
1024 self._datafilters = {}
1024 self._datafilters = {}
1025 self._transref = self._lockref = self._wlockref = None
1025 self._transref = self._lockref = self._wlockref = None
1026
1026
1027 # A cache for various files under .hg/ that tracks file changes,
1027 # A cache for various files under .hg/ that tracks file changes,
1028 # (used by the filecache decorator)
1028 # (used by the filecache decorator)
1029 #
1029 #
1030 # Maps a property name to its util.filecacheentry
1030 # Maps a property name to its util.filecacheentry
1031 self._filecache = {}
1031 self._filecache = {}
1032
1032
1033 # hold sets of revision to be filtered
1033 # hold sets of revision to be filtered
1034 # should be cleared when something might have changed the filter value:
1034 # should be cleared when something might have changed the filter value:
1035 # - new changesets,
1035 # - new changesets,
1036 # - phase change,
1036 # - phase change,
1037 # - new obsolescence marker,
1037 # - new obsolescence marker,
1038 # - working directory parent change,
1038 # - working directory parent change,
1039 # - bookmark changes
1039 # - bookmark changes
1040 self.filteredrevcache = {}
1040 self.filteredrevcache = {}
1041
1041
1042 # post-dirstate-status hooks
1042 # post-dirstate-status hooks
1043 self._postdsstatus = []
1043 self._postdsstatus = []
1044
1044
1045 # generic mapping between names and nodes
1045 # generic mapping between names and nodes
1046 self.names = namespaces.namespaces()
1046 self.names = namespaces.namespaces()
1047
1047
1048 # Key to signature value.
1048 # Key to signature value.
1049 self._sparsesignaturecache = {}
1049 self._sparsesignaturecache = {}
1050 # Signature to cached matcher instance.
1050 # Signature to cached matcher instance.
1051 self._sparsematchercache = {}
1051 self._sparsematchercache = {}
1052
1052
1053 self._extrafilterid = repoview.extrafilter(ui)
1053 self._extrafilterid = repoview.extrafilter(ui)
1054
1054
1055 def _getvfsward(self, origfunc):
1055 def _getvfsward(self, origfunc):
1056 """build a ward for self.vfs"""
1056 """build a ward for self.vfs"""
1057 rref = weakref.ref(self)
1057 rref = weakref.ref(self)
1058 def checkvfs(path, mode=None):
1058 def checkvfs(path, mode=None):
1059 ret = origfunc(path, mode=mode)
1059 ret = origfunc(path, mode=mode)
1060 repo = rref()
1060 repo = rref()
1061 if (repo is None
1061 if (repo is None
1062 or not util.safehasattr(repo, '_wlockref')
1062 or not util.safehasattr(repo, '_wlockref')
1063 or not util.safehasattr(repo, '_lockref')):
1063 or not util.safehasattr(repo, '_lockref')):
1064 return
1064 return
1065 if mode in (None, 'r', 'rb'):
1065 if mode in (None, 'r', 'rb'):
1066 return
1066 return
1067 if path.startswith(repo.path):
1067 if path.startswith(repo.path):
1068 # truncate name relative to the repository (.hg)
1068 # truncate name relative to the repository (.hg)
1069 path = path[len(repo.path) + 1:]
1069 path = path[len(repo.path) + 1:]
1070 if path.startswith('cache/'):
1070 if path.startswith('cache/'):
1071 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
1071 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
1072 repo.ui.develwarn(msg % path, stacklevel=3, config="cache-vfs")
1072 repo.ui.develwarn(msg % path, stacklevel=3, config="cache-vfs")
1073 if path.startswith('journal.') or path.startswith('undo.'):
1073 if path.startswith('journal.') or path.startswith('undo.'):
1074 # journal is covered by 'lock'
1074 # journal is covered by 'lock'
1075 if repo._currentlock(repo._lockref) is None:
1075 if repo._currentlock(repo._lockref) is None:
1076 repo.ui.develwarn('write with no lock: "%s"' % path,
1076 repo.ui.develwarn('write with no lock: "%s"' % path,
1077 stacklevel=3, config='check-locks')
1077 stacklevel=3, config='check-locks')
1078 elif repo._currentlock(repo._wlockref) is None:
1078 elif repo._currentlock(repo._wlockref) is None:
1079 # rest of vfs files are covered by 'wlock'
1079 # rest of vfs files are covered by 'wlock'
1080 #
1080 #
1081 # exclude special files
1081 # exclude special files
1082 for prefix in self._wlockfreeprefix:
1082 for prefix in self._wlockfreeprefix:
1083 if path.startswith(prefix):
1083 if path.startswith(prefix):
1084 return
1084 return
1085 repo.ui.develwarn('write with no wlock: "%s"' % path,
1085 repo.ui.develwarn('write with no wlock: "%s"' % path,
1086 stacklevel=3, config='check-locks')
1086 stacklevel=3, config='check-locks')
1087 return ret
1087 return ret
1088 return checkvfs
1088 return checkvfs
1089
1089
1090 def _getsvfsward(self, origfunc):
1090 def _getsvfsward(self, origfunc):
1091 """build a ward for self.svfs"""
1091 """build a ward for self.svfs"""
1092 rref = weakref.ref(self)
1092 rref = weakref.ref(self)
1093 def checksvfs(path, mode=None):
1093 def checksvfs(path, mode=None):
1094 ret = origfunc(path, mode=mode)
1094 ret = origfunc(path, mode=mode)
1095 repo = rref()
1095 repo = rref()
1096 if repo is None or not util.safehasattr(repo, '_lockref'):
1096 if repo is None or not util.safehasattr(repo, '_lockref'):
1097 return
1097 return
1098 if mode in (None, 'r', 'rb'):
1098 if mode in (None, 'r', 'rb'):
1099 return
1099 return
1100 if path.startswith(repo.sharedpath):
1100 if path.startswith(repo.sharedpath):
1101 # truncate name relative to the repository (.hg)
1101 # truncate name relative to the repository (.hg)
1102 path = path[len(repo.sharedpath) + 1:]
1102 path = path[len(repo.sharedpath) + 1:]
1103 if repo._currentlock(repo._lockref) is None:
1103 if repo._currentlock(repo._lockref) is None:
1104 repo.ui.develwarn('write with no lock: "%s"' % path,
1104 repo.ui.develwarn('write with no lock: "%s"' % path,
1105 stacklevel=4)
1105 stacklevel=4)
1106 return ret
1106 return ret
1107 return checksvfs
1107 return checksvfs
1108
1108
1109 def close(self):
1109 def close(self):
1110 self._writecaches()
1110 self._writecaches()
1111
1111
1112 def _writecaches(self):
1112 def _writecaches(self):
1113 if self._revbranchcache:
1113 if self._revbranchcache:
1114 self._revbranchcache.write()
1114 self._revbranchcache.write()
1115
1115
1116 def _restrictcapabilities(self, caps):
1116 def _restrictcapabilities(self, caps):
1117 if self.ui.configbool('experimental', 'bundle2-advertise'):
1117 if self.ui.configbool('experimental', 'bundle2-advertise'):
1118 caps = set(caps)
1118 caps = set(caps)
1119 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
1119 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
1120 role='client'))
1120 role='client'))
1121 caps.add('bundle2=' + urlreq.quote(capsblob))
1121 caps.add('bundle2=' + urlreq.quote(capsblob))
1122 return caps
1122 return caps
1123
1123
1124 def _writerequirements(self):
1124 def _writerequirements(self):
1125 scmutil.writerequires(self.vfs, self.requirements)
1125 scmutil.writerequires(self.vfs, self.requirements)
1126
1126
1127 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1127 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1128 # self -> auditor -> self._checknested -> self
1128 # self -> auditor -> self._checknested -> self
1129
1129
1130 @property
1130 @property
1131 def auditor(self):
1131 def auditor(self):
1132 # This is only used by context.workingctx.match in order to
1132 # This is only used by context.workingctx.match in order to
1133 # detect files in subrepos.
1133 # detect files in subrepos.
1134 return pathutil.pathauditor(self.root, callback=self._checknested)
1134 return pathutil.pathauditor(self.root, callback=self._checknested)
1135
1135
1136 @property
1136 @property
1137 def nofsauditor(self):
1137 def nofsauditor(self):
1138 # This is only used by context.basectx.match in order to detect
1138 # This is only used by context.basectx.match in order to detect
1139 # files in subrepos.
1139 # files in subrepos.
1140 return pathutil.pathauditor(self.root, callback=self._checknested,
1140 return pathutil.pathauditor(self.root, callback=self._checknested,
1141 realfs=False, cached=True)
1141 realfs=False, cached=True)
1142
1142
1143 def _checknested(self, path):
1143 def _checknested(self, path):
1144 """Determine if path is a legal nested repository."""
1144 """Determine if path is a legal nested repository."""
1145 if not path.startswith(self.root):
1145 if not path.startswith(self.root):
1146 return False
1146 return False
1147 subpath = path[len(self.root) + 1:]
1147 subpath = path[len(self.root) + 1:]
1148 normsubpath = util.pconvert(subpath)
1148 normsubpath = util.pconvert(subpath)
1149
1149
1150 # XXX: Checking against the current working copy is wrong in
1150 # XXX: Checking against the current working copy is wrong in
1151 # the sense that it can reject things like
1151 # the sense that it can reject things like
1152 #
1152 #
1153 # $ hg cat -r 10 sub/x.txt
1153 # $ hg cat -r 10 sub/x.txt
1154 #
1154 #
1155 # if sub/ is no longer a subrepository in the working copy
1155 # if sub/ is no longer a subrepository in the working copy
1156 # parent revision.
1156 # parent revision.
1157 #
1157 #
1158 # However, it can of course also allow things that would have
1158 # However, it can of course also allow things that would have
1159 # been rejected before, such as the above cat command if sub/
1159 # been rejected before, such as the above cat command if sub/
1160 # is a subrepository now, but was a normal directory before.
1160 # is a subrepository now, but was a normal directory before.
1161 # The old path auditor would have rejected by mistake since it
1161 # The old path auditor would have rejected by mistake since it
1162 # panics when it sees sub/.hg/.
1162 # panics when it sees sub/.hg/.
1163 #
1163 #
1164 # All in all, checking against the working copy seems sensible
1164 # All in all, checking against the working copy seems sensible
1165 # since we want to prevent access to nested repositories on
1165 # since we want to prevent access to nested repositories on
1166 # the filesystem *now*.
1166 # the filesystem *now*.
1167 ctx = self[None]
1167 ctx = self[None]
1168 parts = util.splitpath(subpath)
1168 parts = util.splitpath(subpath)
1169 while parts:
1169 while parts:
1170 prefix = '/'.join(parts)
1170 prefix = '/'.join(parts)
1171 if prefix in ctx.substate:
1171 if prefix in ctx.substate:
1172 if prefix == normsubpath:
1172 if prefix == normsubpath:
1173 return True
1173 return True
1174 else:
1174 else:
1175 sub = ctx.sub(prefix)
1175 sub = ctx.sub(prefix)
1176 return sub.checknested(subpath[len(prefix) + 1:])
1176 return sub.checknested(subpath[len(prefix) + 1:])
1177 else:
1177 else:
1178 parts.pop()
1178 parts.pop()
1179 return False
1179 return False
1180
1180
1181 def peer(self):
1181 def peer(self):
1182 return localpeer(self) # not cached to avoid reference cycle
1182 return localpeer(self) # not cached to avoid reference cycle
1183
1183
1184 def unfiltered(self):
1184 def unfiltered(self):
1185 """Return unfiltered version of the repository
1185 """Return unfiltered version of the repository
1186
1186
1187 Intended to be overwritten by filtered repo."""
1187 Intended to be overwritten by filtered repo."""
1188 return self
1188 return self
1189
1189
1190 def filtered(self, name, visibilityexceptions=None):
1190 def filtered(self, name, visibilityexceptions=None):
1191 """Return a filtered version of a repository
1191 """Return a filtered version of a repository
1192
1192
1193 The `name` parameter is the identifier of the requested view. This
1193 The `name` parameter is the identifier of the requested view. This
1194 will return a repoview object set "exactly" to the specified view.
1194 will return a repoview object set "exactly" to the specified view.
1195
1195
1196 This function does not apply recursive filtering to a repository. For
1196 This function does not apply recursive filtering to a repository. For
1197 example calling `repo.filtered("served")` will return a repoview using
1197 example calling `repo.filtered("served")` will return a repoview using
1198 the "served" view, regardless of the initial view used by `repo`.
1198 the "served" view, regardless of the initial view used by `repo`.
1199
1199
1200 In other word, there is always only one level of `repoview` "filtering".
1200 In other word, there is always only one level of `repoview` "filtering".
1201 """
1201 """
1202 if self._extrafilterid is not None and '%' not in name:
1202 if self._extrafilterid is not None and '%' not in name:
1203 name = name + '%' + self._extrafilterid
1203 name = name + '%' + self._extrafilterid
1204
1204
1205 cls = repoview.newtype(self.unfiltered().__class__)
1205 cls = repoview.newtype(self.unfiltered().__class__)
1206 return cls(self, name, visibilityexceptions)
1206 return cls(self, name, visibilityexceptions)
1207
1207
1208 @repofilecache('bookmarks', 'bookmarks.current')
1208 @repofilecache('bookmarks', 'bookmarks.current')
1209 def _bookmarks(self):
1209 def _bookmarks(self):
1210 return bookmarks.bmstore(self)
1210 return bookmarks.bmstore(self)
1211
1211
1212 @property
1212 @property
1213 def _activebookmark(self):
1213 def _activebookmark(self):
1214 return self._bookmarks.active
1214 return self._bookmarks.active
1215
1215
1216 # _phasesets depend on changelog. what we need is to call
1216 # _phasesets depend on changelog. what we need is to call
1217 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1217 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1218 # can't be easily expressed in filecache mechanism.
1218 # can't be easily expressed in filecache mechanism.
1219 @storecache('phaseroots', '00changelog.i')
1219 @storecache('phaseroots', '00changelog.i')
1220 def _phasecache(self):
1220 def _phasecache(self):
1221 return phases.phasecache(self, self._phasedefaults)
1221 return phases.phasecache(self, self._phasedefaults)
1222
1222
1223 @storecache('obsstore')
1223 @storecache('obsstore')
1224 def obsstore(self):
1224 def obsstore(self):
1225 return obsolete.makestore(self.ui, self)
1225 return obsolete.makestore(self.ui, self)
1226
1226
1227 @storecache('00changelog.i')
1227 @storecache('00changelog.i')
1228 def changelog(self):
1228 def changelog(self):
1229 return changelog.changelog(self.svfs,
1229 return changelog.changelog(self.svfs,
1230 trypending=txnutil.mayhavepending(self.root))
1230 trypending=txnutil.mayhavepending(self.root))
1231
1231
1232 @storecache('00manifest.i')
1232 @storecache('00manifest.i')
1233 def manifestlog(self):
1233 def manifestlog(self):
1234 rootstore = manifest.manifestrevlog(self.svfs)
1234 rootstore = manifest.manifestrevlog(self.svfs)
1235 return manifest.manifestlog(self.svfs, self, rootstore,
1235 return manifest.manifestlog(self.svfs, self, rootstore,
1236 self._storenarrowmatch)
1236 self._storenarrowmatch)
1237
1237
1238 @repofilecache('dirstate')
1238 @repofilecache('dirstate')
1239 def dirstate(self):
1239 def dirstate(self):
1240 return self._makedirstate()
1240 return self._makedirstate()
1241
1241
1242 def _makedirstate(self):
1242 def _makedirstate(self):
1243 """Extension point for wrapping the dirstate per-repo."""
1243 """Extension point for wrapping the dirstate per-repo."""
1244 sparsematchfn = lambda: sparse.matcher(self)
1244 sparsematchfn = lambda: sparse.matcher(self)
1245
1245
1246 return dirstate.dirstate(self.vfs, self.ui, self.root,
1246 return dirstate.dirstate(self.vfs, self.ui, self.root,
1247 self._dirstatevalidate, sparsematchfn)
1247 self._dirstatevalidate, sparsematchfn)
1248
1248
1249 def _dirstatevalidate(self, node):
1249 def _dirstatevalidate(self, node):
1250 try:
1250 try:
1251 self.changelog.rev(node)
1251 self.changelog.rev(node)
1252 return node
1252 return node
1253 except error.LookupError:
1253 except error.LookupError:
1254 if not self._dirstatevalidatewarned:
1254 if not self._dirstatevalidatewarned:
1255 self._dirstatevalidatewarned = True
1255 self._dirstatevalidatewarned = True
1256 self.ui.warn(_("warning: ignoring unknown"
1256 self.ui.warn(_("warning: ignoring unknown"
1257 " working parent %s!\n") % short(node))
1257 " working parent %s!\n") % short(node))
1258 return nullid
1258 return nullid
1259
1259
1260 @storecache(narrowspec.FILENAME)
1260 @storecache(narrowspec.FILENAME)
1261 def narrowpats(self):
1261 def narrowpats(self):
1262 """matcher patterns for this repository's narrowspec
1262 """matcher patterns for this repository's narrowspec
1263
1263
1264 A tuple of (includes, excludes).
1264 A tuple of (includes, excludes).
1265 """
1265 """
1266 return narrowspec.load(self)
1266 return narrowspec.load(self)
1267
1267
1268 @storecache(narrowspec.FILENAME)
1268 @storecache(narrowspec.FILENAME)
1269 def _storenarrowmatch(self):
1269 def _storenarrowmatch(self):
1270 if repository.NARROW_REQUIREMENT not in self.requirements:
1270 if repository.NARROW_REQUIREMENT not in self.requirements:
1271 return matchmod.always()
1271 return matchmod.always()
1272 include, exclude = self.narrowpats
1272 include, exclude = self.narrowpats
1273 return narrowspec.match(self.root, include=include, exclude=exclude)
1273 return narrowspec.match(self.root, include=include, exclude=exclude)
1274
1274
1275 @storecache(narrowspec.FILENAME)
1275 @storecache(narrowspec.FILENAME)
1276 def _narrowmatch(self):
1276 def _narrowmatch(self):
1277 if repository.NARROW_REQUIREMENT not in self.requirements:
1277 if repository.NARROW_REQUIREMENT not in self.requirements:
1278 return matchmod.always()
1278 return matchmod.always()
1279 narrowspec.checkworkingcopynarrowspec(self)
1279 narrowspec.checkworkingcopynarrowspec(self)
1280 include, exclude = self.narrowpats
1280 include, exclude = self.narrowpats
1281 return narrowspec.match(self.root, include=include, exclude=exclude)
1281 return narrowspec.match(self.root, include=include, exclude=exclude)
1282
1282
1283 def narrowmatch(self, match=None, includeexact=False):
1283 def narrowmatch(self, match=None, includeexact=False):
1284 """matcher corresponding the the repo's narrowspec
1284 """matcher corresponding the the repo's narrowspec
1285
1285
1286 If `match` is given, then that will be intersected with the narrow
1286 If `match` is given, then that will be intersected with the narrow
1287 matcher.
1287 matcher.
1288
1288
1289 If `includeexact` is True, then any exact matches from `match` will
1289 If `includeexact` is True, then any exact matches from `match` will
1290 be included even if they're outside the narrowspec.
1290 be included even if they're outside the narrowspec.
1291 """
1291 """
1292 if match:
1292 if match:
1293 if includeexact and not self._narrowmatch.always():
1293 if includeexact and not self._narrowmatch.always():
1294 # do not exclude explicitly-specified paths so that they can
1294 # do not exclude explicitly-specified paths so that they can
1295 # be warned later on
1295 # be warned later on
1296 em = matchmod.exact(match.files())
1296 em = matchmod.exact(match.files())
1297 nm = matchmod.unionmatcher([self._narrowmatch, em])
1297 nm = matchmod.unionmatcher([self._narrowmatch, em])
1298 return matchmod.intersectmatchers(match, nm)
1298 return matchmod.intersectmatchers(match, nm)
1299 return matchmod.intersectmatchers(match, self._narrowmatch)
1299 return matchmod.intersectmatchers(match, self._narrowmatch)
1300 return self._narrowmatch
1300 return self._narrowmatch
1301
1301
1302 def setnarrowpats(self, newincludes, newexcludes):
1302 def setnarrowpats(self, newincludes, newexcludes):
1303 narrowspec.save(self, newincludes, newexcludes)
1303 narrowspec.save(self, newincludes, newexcludes)
1304 self.invalidate(clearfilecache=True)
1304 self.invalidate(clearfilecache=True)
1305
1305
1306 def __getitem__(self, changeid):
1306 def __getitem__(self, changeid):
1307 if changeid is None:
1307 if changeid is None:
1308 return context.workingctx(self)
1308 return context.workingctx(self)
1309 if isinstance(changeid, context.basectx):
1309 if isinstance(changeid, context.basectx):
1310 return changeid
1310 return changeid
1311 if isinstance(changeid, slice):
1311 if isinstance(changeid, slice):
1312 # wdirrev isn't contiguous so the slice shouldn't include it
1312 # wdirrev isn't contiguous so the slice shouldn't include it
1313 return [self[i]
1313 return [self[i]
1314 for i in pycompat.xrange(*changeid.indices(len(self)))
1314 for i in pycompat.xrange(*changeid.indices(len(self)))
1315 if i not in self.changelog.filteredrevs]
1315 if i not in self.changelog.filteredrevs]
1316 try:
1316 try:
1317 if isinstance(changeid, int):
1317 if isinstance(changeid, int):
1318 node = self.changelog.node(changeid)
1318 node = self.changelog.node(changeid)
1319 rev = changeid
1319 rev = changeid
1320 elif changeid == 'null':
1320 elif changeid == 'null':
1321 node = nullid
1321 node = nullid
1322 rev = nullrev
1322 rev = nullrev
1323 elif changeid == 'tip':
1323 elif changeid == 'tip':
1324 node = self.changelog.tip()
1324 node = self.changelog.tip()
1325 rev = self.changelog.rev(node)
1325 rev = self.changelog.rev(node)
1326 elif changeid == '.':
1326 elif changeid == '.':
1327 # this is a hack to delay/avoid loading obsmarkers
1327 # this is a hack to delay/avoid loading obsmarkers
1328 # when we know that '.' won't be hidden
1328 # when we know that '.' won't be hidden
1329 node = self.dirstate.p1()
1329 node = self.dirstate.p1()
1330 rev = self.unfiltered().changelog.rev(node)
1330 rev = self.unfiltered().changelog.rev(node)
1331 elif len(changeid) == 20:
1331 elif len(changeid) == 20:
1332 try:
1332 try:
1333 node = changeid
1333 node = changeid
1334 rev = self.changelog.rev(changeid)
1334 rev = self.changelog.rev(changeid)
1335 except error.FilteredLookupError:
1335 except error.FilteredLookupError:
1336 changeid = hex(changeid) # for the error message
1336 changeid = hex(changeid) # for the error message
1337 raise
1337 raise
1338 except LookupError:
1338 except LookupError:
1339 # check if it might have come from damaged dirstate
1339 # check if it might have come from damaged dirstate
1340 #
1340 #
1341 # XXX we could avoid the unfiltered if we had a recognizable
1341 # XXX we could avoid the unfiltered if we had a recognizable
1342 # exception for filtered changeset access
1342 # exception for filtered changeset access
1343 if (self.local()
1343 if (self.local()
1344 and changeid in self.unfiltered().dirstate.parents()):
1344 and changeid in self.unfiltered().dirstate.parents()):
1345 msg = _("working directory has unknown parent '%s'!")
1345 msg = _("working directory has unknown parent '%s'!")
1346 raise error.Abort(msg % short(changeid))
1346 raise error.Abort(msg % short(changeid))
1347 changeid = hex(changeid) # for the error message
1347 changeid = hex(changeid) # for the error message
1348 raise
1348 raise
1349
1349
1350 elif len(changeid) == 40:
1350 elif len(changeid) == 40:
1351 node = bin(changeid)
1351 node = bin(changeid)
1352 rev = self.changelog.rev(node)
1352 rev = self.changelog.rev(node)
1353 else:
1353 else:
1354 raise error.ProgrammingError(
1354 raise error.ProgrammingError(
1355 "unsupported changeid '%s' of type %s" %
1355 "unsupported changeid '%s' of type %s" %
1356 (changeid, type(changeid)))
1356 (changeid, type(changeid)))
1357
1357
1358 return context.changectx(self, rev, node)
1358 return context.changectx(self, rev, node)
1359
1359
1360 except (error.FilteredIndexError, error.FilteredLookupError):
1360 except (error.FilteredIndexError, error.FilteredLookupError):
1361 raise error.FilteredRepoLookupError(_("filtered revision '%s'")
1361 raise error.FilteredRepoLookupError(_("filtered revision '%s'")
1362 % pycompat.bytestr(changeid))
1362 % pycompat.bytestr(changeid))
1363 except (IndexError, LookupError):
1363 except (IndexError, LookupError):
1364 raise error.RepoLookupError(
1364 raise error.RepoLookupError(
1365 _("unknown revision '%s'") % pycompat.bytestr(changeid))
1365 _("unknown revision '%s'") % pycompat.bytestr(changeid))
1366 except error.WdirUnsupported:
1366 except error.WdirUnsupported:
1367 return context.workingctx(self)
1367 return context.workingctx(self)
1368
1368
1369 def __contains__(self, changeid):
1369 def __contains__(self, changeid):
1370 """True if the given changeid exists
1370 """True if the given changeid exists
1371
1371
1372 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1372 error.AmbiguousPrefixLookupError is raised if an ambiguous node
1373 specified.
1373 specified.
1374 """
1374 """
1375 try:
1375 try:
1376 self[changeid]
1376 self[changeid]
1377 return True
1377 return True
1378 except error.RepoLookupError:
1378 except error.RepoLookupError:
1379 return False
1379 return False
1380
1380
1381 def __nonzero__(self):
1381 def __nonzero__(self):
1382 return True
1382 return True
1383
1383
1384 __bool__ = __nonzero__
1384 __bool__ = __nonzero__
1385
1385
1386 def __len__(self):
1386 def __len__(self):
1387 # no need to pay the cost of repoview.changelog
1387 # no need to pay the cost of repoview.changelog
1388 unfi = self.unfiltered()
1388 unfi = self.unfiltered()
1389 return len(unfi.changelog)
1389 return len(unfi.changelog)
1390
1390
1391 def __iter__(self):
1391 def __iter__(self):
1392 return iter(self.changelog)
1392 return iter(self.changelog)
1393
1393
1394 def revs(self, expr, *args):
1394 def revs(self, expr, *args):
1395 '''Find revisions matching a revset.
1395 '''Find revisions matching a revset.
1396
1396
1397 The revset is specified as a string ``expr`` that may contain
1397 The revset is specified as a string ``expr`` that may contain
1398 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1398 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1399
1399
1400 Revset aliases from the configuration are not expanded. To expand
1400 Revset aliases from the configuration are not expanded. To expand
1401 user aliases, consider calling ``scmutil.revrange()`` or
1401 user aliases, consider calling ``scmutil.revrange()`` or
1402 ``repo.anyrevs([expr], user=True)``.
1402 ``repo.anyrevs([expr], user=True)``.
1403
1403
1404 Returns a revset.abstractsmartset, which is a list-like interface
1404 Returns a revset.abstractsmartset, which is a list-like interface
1405 that contains integer revisions.
1405 that contains integer revisions.
1406 '''
1406 '''
1407 tree = revsetlang.spectree(expr, *args)
1407 tree = revsetlang.spectree(expr, *args)
1408 return revset.makematcher(tree)(self)
1408 return revset.makematcher(tree)(self)
1409
1409
1410 def set(self, expr, *args):
1410 def set(self, expr, *args):
1411 '''Find revisions matching a revset and emit changectx instances.
1411 '''Find revisions matching a revset and emit changectx instances.
1412
1412
1413 This is a convenience wrapper around ``revs()`` that iterates the
1413 This is a convenience wrapper around ``revs()`` that iterates the
1414 result and is a generator of changectx instances.
1414 result and is a generator of changectx instances.
1415
1415
1416 Revset aliases from the configuration are not expanded. To expand
1416 Revset aliases from the configuration are not expanded. To expand
1417 user aliases, consider calling ``scmutil.revrange()``.
1417 user aliases, consider calling ``scmutil.revrange()``.
1418 '''
1418 '''
1419 for r in self.revs(expr, *args):
1419 for r in self.revs(expr, *args):
1420 yield self[r]
1420 yield self[r]
1421
1421
1422 def anyrevs(self, specs, user=False, localalias=None):
1422 def anyrevs(self, specs, user=False, localalias=None):
1423 '''Find revisions matching one of the given revsets.
1423 '''Find revisions matching one of the given revsets.
1424
1424
1425 Revset aliases from the configuration are not expanded by default. To
1425 Revset aliases from the configuration are not expanded by default. To
1426 expand user aliases, specify ``user=True``. To provide some local
1426 expand user aliases, specify ``user=True``. To provide some local
1427 definitions overriding user aliases, set ``localalias`` to
1427 definitions overriding user aliases, set ``localalias`` to
1428 ``{name: definitionstring}``.
1428 ``{name: definitionstring}``.
1429 '''
1429 '''
1430 if user:
1430 if user:
1431 m = revset.matchany(self.ui, specs,
1431 m = revset.matchany(self.ui, specs,
1432 lookup=revset.lookupfn(self),
1432 lookup=revset.lookupfn(self),
1433 localalias=localalias)
1433 localalias=localalias)
1434 else:
1434 else:
1435 m = revset.matchany(None, specs, localalias=localalias)
1435 m = revset.matchany(None, specs, localalias=localalias)
1436 return m(self)
1436 return m(self)
1437
1437
1438 def url(self):
1438 def url(self):
1439 return 'file:' + self.root
1439 return 'file:' + self.root
1440
1440
1441 def hook(self, name, throw=False, **args):
1441 def hook(self, name, throw=False, **args):
1442 """Call a hook, passing this repo instance.
1442 """Call a hook, passing this repo instance.
1443
1443
1444 This a convenience method to aid invoking hooks. Extensions likely
1444 This a convenience method to aid invoking hooks. Extensions likely
1445 won't call this unless they have registered a custom hook or are
1445 won't call this unless they have registered a custom hook or are
1446 replacing code that is expected to call a hook.
1446 replacing code that is expected to call a hook.
1447 """
1447 """
1448 return hook.hook(self.ui, self, name, throw, **args)
1448 return hook.hook(self.ui, self, name, throw, **args)
1449
1449
1450 @filteredpropertycache
1450 @filteredpropertycache
1451 def _tagscache(self):
1451 def _tagscache(self):
1452 '''Returns a tagscache object that contains various tags related
1452 '''Returns a tagscache object that contains various tags related
1453 caches.'''
1453 caches.'''
1454
1454
1455 # This simplifies its cache management by having one decorated
1455 # This simplifies its cache management by having one decorated
1456 # function (this one) and the rest simply fetch things from it.
1456 # function (this one) and the rest simply fetch things from it.
1457 class tagscache(object):
1457 class tagscache(object):
1458 def __init__(self):
1458 def __init__(self):
1459 # These two define the set of tags for this repository. tags
1459 # These two define the set of tags for this repository. tags
1460 # maps tag name to node; tagtypes maps tag name to 'global' or
1460 # maps tag name to node; tagtypes maps tag name to 'global' or
1461 # 'local'. (Global tags are defined by .hgtags across all
1461 # 'local'. (Global tags are defined by .hgtags across all
1462 # heads, and local tags are defined in .hg/localtags.)
1462 # heads, and local tags are defined in .hg/localtags.)
1463 # They constitute the in-memory cache of tags.
1463 # They constitute the in-memory cache of tags.
1464 self.tags = self.tagtypes = None
1464 self.tags = self.tagtypes = None
1465
1465
1466 self.nodetagscache = self.tagslist = None
1466 self.nodetagscache = self.tagslist = None
1467
1467
1468 cache = tagscache()
1468 cache = tagscache()
1469 cache.tags, cache.tagtypes = self._findtags()
1469 cache.tags, cache.tagtypes = self._findtags()
1470
1470
1471 return cache
1471 return cache
1472
1472
1473 def tags(self):
1473 def tags(self):
1474 '''return a mapping of tag to node'''
1474 '''return a mapping of tag to node'''
1475 t = {}
1475 t = {}
1476 if self.changelog.filteredrevs:
1476 if self.changelog.filteredrevs:
1477 tags, tt = self._findtags()
1477 tags, tt = self._findtags()
1478 else:
1478 else:
1479 tags = self._tagscache.tags
1479 tags = self._tagscache.tags
1480 rev = self.changelog.rev
1480 rev = self.changelog.rev
1481 for k, v in tags.iteritems():
1481 for k, v in tags.iteritems():
1482 try:
1482 try:
1483 # ignore tags to unknown nodes
1483 # ignore tags to unknown nodes
1484 rev(v)
1484 rev(v)
1485 t[k] = v
1485 t[k] = v
1486 except (error.LookupError, ValueError):
1486 except (error.LookupError, ValueError):
1487 pass
1487 pass
1488 return t
1488 return t
1489
1489
1490 def _findtags(self):
1490 def _findtags(self):
1491 '''Do the hard work of finding tags. Return a pair of dicts
1491 '''Do the hard work of finding tags. Return a pair of dicts
1492 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1492 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1493 maps tag name to a string like \'global\' or \'local\'.
1493 maps tag name to a string like \'global\' or \'local\'.
1494 Subclasses or extensions are free to add their own tags, but
1494 Subclasses or extensions are free to add their own tags, but
1495 should be aware that the returned dicts will be retained for the
1495 should be aware that the returned dicts will be retained for the
1496 duration of the localrepo object.'''
1496 duration of the localrepo object.'''
1497
1497
1498 # XXX what tagtype should subclasses/extensions use? Currently
1498 # XXX what tagtype should subclasses/extensions use? Currently
1499 # mq and bookmarks add tags, but do not set the tagtype at all.
1499 # mq and bookmarks add tags, but do not set the tagtype at all.
1500 # Should each extension invent its own tag type? Should there
1500 # Should each extension invent its own tag type? Should there
1501 # be one tagtype for all such "virtual" tags? Or is the status
1501 # be one tagtype for all such "virtual" tags? Or is the status
1502 # quo fine?
1502 # quo fine?
1503
1503
1504
1504
1505 # map tag name to (node, hist)
1505 # map tag name to (node, hist)
1506 alltags = tagsmod.findglobaltags(self.ui, self)
1506 alltags = tagsmod.findglobaltags(self.ui, self)
1507 # map tag name to tag type
1507 # map tag name to tag type
1508 tagtypes = dict((tag, 'global') for tag in alltags)
1508 tagtypes = dict((tag, 'global') for tag in alltags)
1509
1509
1510 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1510 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1511
1511
1512 # Build the return dicts. Have to re-encode tag names because
1512 # Build the return dicts. Have to re-encode tag names because
1513 # the tags module always uses UTF-8 (in order not to lose info
1513 # the tags module always uses UTF-8 (in order not to lose info
1514 # writing to the cache), but the rest of Mercurial wants them in
1514 # writing to the cache), but the rest of Mercurial wants them in
1515 # local encoding.
1515 # local encoding.
1516 tags = {}
1516 tags = {}
1517 for (name, (node, hist)) in alltags.iteritems():
1517 for (name, (node, hist)) in alltags.iteritems():
1518 if node != nullid:
1518 if node != nullid:
1519 tags[encoding.tolocal(name)] = node
1519 tags[encoding.tolocal(name)] = node
1520 tags['tip'] = self.changelog.tip()
1520 tags['tip'] = self.changelog.tip()
1521 tagtypes = dict([(encoding.tolocal(name), value)
1521 tagtypes = dict([(encoding.tolocal(name), value)
1522 for (name, value) in tagtypes.iteritems()])
1522 for (name, value) in tagtypes.iteritems()])
1523 return (tags, tagtypes)
1523 return (tags, tagtypes)
1524
1524
1525 def tagtype(self, tagname):
1525 def tagtype(self, tagname):
1526 '''
1526 '''
1527 return the type of the given tag. result can be:
1527 return the type of the given tag. result can be:
1528
1528
1529 'local' : a local tag
1529 'local' : a local tag
1530 'global' : a global tag
1530 'global' : a global tag
1531 None : tag does not exist
1531 None : tag does not exist
1532 '''
1532 '''
1533
1533
1534 return self._tagscache.tagtypes.get(tagname)
1534 return self._tagscache.tagtypes.get(tagname)
1535
1535
1536 def tagslist(self):
1536 def tagslist(self):
1537 '''return a list of tags ordered by revision'''
1537 '''return a list of tags ordered by revision'''
1538 if not self._tagscache.tagslist:
1538 if not self._tagscache.tagslist:
1539 l = []
1539 l = []
1540 for t, n in self.tags().iteritems():
1540 for t, n in self.tags().iteritems():
1541 l.append((self.changelog.rev(n), t, n))
1541 l.append((self.changelog.rev(n), t, n))
1542 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1542 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1543
1543
1544 return self._tagscache.tagslist
1544 return self._tagscache.tagslist
1545
1545
1546 def nodetags(self, node):
1546 def nodetags(self, node):
1547 '''return the tags associated with a node'''
1547 '''return the tags associated with a node'''
1548 if not self._tagscache.nodetagscache:
1548 if not self._tagscache.nodetagscache:
1549 nodetagscache = {}
1549 nodetagscache = {}
1550 for t, n in self._tagscache.tags.iteritems():
1550 for t, n in self._tagscache.tags.iteritems():
1551 nodetagscache.setdefault(n, []).append(t)
1551 nodetagscache.setdefault(n, []).append(t)
1552 for tags in nodetagscache.itervalues():
1552 for tags in nodetagscache.itervalues():
1553 tags.sort()
1553 tags.sort()
1554 self._tagscache.nodetagscache = nodetagscache
1554 self._tagscache.nodetagscache = nodetagscache
1555 return self._tagscache.nodetagscache.get(node, [])
1555 return self._tagscache.nodetagscache.get(node, [])
1556
1556
1557 def nodebookmarks(self, node):
1557 def nodebookmarks(self, node):
1558 """return the list of bookmarks pointing to the specified node"""
1558 """return the list of bookmarks pointing to the specified node"""
1559 return self._bookmarks.names(node)
1559 return self._bookmarks.names(node)
1560
1560
1561 def branchmap(self):
1561 def branchmap(self):
1562 '''returns a dictionary {branch: [branchheads]} with branchheads
1562 '''returns a dictionary {branch: [branchheads]} with branchheads
1563 ordered by increasing revision number'''
1563 ordered by increasing revision number'''
1564 return self._branchcaches[self]
1564 return self._branchcaches[self]
1565
1565
1566 @unfilteredmethod
1566 @unfilteredmethod
1567 def revbranchcache(self):
1567 def revbranchcache(self):
1568 if not self._revbranchcache:
1568 if not self._revbranchcache:
1569 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1569 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1570 return self._revbranchcache
1570 return self._revbranchcache
1571
1571
1572 def branchtip(self, branch, ignoremissing=False):
1572 def branchtip(self, branch, ignoremissing=False):
1573 '''return the tip node for a given branch
1573 '''return the tip node for a given branch
1574
1574
1575 If ignoremissing is True, then this method will not raise an error.
1575 If ignoremissing is True, then this method will not raise an error.
1576 This is helpful for callers that only expect None for a missing branch
1576 This is helpful for callers that only expect None for a missing branch
1577 (e.g. namespace).
1577 (e.g. namespace).
1578
1578
1579 '''
1579 '''
1580 try:
1580 try:
1581 return self.branchmap().branchtip(branch)
1581 return self.branchmap().branchtip(branch)
1582 except KeyError:
1582 except KeyError:
1583 if not ignoremissing:
1583 if not ignoremissing:
1584 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1584 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1585 else:
1585 else:
1586 pass
1586 pass
1587
1587
1588 def lookup(self, key):
1588 def lookup(self, key):
1589 node = scmutil.revsymbol(self, key).node()
1589 node = scmutil.revsymbol(self, key).node()
1590 if node is None:
1590 if node is None:
1591 raise error.RepoLookupError(_("unknown revision '%s'") % key)
1591 raise error.RepoLookupError(_("unknown revision '%s'") % key)
1592 return node
1592 return node
1593
1593
1594 def lookupbranch(self, key):
1594 def lookupbranch(self, key):
1595 if self.branchmap().hasbranch(key):
1595 if self.branchmap().hasbranch(key):
1596 return key
1596 return key
1597
1597
1598 return scmutil.revsymbol(self, key).branch()
1598 return scmutil.revsymbol(self, key).branch()
1599
1599
1600 def known(self, nodes):
1600 def known(self, nodes):
1601 cl = self.changelog
1601 cl = self.changelog
1602 nm = cl.nodemap
1602 nm = cl.nodemap
1603 filtered = cl.filteredrevs
1603 filtered = cl.filteredrevs
1604 result = []
1604 result = []
1605 for n in nodes:
1605 for n in nodes:
1606 r = nm.get(n)
1606 r = nm.get(n)
1607 resp = not (r is None or r in filtered)
1607 resp = not (r is None or r in filtered)
1608 result.append(resp)
1608 result.append(resp)
1609 return result
1609 return result
1610
1610
1611 def local(self):
1611 def local(self):
1612 return self
1612 return self
1613
1613
1614 def publishing(self):
1614 def publishing(self):
1615 # it's safe (and desirable) to trust the publish flag unconditionally
1615 # it's safe (and desirable) to trust the publish flag unconditionally
1616 # so that we don't finalize changes shared between users via ssh or nfs
1616 # so that we don't finalize changes shared between users via ssh or nfs
1617 return self.ui.configbool('phases', 'publish', untrusted=True)
1617 return self.ui.configbool('phases', 'publish', untrusted=True)
1618
1618
1619 def cancopy(self):
1619 def cancopy(self):
1620 # so statichttprepo's override of local() works
1620 # so statichttprepo's override of local() works
1621 if not self.local():
1621 if not self.local():
1622 return False
1622 return False
1623 if not self.publishing():
1623 if not self.publishing():
1624 return True
1624 return True
1625 # if publishing we can't copy if there is filtered content
1625 # if publishing we can't copy if there is filtered content
1626 return not self.filtered('visible').changelog.filteredrevs
1626 return not self.filtered('visible').changelog.filteredrevs
1627
1627
1628 def shared(self):
1628 def shared(self):
1629 '''the type of shared repository (None if not shared)'''
1629 '''the type of shared repository (None if not shared)'''
1630 if self.sharedpath != self.path:
1630 if self.sharedpath != self.path:
1631 return 'store'
1631 return 'store'
1632 return None
1632 return None
1633
1633
1634 def wjoin(self, f, *insidef):
1634 def wjoin(self, f, *insidef):
1635 return self.vfs.reljoin(self.root, f, *insidef)
1635 return self.vfs.reljoin(self.root, f, *insidef)
1636
1636
1637 def setparents(self, p1, p2=nullid):
1637 def setparents(self, p1, p2=nullid):
1638 with self.dirstate.parentchange():
1638 with self.dirstate.parentchange():
1639 copies = self.dirstate.setparents(p1, p2)
1639 copies = self.dirstate.setparents(p1, p2)
1640 pctx = self[p1]
1640 pctx = self[p1]
1641 if copies:
1641 if copies:
1642 # Adjust copy records, the dirstate cannot do it, it
1642 # Adjust copy records, the dirstate cannot do it, it
1643 # requires access to parents manifests. Preserve them
1643 # requires access to parents manifests. Preserve them
1644 # only for entries added to first parent.
1644 # only for entries added to first parent.
1645 for f in copies:
1645 for f in copies:
1646 if f not in pctx and copies[f] in pctx:
1646 if f not in pctx and copies[f] in pctx:
1647 self.dirstate.copy(copies[f], f)
1647 self.dirstate.copy(copies[f], f)
1648 if p2 == nullid:
1648 if p2 == nullid:
1649 for f, s in sorted(self.dirstate.copies().items()):
1649 for f, s in sorted(self.dirstate.copies().items()):
1650 if f not in pctx and s not in pctx:
1650 if f not in pctx and s not in pctx:
1651 self.dirstate.copy(None, f)
1651 self.dirstate.copy(None, f)
1652
1652
1653 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1653 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1654 """changeid must be a changeset revision, if specified.
1654 """changeid must be a changeset revision, if specified.
1655 fileid can be a file revision or node."""
1655 fileid can be a file revision or node."""
1656 return context.filectx(self, path, changeid, fileid,
1656 return context.filectx(self, path, changeid, fileid,
1657 changectx=changectx)
1657 changectx=changectx)
1658
1658
1659 def getcwd(self):
1659 def getcwd(self):
1660 return self.dirstate.getcwd()
1660 return self.dirstate.getcwd()
1661
1661
1662 def pathto(self, f, cwd=None):
1662 def pathto(self, f, cwd=None):
1663 return self.dirstate.pathto(f, cwd)
1663 return self.dirstate.pathto(f, cwd)
1664
1664
1665 def _loadfilter(self, filter):
1665 def _loadfilter(self, filter):
1666 if filter not in self._filterpats:
1666 if filter not in self._filterpats:
1667 l = []
1667 l = []
1668 for pat, cmd in self.ui.configitems(filter):
1668 for pat, cmd in self.ui.configitems(filter):
1669 if cmd == '!':
1669 if cmd == '!':
1670 continue
1670 continue
1671 mf = matchmod.match(self.root, '', [pat])
1671 mf = matchmod.match(self.root, '', [pat])
1672 fn = None
1672 fn = None
1673 params = cmd
1673 params = cmd
1674 for name, filterfn in self._datafilters.iteritems():
1674 for name, filterfn in self._datafilters.iteritems():
1675 if cmd.startswith(name):
1675 if cmd.startswith(name):
1676 fn = filterfn
1676 fn = filterfn
1677 params = cmd[len(name):].lstrip()
1677 params = cmd[len(name):].lstrip()
1678 break
1678 break
1679 if not fn:
1679 if not fn:
1680 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1680 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1681 # Wrap old filters not supporting keyword arguments
1681 # Wrap old filters not supporting keyword arguments
1682 if not pycompat.getargspec(fn)[2]:
1682 if not pycompat.getargspec(fn)[2]:
1683 oldfn = fn
1683 oldfn = fn
1684 fn = lambda s, c, **kwargs: oldfn(s, c)
1684 fn = lambda s, c, **kwargs: oldfn(s, c)
1685 l.append((mf, fn, params))
1685 l.append((mf, fn, params))
1686 self._filterpats[filter] = l
1686 self._filterpats[filter] = l
1687 return self._filterpats[filter]
1687 return self._filterpats[filter]
1688
1688
1689 def _filter(self, filterpats, filename, data):
1689 def _filter(self, filterpats, filename, data):
1690 for mf, fn, cmd in filterpats:
1690 for mf, fn, cmd in filterpats:
1691 if mf(filename):
1691 if mf(filename):
1692 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1692 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1693 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1693 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1694 break
1694 break
1695
1695
1696 return data
1696 return data
1697
1697
1698 @unfilteredpropertycache
1698 @unfilteredpropertycache
1699 def _encodefilterpats(self):
1699 def _encodefilterpats(self):
1700 return self._loadfilter('encode')
1700 return self._loadfilter('encode')
1701
1701
1702 @unfilteredpropertycache
1702 @unfilteredpropertycache
1703 def _decodefilterpats(self):
1703 def _decodefilterpats(self):
1704 return self._loadfilter('decode')
1704 return self._loadfilter('decode')
1705
1705
1706 def adddatafilter(self, name, filter):
1706 def adddatafilter(self, name, filter):
1707 self._datafilters[name] = filter
1707 self._datafilters[name] = filter
1708
1708
1709 def wread(self, filename):
1709 def wread(self, filename):
1710 if self.wvfs.islink(filename):
1710 if self.wvfs.islink(filename):
1711 data = self.wvfs.readlink(filename)
1711 data = self.wvfs.readlink(filename)
1712 else:
1712 else:
1713 data = self.wvfs.read(filename)
1713 data = self.wvfs.read(filename)
1714 return self._filter(self._encodefilterpats, filename, data)
1714 return self._filter(self._encodefilterpats, filename, data)
1715
1715
1716 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1716 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1717 """write ``data`` into ``filename`` in the working directory
1717 """write ``data`` into ``filename`` in the working directory
1718
1718
1719 This returns length of written (maybe decoded) data.
1719 This returns length of written (maybe decoded) data.
1720 """
1720 """
1721 data = self._filter(self._decodefilterpats, filename, data)
1721 data = self._filter(self._decodefilterpats, filename, data)
1722 if 'l' in flags:
1722 if 'l' in flags:
1723 self.wvfs.symlink(data, filename)
1723 self.wvfs.symlink(data, filename)
1724 else:
1724 else:
1725 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1725 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1726 **kwargs)
1726 **kwargs)
1727 if 'x' in flags:
1727 if 'x' in flags:
1728 self.wvfs.setflags(filename, False, True)
1728 self.wvfs.setflags(filename, False, True)
1729 else:
1729 else:
1730 self.wvfs.setflags(filename, False, False)
1730 self.wvfs.setflags(filename, False, False)
1731 return len(data)
1731 return len(data)
1732
1732
1733 def wwritedata(self, filename, data):
1733 def wwritedata(self, filename, data):
1734 return self._filter(self._decodefilterpats, filename, data)
1734 return self._filter(self._decodefilterpats, filename, data)
1735
1735
1736 def currenttransaction(self):
1736 def currenttransaction(self):
1737 """return the current transaction or None if non exists"""
1737 """return the current transaction or None if non exists"""
1738 if self._transref:
1738 if self._transref:
1739 tr = self._transref()
1739 tr = self._transref()
1740 else:
1740 else:
1741 tr = None
1741 tr = None
1742
1742
1743 if tr and tr.running():
1743 if tr and tr.running():
1744 return tr
1744 return tr
1745 return None
1745 return None
1746
1746
1747 def transaction(self, desc, report=None):
1747 def transaction(self, desc, report=None):
1748 if (self.ui.configbool('devel', 'all-warnings')
1748 if (self.ui.configbool('devel', 'all-warnings')
1749 or self.ui.configbool('devel', 'check-locks')):
1749 or self.ui.configbool('devel', 'check-locks')):
1750 if self._currentlock(self._lockref) is None:
1750 if self._currentlock(self._lockref) is None:
1751 raise error.ProgrammingError('transaction requires locking')
1751 raise error.ProgrammingError('transaction requires locking')
1752 tr = self.currenttransaction()
1752 tr = self.currenttransaction()
1753 if tr is not None:
1753 if tr is not None:
1754 return tr.nest(name=desc)
1754 return tr.nest(name=desc)
1755
1755
1756 # abort here if the journal already exists
1756 # abort here if the journal already exists
1757 if self.svfs.exists("journal"):
1757 if self.svfs.exists("journal"):
1758 raise error.RepoError(
1758 raise error.RepoError(
1759 _("abandoned transaction found"),
1759 _("abandoned transaction found"),
1760 hint=_("run 'hg recover' to clean up transaction"))
1760 hint=_("run 'hg recover' to clean up transaction"))
1761
1761
1762 idbase = "%.40f#%f" % (random.random(), time.time())
1762 idbase = "%.40f#%f" % (random.random(), time.time())
1763 ha = hex(hashlib.sha1(idbase).digest())
1763 ha = hex(hashlib.sha1(idbase).digest())
1764 txnid = 'TXN:' + ha
1764 txnid = 'TXN:' + ha
1765 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1765 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1766
1766
1767 self._writejournal(desc)
1767 self._writejournal(desc)
1768 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1768 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1769 if report:
1769 if report:
1770 rp = report
1770 rp = report
1771 else:
1771 else:
1772 rp = self.ui.warn
1772 rp = self.ui.warn
1773 vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/
1773 vfsmap = {'plain': self.vfs, 'store': self.svfs} # root of .hg/
1774 # we must avoid cyclic reference between repo and transaction.
1774 # we must avoid cyclic reference between repo and transaction.
1775 reporef = weakref.ref(self)
1775 reporef = weakref.ref(self)
1776 # Code to track tag movement
1776 # Code to track tag movement
1777 #
1777 #
1778 # Since tags are all handled as file content, it is actually quite hard
1778 # Since tags are all handled as file content, it is actually quite hard
1779 # to track these movement from a code perspective. So we fallback to a
1779 # to track these movement from a code perspective. So we fallback to a
1780 # tracking at the repository level. One could envision to track changes
1780 # tracking at the repository level. One could envision to track changes
1781 # to the '.hgtags' file through changegroup apply but that fails to
1781 # to the '.hgtags' file through changegroup apply but that fails to
1782 # cope with case where transaction expose new heads without changegroup
1782 # cope with case where transaction expose new heads without changegroup
1783 # being involved (eg: phase movement).
1783 # being involved (eg: phase movement).
1784 #
1784 #
1785 # For now, We gate the feature behind a flag since this likely comes
1785 # For now, We gate the feature behind a flag since this likely comes
1786 # with performance impacts. The current code run more often than needed
1786 # with performance impacts. The current code run more often than needed
1787 # and do not use caches as much as it could. The current focus is on
1787 # and do not use caches as much as it could. The current focus is on
1788 # the behavior of the feature so we disable it by default. The flag
1788 # the behavior of the feature so we disable it by default. The flag
1789 # will be removed when we are happy with the performance impact.
1789 # will be removed when we are happy with the performance impact.
1790 #
1790 #
1791 # Once this feature is no longer experimental move the following
1791 # Once this feature is no longer experimental move the following
1792 # documentation to the appropriate help section:
1792 # documentation to the appropriate help section:
1793 #
1793 #
1794 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1794 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1795 # tags (new or changed or deleted tags). In addition the details of
1795 # tags (new or changed or deleted tags). In addition the details of
1796 # these changes are made available in a file at:
1796 # these changes are made available in a file at:
1797 # ``REPOROOT/.hg/changes/tags.changes``.
1797 # ``REPOROOT/.hg/changes/tags.changes``.
1798 # Make sure you check for HG_TAG_MOVED before reading that file as it
1798 # Make sure you check for HG_TAG_MOVED before reading that file as it
1799 # might exist from a previous transaction even if no tag were touched
1799 # might exist from a previous transaction even if no tag were touched
1800 # in this one. Changes are recorded in a line base format::
1800 # in this one. Changes are recorded in a line base format::
1801 #
1801 #
1802 # <action> <hex-node> <tag-name>\n
1802 # <action> <hex-node> <tag-name>\n
1803 #
1803 #
1804 # Actions are defined as follow:
1804 # Actions are defined as follow:
1805 # "-R": tag is removed,
1805 # "-R": tag is removed,
1806 # "+A": tag is added,
1806 # "+A": tag is added,
1807 # "-M": tag is moved (old value),
1807 # "-M": tag is moved (old value),
1808 # "+M": tag is moved (new value),
1808 # "+M": tag is moved (new value),
1809 tracktags = lambda x: None
1809 tracktags = lambda x: None
1810 # experimental config: experimental.hook-track-tags
1810 # experimental config: experimental.hook-track-tags
1811 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1811 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1812 if desc != 'strip' and shouldtracktags:
1812 if desc != 'strip' and shouldtracktags:
1813 oldheads = self.changelog.headrevs()
1813 oldheads = self.changelog.headrevs()
1814 def tracktags(tr2):
1814 def tracktags(tr2):
1815 repo = reporef()
1815 repo = reporef()
1816 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1816 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1817 newheads = repo.changelog.headrevs()
1817 newheads = repo.changelog.headrevs()
1818 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1818 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1819 # notes: we compare lists here.
1819 # notes: we compare lists here.
1820 # As we do it only once buiding set would not be cheaper
1820 # As we do it only once buiding set would not be cheaper
1821 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1821 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1822 if changes:
1822 if changes:
1823 tr2.hookargs['tag_moved'] = '1'
1823 tr2.hookargs['tag_moved'] = '1'
1824 with repo.vfs('changes/tags.changes', 'w',
1824 with repo.vfs('changes/tags.changes', 'w',
1825 atomictemp=True) as changesfile:
1825 atomictemp=True) as changesfile:
1826 # note: we do not register the file to the transaction
1826 # note: we do not register the file to the transaction
1827 # because we needs it to still exist on the transaction
1827 # because we needs it to still exist on the transaction
1828 # is close (for txnclose hooks)
1828 # is close (for txnclose hooks)
1829 tagsmod.writediff(changesfile, changes)
1829 tagsmod.writediff(changesfile, changes)
1830 def validate(tr2):
1830 def validate(tr2):
1831 """will run pre-closing hooks"""
1831 """will run pre-closing hooks"""
1832 # XXX the transaction API is a bit lacking here so we take a hacky
1832 # XXX the transaction API is a bit lacking here so we take a hacky
1833 # path for now
1833 # path for now
1834 #
1834 #
1835 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1835 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1836 # dict is copied before these run. In addition we needs the data
1836 # dict is copied before these run. In addition we needs the data
1837 # available to in memory hooks too.
1837 # available to in memory hooks too.
1838 #
1838 #
1839 # Moreover, we also need to make sure this runs before txnclose
1839 # Moreover, we also need to make sure this runs before txnclose
1840 # hooks and there is no "pending" mechanism that would execute
1840 # hooks and there is no "pending" mechanism that would execute
1841 # logic only if hooks are about to run.
1841 # logic only if hooks are about to run.
1842 #
1842 #
1843 # Fixing this limitation of the transaction is also needed to track
1843 # Fixing this limitation of the transaction is also needed to track
1844 # other families of changes (bookmarks, phases, obsolescence).
1844 # other families of changes (bookmarks, phases, obsolescence).
1845 #
1845 #
1846 # This will have to be fixed before we remove the experimental
1846 # This will have to be fixed before we remove the experimental
1847 # gating.
1847 # gating.
1848 tracktags(tr2)
1848 tracktags(tr2)
1849 repo = reporef()
1849 repo = reporef()
1850 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1850 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1851 scmutil.enforcesinglehead(repo, tr2, desc)
1851 scmutil.enforcesinglehead(repo, tr2, desc)
1852 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1852 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1853 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1853 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1854 args = tr.hookargs.copy()
1854 args = tr.hookargs.copy()
1855 args.update(bookmarks.preparehookargs(name, old, new))
1855 args.update(bookmarks.preparehookargs(name, old, new))
1856 repo.hook('pretxnclose-bookmark', throw=True,
1856 repo.hook('pretxnclose-bookmark', throw=True,
1857 **pycompat.strkwargs(args))
1857 **pycompat.strkwargs(args))
1858 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1858 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1859 cl = repo.unfiltered().changelog
1859 cl = repo.unfiltered().changelog
1860 for rev, (old, new) in tr.changes['phases'].items():
1860 for rev, (old, new) in tr.changes['phases'].items():
1861 args = tr.hookargs.copy()
1861 args = tr.hookargs.copy()
1862 node = hex(cl.node(rev))
1862 node = hex(cl.node(rev))
1863 args.update(phases.preparehookargs(node, old, new))
1863 args.update(phases.preparehookargs(node, old, new))
1864 repo.hook('pretxnclose-phase', throw=True,
1864 repo.hook('pretxnclose-phase', throw=True,
1865 **pycompat.strkwargs(args))
1865 **pycompat.strkwargs(args))
1866
1866
1867 repo.hook('pretxnclose', throw=True,
1867 repo.hook('pretxnclose', throw=True,
1868 **pycompat.strkwargs(tr.hookargs))
1868 **pycompat.strkwargs(tr.hookargs))
1869 def releasefn(tr, success):
1869 def releasefn(tr, success):
1870 repo = reporef()
1870 repo = reporef()
1871 if success:
1871 if success:
1872 # this should be explicitly invoked here, because
1872 # this should be explicitly invoked here, because
1873 # in-memory changes aren't written out at closing
1873 # in-memory changes aren't written out at closing
1874 # transaction, if tr.addfilegenerator (via
1874 # transaction, if tr.addfilegenerator (via
1875 # dirstate.write or so) isn't invoked while
1875 # dirstate.write or so) isn't invoked while
1876 # transaction running
1876 # transaction running
1877 repo.dirstate.write(None)
1877 repo.dirstate.write(None)
1878 else:
1878 else:
1879 # discard all changes (including ones already written
1879 # discard all changes (including ones already written
1880 # out) in this transaction
1880 # out) in this transaction
1881 narrowspec.restorebackup(self, 'journal.narrowspec')
1881 narrowspec.restorebackup(self, 'journal.narrowspec')
1882 narrowspec.restorewcbackup(self, 'journal.narrowspec.dirstate')
1882 narrowspec.restorewcbackup(self, 'journal.narrowspec.dirstate')
1883 repo.dirstate.restorebackup(None, 'journal.dirstate')
1883 repo.dirstate.restorebackup(None, 'journal.dirstate')
1884
1884
1885 repo.invalidate(clearfilecache=True)
1885 repo.invalidate(clearfilecache=True)
1886
1886
1887 tr = transaction.transaction(rp, self.svfs, vfsmap,
1887 tr = transaction.transaction(rp, self.svfs, vfsmap,
1888 "journal",
1888 "journal",
1889 "undo",
1889 "undo",
1890 aftertrans(renames),
1890 aftertrans(renames),
1891 self.store.createmode,
1891 self.store.createmode,
1892 validator=validate,
1892 validator=validate,
1893 releasefn=releasefn,
1893 releasefn=releasefn,
1894 checkambigfiles=_cachedfiles,
1894 checkambigfiles=_cachedfiles,
1895 name=desc)
1895 name=desc)
1896 tr.changes['origrepolen'] = len(self)
1896 tr.changes['origrepolen'] = len(self)
1897 tr.changes['obsmarkers'] = set()
1897 tr.changes['obsmarkers'] = set()
1898 tr.changes['phases'] = {}
1898 tr.changes['phases'] = {}
1899 tr.changes['bookmarks'] = {}
1899 tr.changes['bookmarks'] = {}
1900
1900
1901 tr.hookargs['txnid'] = txnid
1901 tr.hookargs['txnid'] = txnid
1902 tr.hookargs['txnname'] = desc
1902 tr.hookargs['txnname'] = desc
1903 # note: writing the fncache only during finalize mean that the file is
1903 # note: writing the fncache only during finalize mean that the file is
1904 # outdated when running hooks. As fncache is used for streaming clone,
1904 # outdated when running hooks. As fncache is used for streaming clone,
1905 # this is not expected to break anything that happen during the hooks.
1905 # this is not expected to break anything that happen during the hooks.
1906 tr.addfinalize('flush-fncache', self.store.write)
1906 tr.addfinalize('flush-fncache', self.store.write)
1907 def txnclosehook(tr2):
1907 def txnclosehook(tr2):
1908 """To be run if transaction is successful, will schedule a hook run
1908 """To be run if transaction is successful, will schedule a hook run
1909 """
1909 """
1910 # Don't reference tr2 in hook() so we don't hold a reference.
1910 # Don't reference tr2 in hook() so we don't hold a reference.
1911 # This reduces memory consumption when there are multiple
1911 # This reduces memory consumption when there are multiple
1912 # transactions per lock. This can likely go away if issue5045
1912 # transactions per lock. This can likely go away if issue5045
1913 # fixes the function accumulation.
1913 # fixes the function accumulation.
1914 hookargs = tr2.hookargs
1914 hookargs = tr2.hookargs
1915
1915
1916 def hookfunc():
1916 def hookfunc():
1917 repo = reporef()
1917 repo = reporef()
1918 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1918 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1919 bmchanges = sorted(tr.changes['bookmarks'].items())
1919 bmchanges = sorted(tr.changes['bookmarks'].items())
1920 for name, (old, new) in bmchanges:
1920 for name, (old, new) in bmchanges:
1921 args = tr.hookargs.copy()
1921 args = tr.hookargs.copy()
1922 args.update(bookmarks.preparehookargs(name, old, new))
1922 args.update(bookmarks.preparehookargs(name, old, new))
1923 repo.hook('txnclose-bookmark', throw=False,
1923 repo.hook('txnclose-bookmark', throw=False,
1924 **pycompat.strkwargs(args))
1924 **pycompat.strkwargs(args))
1925
1925
1926 if hook.hashook(repo.ui, 'txnclose-phase'):
1926 if hook.hashook(repo.ui, 'txnclose-phase'):
1927 cl = repo.unfiltered().changelog
1927 cl = repo.unfiltered().changelog
1928 phasemv = sorted(tr.changes['phases'].items())
1928 phasemv = sorted(tr.changes['phases'].items())
1929 for rev, (old, new) in phasemv:
1929 for rev, (old, new) in phasemv:
1930 args = tr.hookargs.copy()
1930 args = tr.hookargs.copy()
1931 node = hex(cl.node(rev))
1931 node = hex(cl.node(rev))
1932 args.update(phases.preparehookargs(node, old, new))
1932 args.update(phases.preparehookargs(node, old, new))
1933 repo.hook('txnclose-phase', throw=False,
1933 repo.hook('txnclose-phase', throw=False,
1934 **pycompat.strkwargs(args))
1934 **pycompat.strkwargs(args))
1935
1935
1936 repo.hook('txnclose', throw=False,
1936 repo.hook('txnclose', throw=False,
1937 **pycompat.strkwargs(hookargs))
1937 **pycompat.strkwargs(hookargs))
1938 reporef()._afterlock(hookfunc)
1938 reporef()._afterlock(hookfunc)
1939 tr.addfinalize('txnclose-hook', txnclosehook)
1939 tr.addfinalize('txnclose-hook', txnclosehook)
1940 # Include a leading "-" to make it happen before the transaction summary
1940 # Include a leading "-" to make it happen before the transaction summary
1941 # reports registered via scmutil.registersummarycallback() whose names
1941 # reports registered via scmutil.registersummarycallback() whose names
1942 # are 00-txnreport etc. That way, the caches will be warm when the
1942 # are 00-txnreport etc. That way, the caches will be warm when the
1943 # callbacks run.
1943 # callbacks run.
1944 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1944 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1945 def txnaborthook(tr2):
1945 def txnaborthook(tr2):
1946 """To be run if transaction is aborted
1946 """To be run if transaction is aborted
1947 """
1947 """
1948 reporef().hook('txnabort', throw=False,
1948 reporef().hook('txnabort', throw=False,
1949 **pycompat.strkwargs(tr2.hookargs))
1949 **pycompat.strkwargs(tr2.hookargs))
1950 tr.addabort('txnabort-hook', txnaborthook)
1950 tr.addabort('txnabort-hook', txnaborthook)
1951 # avoid eager cache invalidation. in-memory data should be identical
1951 # avoid eager cache invalidation. in-memory data should be identical
1952 # to stored data if transaction has no error.
1952 # to stored data if transaction has no error.
1953 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1953 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1954 self._transref = weakref.ref(tr)
1954 self._transref = weakref.ref(tr)
1955 scmutil.registersummarycallback(self, tr, desc)
1955 scmutil.registersummarycallback(self, tr, desc)
1956 return tr
1956 return tr
1957
1957
1958 def _journalfiles(self):
1958 def _journalfiles(self):
1959 return ((self.svfs, 'journal'),
1959 return ((self.svfs, 'journal'),
1960 (self.svfs, 'journal.narrowspec'),
1960 (self.svfs, 'journal.narrowspec'),
1961 (self.vfs, 'journal.narrowspec.dirstate'),
1961 (self.vfs, 'journal.narrowspec.dirstate'),
1962 (self.vfs, 'journal.dirstate'),
1962 (self.vfs, 'journal.dirstate'),
1963 (self.vfs, 'journal.branch'),
1963 (self.vfs, 'journal.branch'),
1964 (self.vfs, 'journal.desc'),
1964 (self.vfs, 'journal.desc'),
1965 (self.vfs, 'journal.bookmarks'),
1965 (self.vfs, 'journal.bookmarks'),
1966 (self.svfs, 'journal.phaseroots'))
1966 (self.svfs, 'journal.phaseroots'))
1967
1967
1968 def undofiles(self):
1968 def undofiles(self):
1969 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1969 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1970
1970
1971 @unfilteredmethod
1971 @unfilteredmethod
1972 def _writejournal(self, desc):
1972 def _writejournal(self, desc):
1973 self.dirstate.savebackup(None, 'journal.dirstate')
1973 self.dirstate.savebackup(None, 'journal.dirstate')
1974 narrowspec.savewcbackup(self, 'journal.narrowspec.dirstate')
1974 narrowspec.savewcbackup(self, 'journal.narrowspec.dirstate')
1975 narrowspec.savebackup(self, 'journal.narrowspec')
1975 narrowspec.savebackup(self, 'journal.narrowspec')
1976 self.vfs.write("journal.branch",
1976 self.vfs.write("journal.branch",
1977 encoding.fromlocal(self.dirstate.branch()))
1977 encoding.fromlocal(self.dirstate.branch()))
1978 self.vfs.write("journal.desc",
1978 self.vfs.write("journal.desc",
1979 "%d\n%s\n" % (len(self), desc))
1979 "%d\n%s\n" % (len(self), desc))
1980 self.vfs.write("journal.bookmarks",
1980 self.vfs.write("journal.bookmarks",
1981 self.vfs.tryread("bookmarks"))
1981 self.vfs.tryread("bookmarks"))
1982 self.svfs.write("journal.phaseroots",
1982 self.svfs.write("journal.phaseroots",
1983 self.svfs.tryread("phaseroots"))
1983 self.svfs.tryread("phaseroots"))
1984
1984
1985 def recover(self):
1985 def recover(self):
1986 with self.lock():
1986 with self.lock():
1987 if self.svfs.exists("journal"):
1987 if self.svfs.exists("journal"):
1988 self.ui.status(_("rolling back interrupted transaction\n"))
1988 self.ui.status(_("rolling back interrupted transaction\n"))
1989 vfsmap = {'': self.svfs,
1989 vfsmap = {'': self.svfs,
1990 'plain': self.vfs,}
1990 'plain': self.vfs,}
1991 transaction.rollback(self.svfs, vfsmap, "journal",
1991 transaction.rollback(self.svfs, vfsmap, "journal",
1992 self.ui.warn,
1992 self.ui.warn,
1993 checkambigfiles=_cachedfiles)
1993 checkambigfiles=_cachedfiles)
1994 self.invalidate()
1994 self.invalidate()
1995 return True
1995 return True
1996 else:
1996 else:
1997 self.ui.warn(_("no interrupted transaction available\n"))
1997 self.ui.warn(_("no interrupted transaction available\n"))
1998 return False
1998 return False
1999
1999
2000 def rollback(self, dryrun=False, force=False):
2000 def rollback(self, dryrun=False, force=False):
2001 wlock = lock = dsguard = None
2001 wlock = lock = dsguard = None
2002 try:
2002 try:
2003 wlock = self.wlock()
2003 wlock = self.wlock()
2004 lock = self.lock()
2004 lock = self.lock()
2005 if self.svfs.exists("undo"):
2005 if self.svfs.exists("undo"):
2006 dsguard = dirstateguard.dirstateguard(self, 'rollback')
2006 dsguard = dirstateguard.dirstateguard(self, 'rollback')
2007
2007
2008 return self._rollback(dryrun, force, dsguard)
2008 return self._rollback(dryrun, force, dsguard)
2009 else:
2009 else:
2010 self.ui.warn(_("no rollback information available\n"))
2010 self.ui.warn(_("no rollback information available\n"))
2011 return 1
2011 return 1
2012 finally:
2012 finally:
2013 release(dsguard, lock, wlock)
2013 release(dsguard, lock, wlock)
2014
2014
2015 @unfilteredmethod # Until we get smarter cache management
2015 @unfilteredmethod # Until we get smarter cache management
2016 def _rollback(self, dryrun, force, dsguard):
2016 def _rollback(self, dryrun, force, dsguard):
2017 ui = self.ui
2017 ui = self.ui
2018 try:
2018 try:
2019 args = self.vfs.read('undo.desc').splitlines()
2019 args = self.vfs.read('undo.desc').splitlines()
2020 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2020 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2021 if len(args) >= 3:
2021 if len(args) >= 3:
2022 detail = args[2]
2022 detail = args[2]
2023 oldtip = oldlen - 1
2023 oldtip = oldlen - 1
2024
2024
2025 if detail and ui.verbose:
2025 if detail and ui.verbose:
2026 msg = (_('repository tip rolled back to revision %d'
2026 msg = (_('repository tip rolled back to revision %d'
2027 ' (undo %s: %s)\n')
2027 ' (undo %s: %s)\n')
2028 % (oldtip, desc, detail))
2028 % (oldtip, desc, detail))
2029 else:
2029 else:
2030 msg = (_('repository tip rolled back to revision %d'
2030 msg = (_('repository tip rolled back to revision %d'
2031 ' (undo %s)\n')
2031 ' (undo %s)\n')
2032 % (oldtip, desc))
2032 % (oldtip, desc))
2033 except IOError:
2033 except IOError:
2034 msg = _('rolling back unknown transaction\n')
2034 msg = _('rolling back unknown transaction\n')
2035 desc = None
2035 desc = None
2036
2036
2037 if not force and self['.'] != self['tip'] and desc == 'commit':
2037 if not force and self['.'] != self['tip'] and desc == 'commit':
2038 raise error.Abort(
2038 raise error.Abort(
2039 _('rollback of last commit while not checked out '
2039 _('rollback of last commit while not checked out '
2040 'may lose data'), hint=_('use -f to force'))
2040 'may lose data'), hint=_('use -f to force'))
2041
2041
2042 ui.status(msg)
2042 ui.status(msg)
2043 if dryrun:
2043 if dryrun:
2044 return 0
2044 return 0
2045
2045
2046 parents = self.dirstate.parents()
2046 parents = self.dirstate.parents()
2047 self.destroying()
2047 self.destroying()
2048 vfsmap = {'plain': self.vfs, '': self.svfs}
2048 vfsmap = {'plain': self.vfs, '': self.svfs}
2049 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
2049 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
2050 checkambigfiles=_cachedfiles)
2050 checkambigfiles=_cachedfiles)
2051 if self.vfs.exists('undo.bookmarks'):
2051 if self.vfs.exists('undo.bookmarks'):
2052 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
2052 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
2053 if self.svfs.exists('undo.phaseroots'):
2053 if self.svfs.exists('undo.phaseroots'):
2054 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
2054 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
2055 self.invalidate()
2055 self.invalidate()
2056
2056
2057 parentgone = any(p not in self.changelog.nodemap for p in parents)
2057 parentgone = any(p not in self.changelog.nodemap for p in parents)
2058 if parentgone:
2058 if parentgone:
2059 # prevent dirstateguard from overwriting already restored one
2059 # prevent dirstateguard from overwriting already restored one
2060 dsguard.close()
2060 dsguard.close()
2061
2061
2062 narrowspec.restorebackup(self, 'undo.narrowspec')
2062 narrowspec.restorebackup(self, 'undo.narrowspec')
2063 narrowspec.restorewcbackup(self, 'undo.narrowspec.dirstate')
2063 narrowspec.restorewcbackup(self, 'undo.narrowspec.dirstate')
2064 self.dirstate.restorebackup(None, 'undo.dirstate')
2064 self.dirstate.restorebackup(None, 'undo.dirstate')
2065 try:
2065 try:
2066 branch = self.vfs.read('undo.branch')
2066 branch = self.vfs.read('undo.branch')
2067 self.dirstate.setbranch(encoding.tolocal(branch))
2067 self.dirstate.setbranch(encoding.tolocal(branch))
2068 except IOError:
2068 except IOError:
2069 ui.warn(_('named branch could not be reset: '
2069 ui.warn(_('named branch could not be reset: '
2070 'current branch is still \'%s\'\n')
2070 'current branch is still \'%s\'\n')
2071 % self.dirstate.branch())
2071 % self.dirstate.branch())
2072
2072
2073 parents = tuple([p.rev() for p in self[None].parents()])
2073 parents = tuple([p.rev() for p in self[None].parents()])
2074 if len(parents) > 1:
2074 if len(parents) > 1:
2075 ui.status(_('working directory now based on '
2075 ui.status(_('working directory now based on '
2076 'revisions %d and %d\n') % parents)
2076 'revisions %d and %d\n') % parents)
2077 else:
2077 else:
2078 ui.status(_('working directory now based on '
2078 ui.status(_('working directory now based on '
2079 'revision %d\n') % parents)
2079 'revision %d\n') % parents)
2080 mergemod.mergestate.clean(self, self['.'].node())
2080 mergemod.mergestate.clean(self, self['.'].node())
2081
2081
2082 # TODO: if we know which new heads may result from this rollback, pass
2082 # TODO: if we know which new heads may result from this rollback, pass
2083 # them to destroy(), which will prevent the branchhead cache from being
2083 # them to destroy(), which will prevent the branchhead cache from being
2084 # invalidated.
2084 # invalidated.
2085 self.destroyed()
2085 self.destroyed()
2086 return 0
2086 return 0
2087
2087
2088 def _buildcacheupdater(self, newtransaction):
2088 def _buildcacheupdater(self, newtransaction):
2089 """called during transaction to build the callback updating cache
2089 """called during transaction to build the callback updating cache
2090
2090
2091 Lives on the repository to help extension who might want to augment
2091 Lives on the repository to help extension who might want to augment
2092 this logic. For this purpose, the created transaction is passed to the
2092 this logic. For this purpose, the created transaction is passed to the
2093 method.
2093 method.
2094 """
2094 """
2095 # we must avoid cyclic reference between repo and transaction.
2095 # we must avoid cyclic reference between repo and transaction.
2096 reporef = weakref.ref(self)
2096 reporef = weakref.ref(self)
2097 def updater(tr):
2097 def updater(tr):
2098 repo = reporef()
2098 repo = reporef()
2099 repo.updatecaches(tr)
2099 repo.updatecaches(tr)
2100 return updater
2100 return updater
2101
2101
2102 @unfilteredmethod
2102 @unfilteredmethod
2103 def updatecaches(self, tr=None, full=False):
2103 def updatecaches(self, tr=None, full=False):
2104 """warm appropriate caches
2104 """warm appropriate caches
2105
2105
2106 If this function is called after a transaction closed. The transaction
2106 If this function is called after a transaction closed. The transaction
2107 will be available in the 'tr' argument. This can be used to selectively
2107 will be available in the 'tr' argument. This can be used to selectively
2108 update caches relevant to the changes in that transaction.
2108 update caches relevant to the changes in that transaction.
2109
2109
2110 If 'full' is set, make sure all caches the function knows about have
2110 If 'full' is set, make sure all caches the function knows about have
2111 up-to-date data. Even the ones usually loaded more lazily.
2111 up-to-date data. Even the ones usually loaded more lazily.
2112 """
2112 """
2113 if tr is not None and tr.hookargs.get('source') == 'strip':
2113 if tr is not None and tr.hookargs.get('source') == 'strip':
2114 # During strip, many caches are invalid but
2114 # During strip, many caches are invalid but
2115 # later call to `destroyed` will refresh them.
2115 # later call to `destroyed` will refresh them.
2116 return
2116 return
2117
2117
2118 if tr is None or tr.changes['origrepolen'] < len(self):
2118 if tr is None or tr.changes['origrepolen'] < len(self):
2119 # accessing the 'ser ved' branchmap should refresh all the others,
2119 # accessing the 'ser ved' branchmap should refresh all the others,
2120 self.ui.debug('updating the branch cache\n')
2120 self.ui.debug('updating the branch cache\n')
2121 self.filtered('served').branchmap()
2121 self.filtered('served').branchmap()
2122 self.filtered('served.hidden').branchmap()
2122 self.filtered('served.hidden').branchmap()
2123
2123
2124 if full:
2124 if full:
2125 unfi = self.unfiltered()
2125 unfi = self.unfiltered()
2126 rbc = unfi.revbranchcache()
2126 rbc = unfi.revbranchcache()
2127 for r in unfi.changelog:
2127 for r in unfi.changelog:
2128 rbc.branchinfo(r)
2128 rbc.branchinfo(r)
2129 rbc.write()
2129 rbc.write()
2130
2130
2131 # ensure the working copy parents are in the manifestfulltextcache
2131 # ensure the working copy parents are in the manifestfulltextcache
2132 for ctx in self['.'].parents():
2132 for ctx in self['.'].parents():
2133 ctx.manifest() # accessing the manifest is enough
2133 ctx.manifest() # accessing the manifest is enough
2134
2134
2135 # accessing fnode cache warms the cache
2135 # accessing fnode cache warms the cache
2136 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2136 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2137 # accessing tags warm the cache
2137 # accessing tags warm the cache
2138 self.tags()
2138 self.tags()
2139 self.filtered('served').tags()
2139 self.filtered('served').tags()
2140
2140
2141 def invalidatecaches(self):
2141 def invalidatecaches(self):
2142
2142
2143 if r'_tagscache' in vars(self):
2143 if r'_tagscache' in vars(self):
2144 # can't use delattr on proxy
2144 # can't use delattr on proxy
2145 del self.__dict__[r'_tagscache']
2145 del self.__dict__[r'_tagscache']
2146
2146
2147 self._branchcaches.clear()
2147 self._branchcaches.clear()
2148 self.invalidatevolatilesets()
2148 self.invalidatevolatilesets()
2149 self._sparsesignaturecache.clear()
2149 self._sparsesignaturecache.clear()
2150
2150
2151 def invalidatevolatilesets(self):
2151 def invalidatevolatilesets(self):
2152 self.filteredrevcache.clear()
2152 self.filteredrevcache.clear()
2153 obsolete.clearobscaches(self)
2153 obsolete.clearobscaches(self)
2154
2154
2155 def invalidatedirstate(self):
2155 def invalidatedirstate(self):
2156 '''Invalidates the dirstate, causing the next call to dirstate
2156 '''Invalidates the dirstate, causing the next call to dirstate
2157 to check if it was modified since the last time it was read,
2157 to check if it was modified since the last time it was read,
2158 rereading it if it has.
2158 rereading it if it has.
2159
2159
2160 This is different to dirstate.invalidate() that it doesn't always
2160 This is different to dirstate.invalidate() that it doesn't always
2161 rereads the dirstate. Use dirstate.invalidate() if you want to
2161 rereads the dirstate. Use dirstate.invalidate() if you want to
2162 explicitly read the dirstate again (i.e. restoring it to a previous
2162 explicitly read the dirstate again (i.e. restoring it to a previous
2163 known good state).'''
2163 known good state).'''
2164 if hasunfilteredcache(self, r'dirstate'):
2164 if hasunfilteredcache(self, r'dirstate'):
2165 for k in self.dirstate._filecache:
2165 for k in self.dirstate._filecache:
2166 try:
2166 try:
2167 delattr(self.dirstate, k)
2167 delattr(self.dirstate, k)
2168 except AttributeError:
2168 except AttributeError:
2169 pass
2169 pass
2170 delattr(self.unfiltered(), r'dirstate')
2170 delattr(self.unfiltered(), r'dirstate')
2171
2171
2172 def invalidate(self, clearfilecache=False):
2172 def invalidate(self, clearfilecache=False):
2173 '''Invalidates both store and non-store parts other than dirstate
2173 '''Invalidates both store and non-store parts other than dirstate
2174
2174
2175 If a transaction is running, invalidation of store is omitted,
2175 If a transaction is running, invalidation of store is omitted,
2176 because discarding in-memory changes might cause inconsistency
2176 because discarding in-memory changes might cause inconsistency
2177 (e.g. incomplete fncache causes unintentional failure, but
2177 (e.g. incomplete fncache causes unintentional failure, but
2178 redundant one doesn't).
2178 redundant one doesn't).
2179 '''
2179 '''
2180 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2180 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2181 for k in list(self._filecache.keys()):
2181 for k in list(self._filecache.keys()):
2182 # dirstate is invalidated separately in invalidatedirstate()
2182 # dirstate is invalidated separately in invalidatedirstate()
2183 if k == 'dirstate':
2183 if k == 'dirstate':
2184 continue
2184 continue
2185 if (k == 'changelog' and
2185 if (k == 'changelog' and
2186 self.currenttransaction() and
2186 self.currenttransaction() and
2187 self.changelog._delayed):
2187 self.changelog._delayed):
2188 # The changelog object may store unwritten revisions. We don't
2188 # The changelog object may store unwritten revisions. We don't
2189 # want to lose them.
2189 # want to lose them.
2190 # TODO: Solve the problem instead of working around it.
2190 # TODO: Solve the problem instead of working around it.
2191 continue
2191 continue
2192
2192
2193 if clearfilecache:
2193 if clearfilecache:
2194 del self._filecache[k]
2194 del self._filecache[k]
2195 try:
2195 try:
2196 delattr(unfiltered, k)
2196 delattr(unfiltered, k)
2197 except AttributeError:
2197 except AttributeError:
2198 pass
2198 pass
2199 self.invalidatecaches()
2199 self.invalidatecaches()
2200 if not self.currenttransaction():
2200 if not self.currenttransaction():
2201 # TODO: Changing contents of store outside transaction
2201 # TODO: Changing contents of store outside transaction
2202 # causes inconsistency. We should make in-memory store
2202 # causes inconsistency. We should make in-memory store
2203 # changes detectable, and abort if changed.
2203 # changes detectable, and abort if changed.
2204 self.store.invalidatecaches()
2204 self.store.invalidatecaches()
2205
2205
2206 def invalidateall(self):
2206 def invalidateall(self):
2207 '''Fully invalidates both store and non-store parts, causing the
2207 '''Fully invalidates both store and non-store parts, causing the
2208 subsequent operation to reread any outside changes.'''
2208 subsequent operation to reread any outside changes.'''
2209 # extension should hook this to invalidate its caches
2209 # extension should hook this to invalidate its caches
2210 self.invalidate()
2210 self.invalidate()
2211 self.invalidatedirstate()
2211 self.invalidatedirstate()
2212
2212
2213 @unfilteredmethod
2213 @unfilteredmethod
2214 def _refreshfilecachestats(self, tr):
2214 def _refreshfilecachestats(self, tr):
2215 """Reload stats of cached files so that they are flagged as valid"""
2215 """Reload stats of cached files so that they are flagged as valid"""
2216 for k, ce in self._filecache.items():
2216 for k, ce in self._filecache.items():
2217 k = pycompat.sysstr(k)
2217 k = pycompat.sysstr(k)
2218 if k == r'dirstate' or k not in self.__dict__:
2218 if k == r'dirstate' or k not in self.__dict__:
2219 continue
2219 continue
2220 ce.refresh()
2220 ce.refresh()
2221
2221
2222 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
2222 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
2223 inheritchecker=None, parentenvvar=None):
2223 inheritchecker=None, parentenvvar=None):
2224 parentlock = None
2224 parentlock = None
2225 # the contents of parentenvvar are used by the underlying lock to
2225 # the contents of parentenvvar are used by the underlying lock to
2226 # determine whether it can be inherited
2226 # determine whether it can be inherited
2227 if parentenvvar is not None:
2227 if parentenvvar is not None:
2228 parentlock = encoding.environ.get(parentenvvar)
2228 parentlock = encoding.environ.get(parentenvvar)
2229
2229
2230 timeout = 0
2230 timeout = 0
2231 warntimeout = 0
2231 warntimeout = 0
2232 if wait:
2232 if wait:
2233 timeout = self.ui.configint("ui", "timeout")
2233 timeout = self.ui.configint("ui", "timeout")
2234 warntimeout = self.ui.configint("ui", "timeout.warn")
2234 warntimeout = self.ui.configint("ui", "timeout.warn")
2235 # internal config: ui.signal-safe-lock
2235 # internal config: ui.signal-safe-lock
2236 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
2236 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
2237
2237
2238 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
2238 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
2239 releasefn=releasefn,
2239 releasefn=releasefn,
2240 acquirefn=acquirefn, desc=desc,
2240 acquirefn=acquirefn, desc=desc,
2241 inheritchecker=inheritchecker,
2241 inheritchecker=inheritchecker,
2242 parentlock=parentlock,
2242 parentlock=parentlock,
2243 signalsafe=signalsafe)
2243 signalsafe=signalsafe)
2244 return l
2244 return l
2245
2245
2246 def _afterlock(self, callback):
2246 def _afterlock(self, callback):
2247 """add a callback to be run when the repository is fully unlocked
2247 """add a callback to be run when the repository is fully unlocked
2248
2248
2249 The callback will be executed when the outermost lock is released
2249 The callback will be executed when the outermost lock is released
2250 (with wlock being higher level than 'lock')."""
2250 (with wlock being higher level than 'lock')."""
2251 for ref in (self._wlockref, self._lockref):
2251 for ref in (self._wlockref, self._lockref):
2252 l = ref and ref()
2252 l = ref and ref()
2253 if l and l.held:
2253 if l and l.held:
2254 l.postrelease.append(callback)
2254 l.postrelease.append(callback)
2255 break
2255 break
2256 else: # no lock have been found.
2256 else: # no lock have been found.
2257 callback()
2257 callback()
2258
2258
2259 def lock(self, wait=True):
2259 def lock(self, wait=True):
2260 '''Lock the repository store (.hg/store) and return a weak reference
2260 '''Lock the repository store (.hg/store) and return a weak reference
2261 to the lock. Use this before modifying the store (e.g. committing or
2261 to the lock. Use this before modifying the store (e.g. committing or
2262 stripping). If you are opening a transaction, get a lock as well.)
2262 stripping). If you are opening a transaction, get a lock as well.)
2263
2263
2264 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2264 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2265 'wlock' first to avoid a dead-lock hazard.'''
2265 'wlock' first to avoid a dead-lock hazard.'''
2266 l = self._currentlock(self._lockref)
2266 l = self._currentlock(self._lockref)
2267 if l is not None:
2267 if l is not None:
2268 l.lock()
2268 l.lock()
2269 return l
2269 return l
2270
2270
2271 l = self._lock(vfs=self.svfs,
2271 l = self._lock(vfs=self.svfs,
2272 lockname="lock",
2272 lockname="lock",
2273 wait=wait,
2273 wait=wait,
2274 releasefn=None,
2274 releasefn=None,
2275 acquirefn=self.invalidate,
2275 acquirefn=self.invalidate,
2276 desc=_('repository %s') % self.origroot)
2276 desc=_('repository %s') % self.origroot)
2277 self._lockref = weakref.ref(l)
2277 self._lockref = weakref.ref(l)
2278 return l
2278 return l
2279
2279
2280 def _wlockchecktransaction(self):
2280 def _wlockchecktransaction(self):
2281 if self.currenttransaction() is not None:
2281 if self.currenttransaction() is not None:
2282 raise error.LockInheritanceContractViolation(
2282 raise error.LockInheritanceContractViolation(
2283 'wlock cannot be inherited in the middle of a transaction')
2283 'wlock cannot be inherited in the middle of a transaction')
2284
2284
2285 def wlock(self, wait=True):
2285 def wlock(self, wait=True):
2286 '''Lock the non-store parts of the repository (everything under
2286 '''Lock the non-store parts of the repository (everything under
2287 .hg except .hg/store) and return a weak reference to the lock.
2287 .hg except .hg/store) and return a weak reference to the lock.
2288
2288
2289 Use this before modifying files in .hg.
2289 Use this before modifying files in .hg.
2290
2290
2291 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2291 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2292 'wlock' first to avoid a dead-lock hazard.'''
2292 'wlock' first to avoid a dead-lock hazard.'''
2293 l = self._wlockref and self._wlockref()
2293 l = self._wlockref and self._wlockref()
2294 if l is not None and l.held:
2294 if l is not None and l.held:
2295 l.lock()
2295 l.lock()
2296 return l
2296 return l
2297
2297
2298 # We do not need to check for non-waiting lock acquisition. Such
2298 # We do not need to check for non-waiting lock acquisition. Such
2299 # acquisition would not cause dead-lock as they would just fail.
2299 # acquisition would not cause dead-lock as they would just fail.
2300 if wait and (self.ui.configbool('devel', 'all-warnings')
2300 if wait and (self.ui.configbool('devel', 'all-warnings')
2301 or self.ui.configbool('devel', 'check-locks')):
2301 or self.ui.configbool('devel', 'check-locks')):
2302 if self._currentlock(self._lockref) is not None:
2302 if self._currentlock(self._lockref) is not None:
2303 self.ui.develwarn('"wlock" acquired after "lock"')
2303 self.ui.develwarn('"wlock" acquired after "lock"')
2304
2304
2305 def unlock():
2305 def unlock():
2306 if self.dirstate.pendingparentchange():
2306 if self.dirstate.pendingparentchange():
2307 self.dirstate.invalidate()
2307 self.dirstate.invalidate()
2308 else:
2308 else:
2309 self.dirstate.write(None)
2309 self.dirstate.write(None)
2310
2310
2311 self._filecache['dirstate'].refresh()
2311 self._filecache['dirstate'].refresh()
2312
2312
2313 l = self._lock(self.vfs, "wlock", wait, unlock,
2313 l = self._lock(self.vfs, "wlock", wait, unlock,
2314 self.invalidatedirstate, _('working directory of %s') %
2314 self.invalidatedirstate, _('working directory of %s') %
2315 self.origroot,
2315 self.origroot,
2316 inheritchecker=self._wlockchecktransaction,
2316 inheritchecker=self._wlockchecktransaction,
2317 parentenvvar='HG_WLOCK_LOCKER')
2317 parentenvvar='HG_WLOCK_LOCKER')
2318 self._wlockref = weakref.ref(l)
2318 self._wlockref = weakref.ref(l)
2319 return l
2319 return l
2320
2320
2321 def _currentlock(self, lockref):
2321 def _currentlock(self, lockref):
2322 """Returns the lock if it's held, or None if it's not."""
2322 """Returns the lock if it's held, or None if it's not."""
2323 if lockref is None:
2323 if lockref is None:
2324 return None
2324 return None
2325 l = lockref()
2325 l = lockref()
2326 if l is None or not l.held:
2326 if l is None or not l.held:
2327 return None
2327 return None
2328 return l
2328 return l
2329
2329
2330 def currentwlock(self):
2330 def currentwlock(self):
2331 """Returns the wlock if it's held, or None if it's not."""
2331 """Returns the wlock if it's held, or None if it's not."""
2332 return self._currentlock(self._wlockref)
2332 return self._currentlock(self._wlockref)
2333
2333
2334 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist,
2334 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist,
2335 includecopymeta):
2335 includecopymeta):
2336 """
2336 """
2337 commit an individual file as part of a larger transaction
2337 commit an individual file as part of a larger transaction
2338 """
2338 """
2339
2339
2340 fname = fctx.path()
2340 fname = fctx.path()
2341 fparent1 = manifest1.get(fname, nullid)
2341 fparent1 = manifest1.get(fname, nullid)
2342 fparent2 = manifest2.get(fname, nullid)
2342 fparent2 = manifest2.get(fname, nullid)
2343 if isinstance(fctx, context.filectx):
2343 if isinstance(fctx, context.filectx):
2344 node = fctx.filenode()
2344 node = fctx.filenode()
2345 if node in [fparent1, fparent2]:
2345 if node in [fparent1, fparent2]:
2346 self.ui.debug('reusing %s filelog entry\n' % fname)
2346 self.ui.debug('reusing %s filelog entry\n' % fname)
2347 if manifest1.flags(fname) != fctx.flags():
2347 if manifest1.flags(fname) != fctx.flags():
2348 changelist.append(fname)
2348 changelist.append(fname)
2349 return node
2349 return node
2350
2350
2351 flog = self.file(fname)
2351 flog = self.file(fname)
2352 meta = {}
2352 meta = {}
2353 cfname = fctx.copysource()
2353 cfname = fctx.copysource()
2354 if cfname and cfname != fname:
2354 if cfname and cfname != fname:
2355 # Mark the new revision of this file as a copy of another
2355 # Mark the new revision of this file as a copy of another
2356 # file. This copy data will effectively act as a parent
2356 # file. This copy data will effectively act as a parent
2357 # of this new revision. If this is a merge, the first
2357 # of this new revision. If this is a merge, the first
2358 # parent will be the nullid (meaning "look up the copy data")
2358 # parent will be the nullid (meaning "look up the copy data")
2359 # and the second one will be the other parent. For example:
2359 # and the second one will be the other parent. For example:
2360 #
2360 #
2361 # 0 --- 1 --- 3 rev1 changes file foo
2361 # 0 --- 1 --- 3 rev1 changes file foo
2362 # \ / rev2 renames foo to bar and changes it
2362 # \ / rev2 renames foo to bar and changes it
2363 # \- 2 -/ rev3 should have bar with all changes and
2363 # \- 2 -/ rev3 should have bar with all changes and
2364 # should record that bar descends from
2364 # should record that bar descends from
2365 # bar in rev2 and foo in rev1
2365 # bar in rev2 and foo in rev1
2366 #
2366 #
2367 # this allows this merge to succeed:
2367 # this allows this merge to succeed:
2368 #
2368 #
2369 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2369 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
2370 # \ / merging rev3 and rev4 should use bar@rev2
2370 # \ / merging rev3 and rev4 should use bar@rev2
2371 # \- 2 --- 4 as the merge base
2371 # \- 2 --- 4 as the merge base
2372 #
2372 #
2373
2373
2374 cnode = manifest1.get(cfname)
2374 cnode = manifest1.get(cfname)
2375 newfparent = fparent2
2375 newfparent = fparent2
2376
2376
2377 if manifest2: # branch merge
2377 if manifest2: # branch merge
2378 if fparent2 == nullid or cnode is None: # copied on remote side
2378 if fparent2 == nullid or cnode is None: # copied on remote side
2379 if cfname in manifest2:
2379 if cfname in manifest2:
2380 cnode = manifest2[cfname]
2380 cnode = manifest2[cfname]
2381 newfparent = fparent1
2381 newfparent = fparent1
2382
2382
2383 # Here, we used to search backwards through history to try to find
2383 # Here, we used to search backwards through history to try to find
2384 # where the file copy came from if the source of a copy was not in
2384 # where the file copy came from if the source of a copy was not in
2385 # the parent directory. However, this doesn't actually make sense to
2385 # the parent directory. However, this doesn't actually make sense to
2386 # do (what does a copy from something not in your working copy even
2386 # do (what does a copy from something not in your working copy even
2387 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2387 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
2388 # the user that copy information was dropped, so if they didn't
2388 # the user that copy information was dropped, so if they didn't
2389 # expect this outcome it can be fixed, but this is the correct
2389 # expect this outcome it can be fixed, but this is the correct
2390 # behavior in this circumstance.
2390 # behavior in this circumstance.
2391
2391
2392 if cnode:
2392 if cnode:
2393 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(cnode)))
2393 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(cnode)))
2394 if includecopymeta:
2394 if includecopymeta:
2395 meta["copy"] = cfname
2395 meta["copy"] = cfname
2396 meta["copyrev"] = hex(cnode)
2396 meta["copyrev"] = hex(cnode)
2397 fparent1, fparent2 = nullid, newfparent
2397 fparent1, fparent2 = nullid, newfparent
2398 else:
2398 else:
2399 self.ui.warn(_("warning: can't find ancestor for '%s' "
2399 self.ui.warn(_("warning: can't find ancestor for '%s' "
2400 "copied from '%s'!\n") % (fname, cfname))
2400 "copied from '%s'!\n") % (fname, cfname))
2401
2401
2402 elif fparent1 == nullid:
2402 elif fparent1 == nullid:
2403 fparent1, fparent2 = fparent2, nullid
2403 fparent1, fparent2 = fparent2, nullid
2404 elif fparent2 != nullid:
2404 elif fparent2 != nullid:
2405 # is one parent an ancestor of the other?
2405 # is one parent an ancestor of the other?
2406 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2406 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
2407 if fparent1 in fparentancestors:
2407 if fparent1 in fparentancestors:
2408 fparent1, fparent2 = fparent2, nullid
2408 fparent1, fparent2 = fparent2, nullid
2409 elif fparent2 in fparentancestors:
2409 elif fparent2 in fparentancestors:
2410 fparent2 = nullid
2410 fparent2 = nullid
2411
2411
2412 # is the file changed?
2412 # is the file changed?
2413 text = fctx.data()
2413 text = fctx.data()
2414 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2414 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
2415 changelist.append(fname)
2415 changelist.append(fname)
2416 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2416 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
2417 # are just the flags changed during merge?
2417 # are just the flags changed during merge?
2418 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2418 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
2419 changelist.append(fname)
2419 changelist.append(fname)
2420
2420
2421 return fparent1
2421 return fparent1
2422
2422
2423 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
2423 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
2424 """check for commit arguments that aren't committable"""
2424 """check for commit arguments that aren't committable"""
2425 if match.isexact() or match.prefix():
2425 if match.isexact() or match.prefix():
2426 matched = set(status.modified + status.added + status.removed)
2426 matched = set(status.modified + status.added + status.removed)
2427
2427
2428 for f in match.files():
2428 for f in match.files():
2429 f = self.dirstate.normalize(f)
2429 f = self.dirstate.normalize(f)
2430 if f == '.' or f in matched or f in wctx.substate:
2430 if f == '.' or f in matched or f in wctx.substate:
2431 continue
2431 continue
2432 if f in status.deleted:
2432 if f in status.deleted:
2433 fail(f, _('file not found!'))
2433 fail(f, _('file not found!'))
2434 if f in vdirs: # visited directory
2434 if f in vdirs: # visited directory
2435 d = f + '/'
2435 d = f + '/'
2436 for mf in matched:
2436 for mf in matched:
2437 if mf.startswith(d):
2437 if mf.startswith(d):
2438 break
2438 break
2439 else:
2439 else:
2440 fail(f, _("no match under directory!"))
2440 fail(f, _("no match under directory!"))
2441 elif f not in self.dirstate:
2441 elif f not in self.dirstate:
2442 fail(f, _("file not tracked!"))
2442 fail(f, _("file not tracked!"))
2443
2443
2444 @unfilteredmethod
2444 @unfilteredmethod
2445 def commit(self, text="", user=None, date=None, match=None, force=False,
2445 def commit(self, text="", user=None, date=None, match=None, force=False,
2446 editor=False, extra=None):
2446 editor=False, extra=None):
2447 """Add a new revision to current repository.
2447 """Add a new revision to current repository.
2448
2448
2449 Revision information is gathered from the working directory,
2449 Revision information is gathered from the working directory,
2450 match can be used to filter the committed files. If editor is
2450 match can be used to filter the committed files. If editor is
2451 supplied, it is called to get a commit message.
2451 supplied, it is called to get a commit message.
2452 """
2452 """
2453 if extra is None:
2453 if extra is None:
2454 extra = {}
2454 extra = {}
2455
2455
2456 def fail(f, msg):
2456 def fail(f, msg):
2457 raise error.Abort('%s: %s' % (f, msg))
2457 raise error.Abort('%s: %s' % (f, msg))
2458
2458
2459 if not match:
2459 if not match:
2460 match = matchmod.always()
2460 match = matchmod.always()
2461
2461
2462 if not force:
2462 if not force:
2463 vdirs = []
2463 vdirs = []
2464 match.explicitdir = vdirs.append
2464 match.explicitdir = vdirs.append
2465 match.bad = fail
2465 match.bad = fail
2466
2466
2467 # lock() for recent changelog (see issue4368)
2467 # lock() for recent changelog (see issue4368)
2468 with self.wlock(), self.lock():
2468 with self.wlock(), self.lock():
2469 wctx = self[None]
2469 wctx = self[None]
2470 merge = len(wctx.parents()) > 1
2470 merge = len(wctx.parents()) > 1
2471
2471
2472 if not force and merge and not match.always():
2472 if not force and merge and not match.always():
2473 raise error.Abort(_('cannot partially commit a merge '
2473 raise error.Abort(_('cannot partially commit a merge '
2474 '(do not specify files or patterns)'))
2474 '(do not specify files or patterns)'))
2475
2475
2476 status = self.status(match=match, clean=force)
2476 status = self.status(match=match, clean=force)
2477 if force:
2477 if force:
2478 status.modified.extend(status.clean) # mq may commit clean files
2478 status.modified.extend(status.clean) # mq may commit clean files
2479
2479
2480 # check subrepos
2480 # check subrepos
2481 subs, commitsubs, newstate = subrepoutil.precommit(
2481 subs, commitsubs, newstate = subrepoutil.precommit(
2482 self.ui, wctx, status, match, force=force)
2482 self.ui, wctx, status, match, force=force)
2483
2483
2484 # make sure all explicit patterns are matched
2484 # make sure all explicit patterns are matched
2485 if not force:
2485 if not force:
2486 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
2486 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
2487
2487
2488 cctx = context.workingcommitctx(self, status,
2488 cctx = context.workingcommitctx(self, status,
2489 text, user, date, extra)
2489 text, user, date, extra)
2490
2490
2491 # internal config: ui.allowemptycommit
2491 # internal config: ui.allowemptycommit
2492 allowemptycommit = (wctx.branch() != wctx.p1().branch()
2492 allowemptycommit = (wctx.branch() != wctx.p1().branch()
2493 or extra.get('close') or merge or cctx.files()
2493 or extra.get('close') or merge or cctx.files()
2494 or self.ui.configbool('ui', 'allowemptycommit'))
2494 or self.ui.configbool('ui', 'allowemptycommit'))
2495 if not allowemptycommit:
2495 if not allowemptycommit:
2496 return None
2496 return None
2497
2497
2498 if merge and cctx.deleted():
2498 if merge and cctx.deleted():
2499 raise error.Abort(_("cannot commit merge with missing files"))
2499 raise error.Abort(_("cannot commit merge with missing files"))
2500
2500
2501 ms = mergemod.mergestate.read(self)
2501 ms = mergemod.mergestate.read(self)
2502 mergeutil.checkunresolved(ms)
2502 mergeutil.checkunresolved(ms)
2503
2503
2504 if editor:
2504 if editor:
2505 cctx._text = editor(self, cctx, subs)
2505 cctx._text = editor(self, cctx, subs)
2506 edited = (text != cctx._text)
2506 edited = (text != cctx._text)
2507
2507
2508 # Save commit message in case this transaction gets rolled back
2508 # Save commit message in case this transaction gets rolled back
2509 # (e.g. by a pretxncommit hook). Leave the content alone on
2509 # (e.g. by a pretxncommit hook). Leave the content alone on
2510 # the assumption that the user will use the same editor again.
2510 # the assumption that the user will use the same editor again.
2511 msgfn = self.savecommitmessage(cctx._text)
2511 msgfn = self.savecommitmessage(cctx._text)
2512
2512
2513 # commit subs and write new state
2513 # commit subs and write new state
2514 if subs:
2514 if subs:
2515 uipathfn = scmutil.getuipathfn(self)
2515 uipathfn = scmutil.getuipathfn(self)
2516 for s in sorted(commitsubs):
2516 for s in sorted(commitsubs):
2517 sub = wctx.sub(s)
2517 sub = wctx.sub(s)
2518 self.ui.status(_('committing subrepository %s\n') %
2518 self.ui.status(_('committing subrepository %s\n') %
2519 uipathfn(subrepoutil.subrelpath(sub)))
2519 uipathfn(subrepoutil.subrelpath(sub)))
2520 sr = sub.commit(cctx._text, user, date)
2520 sr = sub.commit(cctx._text, user, date)
2521 newstate[s] = (newstate[s][0], sr)
2521 newstate[s] = (newstate[s][0], sr)
2522 subrepoutil.writestate(self, newstate)
2522 subrepoutil.writestate(self, newstate)
2523
2523
2524 p1, p2 = self.dirstate.parents()
2524 p1, p2 = self.dirstate.parents()
2525 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
2525 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
2526 try:
2526 try:
2527 self.hook("precommit", throw=True, parent1=hookp1,
2527 self.hook("precommit", throw=True, parent1=hookp1,
2528 parent2=hookp2)
2528 parent2=hookp2)
2529 with self.transaction('commit'):
2529 with self.transaction('commit'):
2530 ret = self.commitctx(cctx, True)
2530 ret = self.commitctx(cctx, True)
2531 # update bookmarks, dirstate and mergestate
2531 # update bookmarks, dirstate and mergestate
2532 bookmarks.update(self, [p1, p2], ret)
2532 bookmarks.update(self, [p1, p2], ret)
2533 cctx.markcommitted(ret)
2533 cctx.markcommitted(ret)
2534 ms.reset()
2534 ms.reset()
2535 except: # re-raises
2535 except: # re-raises
2536 if edited:
2536 if edited:
2537 self.ui.write(
2537 self.ui.write(
2538 _('note: commit message saved in %s\n') % msgfn)
2538 _('note: commit message saved in %s\n') % msgfn)
2539 raise
2539 raise
2540
2540
2541 def commithook():
2541 def commithook():
2542 # hack for command that use a temporary commit (eg: histedit)
2542 # hack for command that use a temporary commit (eg: histedit)
2543 # temporary commit got stripped before hook release
2543 # temporary commit got stripped before hook release
2544 if self.changelog.hasnode(ret):
2544 if self.changelog.hasnode(ret):
2545 self.hook("commit", node=hex(ret), parent1=hookp1,
2545 self.hook("commit", node=hex(ret), parent1=hookp1,
2546 parent2=hookp2)
2546 parent2=hookp2)
2547 self._afterlock(commithook)
2547 self._afterlock(commithook)
2548 return ret
2548 return ret
2549
2549
2550 @unfilteredmethod
2550 @unfilteredmethod
2551 def commitctx(self, ctx, error=False):
2551 def commitctx(self, ctx, error=False):
2552 """Add a new revision to current repository.
2552 """Add a new revision to current repository.
2553 Revision information is passed via the context argument.
2553 Revision information is passed via the context argument.
2554
2554
2555 ctx.files() should list all files involved in this commit, i.e.
2555 ctx.files() should list all files involved in this commit, i.e.
2556 modified/added/removed files. On merge, it may be wider than the
2556 modified/added/removed files. On merge, it may be wider than the
2557 ctx.files() to be committed, since any file nodes derived directly
2557 ctx.files() to be committed, since any file nodes derived directly
2558 from p1 or p2 are excluded from the committed ctx.files().
2558 from p1 or p2 are excluded from the committed ctx.files().
2559 """
2559 """
2560
2560
2561 p1, p2 = ctx.p1(), ctx.p2()
2561 p1, p2 = ctx.p1(), ctx.p2()
2562 user = ctx.user()
2562 user = ctx.user()
2563
2563
2564 writecopiesto = self.ui.config('experimental', 'copies.write-to')
2564 writecopiesto = self.ui.config('experimental', 'copies.write-to')
2565 writefilecopymeta = writecopiesto != 'changeset-only'
2565 writefilecopymeta = writecopiesto != 'changeset-only'
2566 p1copies, p2copies = None, None
2566 p1copies, p2copies = None, None
2567 if writecopiesto in ('changeset-only', 'compatibility'):
2567 if writecopiesto in ('changeset-only', 'compatibility'):
2568 p1copies = ctx.p1copies()
2568 p1copies = ctx.p1copies()
2569 p2copies = ctx.p2copies()
2569 p2copies = ctx.p2copies()
2570 with self.lock(), self.transaction("commit") as tr:
2570 with self.lock(), self.transaction("commit") as tr:
2571 trp = weakref.proxy(tr)
2571 trp = weakref.proxy(tr)
2572
2572
2573 if ctx.manifestnode():
2573 if ctx.manifestnode():
2574 # reuse an existing manifest revision
2574 # reuse an existing manifest revision
2575 self.ui.debug('reusing known manifest\n')
2575 self.ui.debug('reusing known manifest\n')
2576 mn = ctx.manifestnode()
2576 mn = ctx.manifestnode()
2577 files = ctx.files()
2577 files = ctx.files()
2578 elif ctx.files():
2578 elif ctx.files():
2579 m1ctx = p1.manifestctx()
2579 m1ctx = p1.manifestctx()
2580 m2ctx = p2.manifestctx()
2580 m2ctx = p2.manifestctx()
2581 mctx = m1ctx.copy()
2581 mctx = m1ctx.copy()
2582
2582
2583 m = mctx.read()
2583 m = mctx.read()
2584 m1 = m1ctx.read()
2584 m1 = m1ctx.read()
2585 m2 = m2ctx.read()
2585 m2 = m2ctx.read()
2586
2586
2587 # check in files
2587 # check in files
2588 added = []
2588 added = []
2589 changed = []
2589 changed = []
2590 removed = list(ctx.removed())
2590 removed = list(ctx.removed())
2591 linkrev = len(self)
2591 linkrev = len(self)
2592 self.ui.note(_("committing files:\n"))
2592 self.ui.note(_("committing files:\n"))
2593 uipathfn = scmutil.getuipathfn(self)
2593 uipathfn = scmutil.getuipathfn(self)
2594 for f in sorted(ctx.modified() + ctx.added()):
2594 for f in sorted(ctx.modified() + ctx.added()):
2595 self.ui.note(uipathfn(f) + "\n")
2595 self.ui.note(uipathfn(f) + "\n")
2596 try:
2596 try:
2597 fctx = ctx[f]
2597 fctx = ctx[f]
2598 if fctx is None:
2598 if fctx is None:
2599 removed.append(f)
2599 removed.append(f)
2600 else:
2600 else:
2601 added.append(f)
2601 added.append(f)
2602 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2602 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2603 trp, changed,
2603 trp, changed,
2604 writefilecopymeta)
2604 writefilecopymeta)
2605 m.setflag(f, fctx.flags())
2605 m.setflag(f, fctx.flags())
2606 except OSError:
2606 except OSError:
2607 self.ui.warn(_("trouble committing %s!\n") %
2607 self.ui.warn(_("trouble committing %s!\n") %
2608 uipathfn(f))
2608 uipathfn(f))
2609 raise
2609 raise
2610 except IOError as inst:
2610 except IOError as inst:
2611 errcode = getattr(inst, 'errno', errno.ENOENT)
2611 errcode = getattr(inst, 'errno', errno.ENOENT)
2612 if error or errcode and errcode != errno.ENOENT:
2612 if error or errcode and errcode != errno.ENOENT:
2613 self.ui.warn(_("trouble committing %s!\n") %
2613 self.ui.warn(_("trouble committing %s!\n") %
2614 uipathfn(f))
2614 uipathfn(f))
2615 raise
2615 raise
2616
2616
2617 # update manifest
2617 # update manifest
2618 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2618 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2619 drop = [f for f in removed if f in m]
2619 drop = [f for f in removed if f in m]
2620 for f in drop:
2620 for f in drop:
2621 del m[f]
2621 del m[f]
2622 files = changed + removed
2622 files = changed + removed
2623 md = None
2623 md = None
2624 if not files:
2624 if not files:
2625 # if no "files" actually changed in terms of the changelog,
2625 # if no "files" actually changed in terms of the changelog,
2626 # try hard to detect unmodified manifest entry so that the
2626 # try hard to detect unmodified manifest entry so that the
2627 # exact same commit can be reproduced later on convert.
2627 # exact same commit can be reproduced later on convert.
2628 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
2628 md = m1.diff(m, scmutil.matchfiles(self, ctx.files()))
2629 if not files and md:
2629 if not files and md:
2630 self.ui.debug('not reusing manifest (no file change in '
2630 self.ui.debug('not reusing manifest (no file change in '
2631 'changelog, but manifest differs)\n')
2631 'changelog, but manifest differs)\n')
2632 if files or md:
2632 if files or md:
2633 self.ui.note(_("committing manifest\n"))
2633 self.ui.note(_("committing manifest\n"))
2634 # we're using narrowmatch here since it's already applied at
2634 # we're using narrowmatch here since it's already applied at
2635 # other stages (such as dirstate.walk), so we're already
2635 # other stages (such as dirstate.walk), so we're already
2636 # ignoring things outside of narrowspec in most cases. The
2636 # ignoring things outside of narrowspec in most cases. The
2637 # one case where we might have files outside the narrowspec
2637 # one case where we might have files outside the narrowspec
2638 # at this point is merges, and we already error out in the
2638 # at this point is merges, and we already error out in the
2639 # case where the merge has files outside of the narrowspec,
2639 # case where the merge has files outside of the narrowspec,
2640 # so this is safe.
2640 # so this is safe.
2641 mn = mctx.write(trp, linkrev,
2641 mn = mctx.write(trp, linkrev,
2642 p1.manifestnode(), p2.manifestnode(),
2642 p1.manifestnode(), p2.manifestnode(),
2643 added, drop, match=self.narrowmatch())
2643 added, drop, match=self.narrowmatch())
2644 else:
2644 else:
2645 self.ui.debug('reusing manifest from p1 (listed files '
2645 self.ui.debug('reusing manifest from p1 (listed files '
2646 'actually unchanged)\n')
2646 'actually unchanged)\n')
2647 mn = p1.manifestnode()
2647 mn = p1.manifestnode()
2648 else:
2648 else:
2649 self.ui.debug('reusing manifest from p1 (no file change)\n')
2649 self.ui.debug('reusing manifest from p1 (no file change)\n')
2650 mn = p1.manifestnode()
2650 mn = p1.manifestnode()
2651 files = []
2651 files = []
2652
2652
2653 if writecopiesto == 'changeset-only':
2654 # If writing only to changeset extras, use None to indicate that
2655 # no entry should be written. If writing to both, write an empty
2656 # entry to prevent the reader from falling back to reading
2657 # filelogs.
2658 p1copies = p1copies or None
2659 p2copies = p2copies or None
2660
2653 # update changelog
2661 # update changelog
2654 self.ui.note(_("committing changelog\n"))
2662 self.ui.note(_("committing changelog\n"))
2655 self.changelog.delayupdate(tr)
2663 self.changelog.delayupdate(tr)
2656 n = self.changelog.add(mn, files, ctx.description(),
2664 n = self.changelog.add(mn, files, ctx.description(),
2657 trp, p1.node(), p2.node(),
2665 trp, p1.node(), p2.node(),
2658 user, ctx.date(), ctx.extra().copy(),
2666 user, ctx.date(), ctx.extra().copy(),
2659 p1copies, p2copies)
2667 p1copies, p2copies)
2660 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2668 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2661 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2669 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2662 parent2=xp2)
2670 parent2=xp2)
2663 # set the new commit is proper phase
2671 # set the new commit is proper phase
2664 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2672 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2665 if targetphase:
2673 if targetphase:
2666 # retract boundary do not alter parent changeset.
2674 # retract boundary do not alter parent changeset.
2667 # if a parent have higher the resulting phase will
2675 # if a parent have higher the resulting phase will
2668 # be compliant anyway
2676 # be compliant anyway
2669 #
2677 #
2670 # if minimal phase was 0 we don't need to retract anything
2678 # if minimal phase was 0 we don't need to retract anything
2671 phases.registernew(self, tr, targetphase, [n])
2679 phases.registernew(self, tr, targetphase, [n])
2672 return n
2680 return n
2673
2681
2674 @unfilteredmethod
2682 @unfilteredmethod
2675 def destroying(self):
2683 def destroying(self):
2676 '''Inform the repository that nodes are about to be destroyed.
2684 '''Inform the repository that nodes are about to be destroyed.
2677 Intended for use by strip and rollback, so there's a common
2685 Intended for use by strip and rollback, so there's a common
2678 place for anything that has to be done before destroying history.
2686 place for anything that has to be done before destroying history.
2679
2687
2680 This is mostly useful for saving state that is in memory and waiting
2688 This is mostly useful for saving state that is in memory and waiting
2681 to be flushed when the current lock is released. Because a call to
2689 to be flushed when the current lock is released. Because a call to
2682 destroyed is imminent, the repo will be invalidated causing those
2690 destroyed is imminent, the repo will be invalidated causing those
2683 changes to stay in memory (waiting for the next unlock), or vanish
2691 changes to stay in memory (waiting for the next unlock), or vanish
2684 completely.
2692 completely.
2685 '''
2693 '''
2686 # When using the same lock to commit and strip, the phasecache is left
2694 # When using the same lock to commit and strip, the phasecache is left
2687 # dirty after committing. Then when we strip, the repo is invalidated,
2695 # dirty after committing. Then when we strip, the repo is invalidated,
2688 # causing those changes to disappear.
2696 # causing those changes to disappear.
2689 if '_phasecache' in vars(self):
2697 if '_phasecache' in vars(self):
2690 self._phasecache.write()
2698 self._phasecache.write()
2691
2699
2692 @unfilteredmethod
2700 @unfilteredmethod
2693 def destroyed(self):
2701 def destroyed(self):
2694 '''Inform the repository that nodes have been destroyed.
2702 '''Inform the repository that nodes have been destroyed.
2695 Intended for use by strip and rollback, so there's a common
2703 Intended for use by strip and rollback, so there's a common
2696 place for anything that has to be done after destroying history.
2704 place for anything that has to be done after destroying history.
2697 '''
2705 '''
2698 # When one tries to:
2706 # When one tries to:
2699 # 1) destroy nodes thus calling this method (e.g. strip)
2707 # 1) destroy nodes thus calling this method (e.g. strip)
2700 # 2) use phasecache somewhere (e.g. commit)
2708 # 2) use phasecache somewhere (e.g. commit)
2701 #
2709 #
2702 # then 2) will fail because the phasecache contains nodes that were
2710 # then 2) will fail because the phasecache contains nodes that were
2703 # removed. We can either remove phasecache from the filecache,
2711 # removed. We can either remove phasecache from the filecache,
2704 # causing it to reload next time it is accessed, or simply filter
2712 # causing it to reload next time it is accessed, or simply filter
2705 # the removed nodes now and write the updated cache.
2713 # the removed nodes now and write the updated cache.
2706 self._phasecache.filterunknown(self)
2714 self._phasecache.filterunknown(self)
2707 self._phasecache.write()
2715 self._phasecache.write()
2708
2716
2709 # refresh all repository caches
2717 # refresh all repository caches
2710 self.updatecaches()
2718 self.updatecaches()
2711
2719
2712 # Ensure the persistent tag cache is updated. Doing it now
2720 # Ensure the persistent tag cache is updated. Doing it now
2713 # means that the tag cache only has to worry about destroyed
2721 # means that the tag cache only has to worry about destroyed
2714 # heads immediately after a strip/rollback. That in turn
2722 # heads immediately after a strip/rollback. That in turn
2715 # guarantees that "cachetip == currenttip" (comparing both rev
2723 # guarantees that "cachetip == currenttip" (comparing both rev
2716 # and node) always means no nodes have been added or destroyed.
2724 # and node) always means no nodes have been added or destroyed.
2717
2725
2718 # XXX this is suboptimal when qrefresh'ing: we strip the current
2726 # XXX this is suboptimal when qrefresh'ing: we strip the current
2719 # head, refresh the tag cache, then immediately add a new head.
2727 # head, refresh the tag cache, then immediately add a new head.
2720 # But I think doing it this way is necessary for the "instant
2728 # But I think doing it this way is necessary for the "instant
2721 # tag cache retrieval" case to work.
2729 # tag cache retrieval" case to work.
2722 self.invalidate()
2730 self.invalidate()
2723
2731
2724 def status(self, node1='.', node2=None, match=None,
2732 def status(self, node1='.', node2=None, match=None,
2725 ignored=False, clean=False, unknown=False,
2733 ignored=False, clean=False, unknown=False,
2726 listsubrepos=False):
2734 listsubrepos=False):
2727 '''a convenience method that calls node1.status(node2)'''
2735 '''a convenience method that calls node1.status(node2)'''
2728 return self[node1].status(node2, match, ignored, clean, unknown,
2736 return self[node1].status(node2, match, ignored, clean, unknown,
2729 listsubrepos)
2737 listsubrepos)
2730
2738
2731 def addpostdsstatus(self, ps):
2739 def addpostdsstatus(self, ps):
2732 """Add a callback to run within the wlock, at the point at which status
2740 """Add a callback to run within the wlock, at the point at which status
2733 fixups happen.
2741 fixups happen.
2734
2742
2735 On status completion, callback(wctx, status) will be called with the
2743 On status completion, callback(wctx, status) will be called with the
2736 wlock held, unless the dirstate has changed from underneath or the wlock
2744 wlock held, unless the dirstate has changed from underneath or the wlock
2737 couldn't be grabbed.
2745 couldn't be grabbed.
2738
2746
2739 Callbacks should not capture and use a cached copy of the dirstate --
2747 Callbacks should not capture and use a cached copy of the dirstate --
2740 it might change in the meanwhile. Instead, they should access the
2748 it might change in the meanwhile. Instead, they should access the
2741 dirstate via wctx.repo().dirstate.
2749 dirstate via wctx.repo().dirstate.
2742
2750
2743 This list is emptied out after each status run -- extensions should
2751 This list is emptied out after each status run -- extensions should
2744 make sure it adds to this list each time dirstate.status is called.
2752 make sure it adds to this list each time dirstate.status is called.
2745 Extensions should also make sure they don't call this for statuses
2753 Extensions should also make sure they don't call this for statuses
2746 that don't involve the dirstate.
2754 that don't involve the dirstate.
2747 """
2755 """
2748
2756
2749 # The list is located here for uniqueness reasons -- it is actually
2757 # The list is located here for uniqueness reasons -- it is actually
2750 # managed by the workingctx, but that isn't unique per-repo.
2758 # managed by the workingctx, but that isn't unique per-repo.
2751 self._postdsstatus.append(ps)
2759 self._postdsstatus.append(ps)
2752
2760
2753 def postdsstatus(self):
2761 def postdsstatus(self):
2754 """Used by workingctx to get the list of post-dirstate-status hooks."""
2762 """Used by workingctx to get the list of post-dirstate-status hooks."""
2755 return self._postdsstatus
2763 return self._postdsstatus
2756
2764
2757 def clearpostdsstatus(self):
2765 def clearpostdsstatus(self):
2758 """Used by workingctx to clear post-dirstate-status hooks."""
2766 """Used by workingctx to clear post-dirstate-status hooks."""
2759 del self._postdsstatus[:]
2767 del self._postdsstatus[:]
2760
2768
2761 def heads(self, start=None):
2769 def heads(self, start=None):
2762 if start is None:
2770 if start is None:
2763 cl = self.changelog
2771 cl = self.changelog
2764 headrevs = reversed(cl.headrevs())
2772 headrevs = reversed(cl.headrevs())
2765 return [cl.node(rev) for rev in headrevs]
2773 return [cl.node(rev) for rev in headrevs]
2766
2774
2767 heads = self.changelog.heads(start)
2775 heads = self.changelog.heads(start)
2768 # sort the output in rev descending order
2776 # sort the output in rev descending order
2769 return sorted(heads, key=self.changelog.rev, reverse=True)
2777 return sorted(heads, key=self.changelog.rev, reverse=True)
2770
2778
2771 def branchheads(self, branch=None, start=None, closed=False):
2779 def branchheads(self, branch=None, start=None, closed=False):
2772 '''return a (possibly filtered) list of heads for the given branch
2780 '''return a (possibly filtered) list of heads for the given branch
2773
2781
2774 Heads are returned in topological order, from newest to oldest.
2782 Heads are returned in topological order, from newest to oldest.
2775 If branch is None, use the dirstate branch.
2783 If branch is None, use the dirstate branch.
2776 If start is not None, return only heads reachable from start.
2784 If start is not None, return only heads reachable from start.
2777 If closed is True, return heads that are marked as closed as well.
2785 If closed is True, return heads that are marked as closed as well.
2778 '''
2786 '''
2779 if branch is None:
2787 if branch is None:
2780 branch = self[None].branch()
2788 branch = self[None].branch()
2781 branches = self.branchmap()
2789 branches = self.branchmap()
2782 if not branches.hasbranch(branch):
2790 if not branches.hasbranch(branch):
2783 return []
2791 return []
2784 # the cache returns heads ordered lowest to highest
2792 # the cache returns heads ordered lowest to highest
2785 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2793 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2786 if start is not None:
2794 if start is not None:
2787 # filter out the heads that cannot be reached from startrev
2795 # filter out the heads that cannot be reached from startrev
2788 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2796 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2789 bheads = [h for h in bheads if h in fbheads]
2797 bheads = [h for h in bheads if h in fbheads]
2790 return bheads
2798 return bheads
2791
2799
2792 def branches(self, nodes):
2800 def branches(self, nodes):
2793 if not nodes:
2801 if not nodes:
2794 nodes = [self.changelog.tip()]
2802 nodes = [self.changelog.tip()]
2795 b = []
2803 b = []
2796 for n in nodes:
2804 for n in nodes:
2797 t = n
2805 t = n
2798 while True:
2806 while True:
2799 p = self.changelog.parents(n)
2807 p = self.changelog.parents(n)
2800 if p[1] != nullid or p[0] == nullid:
2808 if p[1] != nullid or p[0] == nullid:
2801 b.append((t, n, p[0], p[1]))
2809 b.append((t, n, p[0], p[1]))
2802 break
2810 break
2803 n = p[0]
2811 n = p[0]
2804 return b
2812 return b
2805
2813
2806 def between(self, pairs):
2814 def between(self, pairs):
2807 r = []
2815 r = []
2808
2816
2809 for top, bottom in pairs:
2817 for top, bottom in pairs:
2810 n, l, i = top, [], 0
2818 n, l, i = top, [], 0
2811 f = 1
2819 f = 1
2812
2820
2813 while n != bottom and n != nullid:
2821 while n != bottom and n != nullid:
2814 p = self.changelog.parents(n)[0]
2822 p = self.changelog.parents(n)[0]
2815 if i == f:
2823 if i == f:
2816 l.append(n)
2824 l.append(n)
2817 f = f * 2
2825 f = f * 2
2818 n = p
2826 n = p
2819 i += 1
2827 i += 1
2820
2828
2821 r.append(l)
2829 r.append(l)
2822
2830
2823 return r
2831 return r
2824
2832
2825 def checkpush(self, pushop):
2833 def checkpush(self, pushop):
2826 """Extensions can override this function if additional checks have
2834 """Extensions can override this function if additional checks have
2827 to be performed before pushing, or call it if they override push
2835 to be performed before pushing, or call it if they override push
2828 command.
2836 command.
2829 """
2837 """
2830
2838
2831 @unfilteredpropertycache
2839 @unfilteredpropertycache
2832 def prepushoutgoinghooks(self):
2840 def prepushoutgoinghooks(self):
2833 """Return util.hooks consists of a pushop with repo, remote, outgoing
2841 """Return util.hooks consists of a pushop with repo, remote, outgoing
2834 methods, which are called before pushing changesets.
2842 methods, which are called before pushing changesets.
2835 """
2843 """
2836 return util.hooks()
2844 return util.hooks()
2837
2845
2838 def pushkey(self, namespace, key, old, new):
2846 def pushkey(self, namespace, key, old, new):
2839 try:
2847 try:
2840 tr = self.currenttransaction()
2848 tr = self.currenttransaction()
2841 hookargs = {}
2849 hookargs = {}
2842 if tr is not None:
2850 if tr is not None:
2843 hookargs.update(tr.hookargs)
2851 hookargs.update(tr.hookargs)
2844 hookargs = pycompat.strkwargs(hookargs)
2852 hookargs = pycompat.strkwargs(hookargs)
2845 hookargs[r'namespace'] = namespace
2853 hookargs[r'namespace'] = namespace
2846 hookargs[r'key'] = key
2854 hookargs[r'key'] = key
2847 hookargs[r'old'] = old
2855 hookargs[r'old'] = old
2848 hookargs[r'new'] = new
2856 hookargs[r'new'] = new
2849 self.hook('prepushkey', throw=True, **hookargs)
2857 self.hook('prepushkey', throw=True, **hookargs)
2850 except error.HookAbort as exc:
2858 except error.HookAbort as exc:
2851 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2859 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2852 if exc.hint:
2860 if exc.hint:
2853 self.ui.write_err(_("(%s)\n") % exc.hint)
2861 self.ui.write_err(_("(%s)\n") % exc.hint)
2854 return False
2862 return False
2855 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2863 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2856 ret = pushkey.push(self, namespace, key, old, new)
2864 ret = pushkey.push(self, namespace, key, old, new)
2857 def runhook():
2865 def runhook():
2858 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2866 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2859 ret=ret)
2867 ret=ret)
2860 self._afterlock(runhook)
2868 self._afterlock(runhook)
2861 return ret
2869 return ret
2862
2870
2863 def listkeys(self, namespace):
2871 def listkeys(self, namespace):
2864 self.hook('prelistkeys', throw=True, namespace=namespace)
2872 self.hook('prelistkeys', throw=True, namespace=namespace)
2865 self.ui.debug('listing keys for "%s"\n' % namespace)
2873 self.ui.debug('listing keys for "%s"\n' % namespace)
2866 values = pushkey.list(self, namespace)
2874 values = pushkey.list(self, namespace)
2867 self.hook('listkeys', namespace=namespace, values=values)
2875 self.hook('listkeys', namespace=namespace, values=values)
2868 return values
2876 return values
2869
2877
2870 def debugwireargs(self, one, two, three=None, four=None, five=None):
2878 def debugwireargs(self, one, two, three=None, four=None, five=None):
2871 '''used to test argument passing over the wire'''
2879 '''used to test argument passing over the wire'''
2872 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2880 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2873 pycompat.bytestr(four),
2881 pycompat.bytestr(four),
2874 pycompat.bytestr(five))
2882 pycompat.bytestr(five))
2875
2883
2876 def savecommitmessage(self, text):
2884 def savecommitmessage(self, text):
2877 fp = self.vfs('last-message.txt', 'wb')
2885 fp = self.vfs('last-message.txt', 'wb')
2878 try:
2886 try:
2879 fp.write(text)
2887 fp.write(text)
2880 finally:
2888 finally:
2881 fp.close()
2889 fp.close()
2882 return self.pathto(fp.name[len(self.root) + 1:])
2890 return self.pathto(fp.name[len(self.root) + 1:])
2883
2891
2884 # used to avoid circular references so destructors work
2892 # used to avoid circular references so destructors work
2885 def aftertrans(files):
2893 def aftertrans(files):
2886 renamefiles = [tuple(t) for t in files]
2894 renamefiles = [tuple(t) for t in files]
2887 def a():
2895 def a():
2888 for vfs, src, dest in renamefiles:
2896 for vfs, src, dest in renamefiles:
2889 # if src and dest refer to a same file, vfs.rename is a no-op,
2897 # if src and dest refer to a same file, vfs.rename is a no-op,
2890 # leaving both src and dest on disk. delete dest to make sure
2898 # leaving both src and dest on disk. delete dest to make sure
2891 # the rename couldn't be such a no-op.
2899 # the rename couldn't be such a no-op.
2892 vfs.tryunlink(dest)
2900 vfs.tryunlink(dest)
2893 try:
2901 try:
2894 vfs.rename(src, dest)
2902 vfs.rename(src, dest)
2895 except OSError: # journal file does not yet exist
2903 except OSError: # journal file does not yet exist
2896 pass
2904 pass
2897 return a
2905 return a
2898
2906
2899 def undoname(fn):
2907 def undoname(fn):
2900 base, name = os.path.split(fn)
2908 base, name = os.path.split(fn)
2901 assert name.startswith('journal')
2909 assert name.startswith('journal')
2902 return os.path.join(base, name.replace('journal', 'undo', 1))
2910 return os.path.join(base, name.replace('journal', 'undo', 1))
2903
2911
2904 def instance(ui, path, create, intents=None, createopts=None):
2912 def instance(ui, path, create, intents=None, createopts=None):
2905 localpath = util.urllocalpath(path)
2913 localpath = util.urllocalpath(path)
2906 if create:
2914 if create:
2907 createrepository(ui, localpath, createopts=createopts)
2915 createrepository(ui, localpath, createopts=createopts)
2908
2916
2909 return makelocalrepository(ui, localpath, intents=intents)
2917 return makelocalrepository(ui, localpath, intents=intents)
2910
2918
2911 def islocal(path):
2919 def islocal(path):
2912 return True
2920 return True
2913
2921
2914 def defaultcreateopts(ui, createopts=None):
2922 def defaultcreateopts(ui, createopts=None):
2915 """Populate the default creation options for a repository.
2923 """Populate the default creation options for a repository.
2916
2924
2917 A dictionary of explicitly requested creation options can be passed
2925 A dictionary of explicitly requested creation options can be passed
2918 in. Missing keys will be populated.
2926 in. Missing keys will be populated.
2919 """
2927 """
2920 createopts = dict(createopts or {})
2928 createopts = dict(createopts or {})
2921
2929
2922 if 'backend' not in createopts:
2930 if 'backend' not in createopts:
2923 # experimental config: storage.new-repo-backend
2931 # experimental config: storage.new-repo-backend
2924 createopts['backend'] = ui.config('storage', 'new-repo-backend')
2932 createopts['backend'] = ui.config('storage', 'new-repo-backend')
2925
2933
2926 return createopts
2934 return createopts
2927
2935
2928 def newreporequirements(ui, createopts):
2936 def newreporequirements(ui, createopts):
2929 """Determine the set of requirements for a new local repository.
2937 """Determine the set of requirements for a new local repository.
2930
2938
2931 Extensions can wrap this function to specify custom requirements for
2939 Extensions can wrap this function to specify custom requirements for
2932 new repositories.
2940 new repositories.
2933 """
2941 """
2934 # If the repo is being created from a shared repository, we copy
2942 # If the repo is being created from a shared repository, we copy
2935 # its requirements.
2943 # its requirements.
2936 if 'sharedrepo' in createopts:
2944 if 'sharedrepo' in createopts:
2937 requirements = set(createopts['sharedrepo'].requirements)
2945 requirements = set(createopts['sharedrepo'].requirements)
2938 if createopts.get('sharedrelative'):
2946 if createopts.get('sharedrelative'):
2939 requirements.add('relshared')
2947 requirements.add('relshared')
2940 else:
2948 else:
2941 requirements.add('shared')
2949 requirements.add('shared')
2942
2950
2943 return requirements
2951 return requirements
2944
2952
2945 if 'backend' not in createopts:
2953 if 'backend' not in createopts:
2946 raise error.ProgrammingError('backend key not present in createopts; '
2954 raise error.ProgrammingError('backend key not present in createopts; '
2947 'was defaultcreateopts() called?')
2955 'was defaultcreateopts() called?')
2948
2956
2949 if createopts['backend'] != 'revlogv1':
2957 if createopts['backend'] != 'revlogv1':
2950 raise error.Abort(_('unable to determine repository requirements for '
2958 raise error.Abort(_('unable to determine repository requirements for '
2951 'storage backend: %s') % createopts['backend'])
2959 'storage backend: %s') % createopts['backend'])
2952
2960
2953 requirements = {'revlogv1'}
2961 requirements = {'revlogv1'}
2954 if ui.configbool('format', 'usestore'):
2962 if ui.configbool('format', 'usestore'):
2955 requirements.add('store')
2963 requirements.add('store')
2956 if ui.configbool('format', 'usefncache'):
2964 if ui.configbool('format', 'usefncache'):
2957 requirements.add('fncache')
2965 requirements.add('fncache')
2958 if ui.configbool('format', 'dotencode'):
2966 if ui.configbool('format', 'dotencode'):
2959 requirements.add('dotencode')
2967 requirements.add('dotencode')
2960
2968
2961 compengine = ui.config('format', 'revlog-compression')
2969 compengine = ui.config('format', 'revlog-compression')
2962 if compengine not in util.compengines:
2970 if compengine not in util.compengines:
2963 raise error.Abort(_('compression engine %s defined by '
2971 raise error.Abort(_('compression engine %s defined by '
2964 'format.revlog-compression not available') %
2972 'format.revlog-compression not available') %
2965 compengine,
2973 compengine,
2966 hint=_('run "hg debuginstall" to list available '
2974 hint=_('run "hg debuginstall" to list available '
2967 'compression engines'))
2975 'compression engines'))
2968
2976
2969 # zlib is the historical default and doesn't need an explicit requirement.
2977 # zlib is the historical default and doesn't need an explicit requirement.
2970 elif compengine == 'zstd':
2978 elif compengine == 'zstd':
2971 requirements.add('revlog-compression-zstd')
2979 requirements.add('revlog-compression-zstd')
2972 elif compengine != 'zlib':
2980 elif compengine != 'zlib':
2973 requirements.add('exp-compression-%s' % compengine)
2981 requirements.add('exp-compression-%s' % compengine)
2974
2982
2975 if scmutil.gdinitconfig(ui):
2983 if scmutil.gdinitconfig(ui):
2976 requirements.add('generaldelta')
2984 requirements.add('generaldelta')
2977 if ui.configbool('format', 'sparse-revlog'):
2985 if ui.configbool('format', 'sparse-revlog'):
2978 requirements.add(SPARSEREVLOG_REQUIREMENT)
2986 requirements.add(SPARSEREVLOG_REQUIREMENT)
2979 if ui.configbool('experimental', 'treemanifest'):
2987 if ui.configbool('experimental', 'treemanifest'):
2980 requirements.add('treemanifest')
2988 requirements.add('treemanifest')
2981
2989
2982 revlogv2 = ui.config('experimental', 'revlogv2')
2990 revlogv2 = ui.config('experimental', 'revlogv2')
2983 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2991 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2984 requirements.remove('revlogv1')
2992 requirements.remove('revlogv1')
2985 # generaldelta is implied by revlogv2.
2993 # generaldelta is implied by revlogv2.
2986 requirements.discard('generaldelta')
2994 requirements.discard('generaldelta')
2987 requirements.add(REVLOGV2_REQUIREMENT)
2995 requirements.add(REVLOGV2_REQUIREMENT)
2988 # experimental config: format.internal-phase
2996 # experimental config: format.internal-phase
2989 if ui.configbool('format', 'internal-phase'):
2997 if ui.configbool('format', 'internal-phase'):
2990 requirements.add('internal-phase')
2998 requirements.add('internal-phase')
2991
2999
2992 if createopts.get('narrowfiles'):
3000 if createopts.get('narrowfiles'):
2993 requirements.add(repository.NARROW_REQUIREMENT)
3001 requirements.add(repository.NARROW_REQUIREMENT)
2994
3002
2995 if createopts.get('lfs'):
3003 if createopts.get('lfs'):
2996 requirements.add('lfs')
3004 requirements.add('lfs')
2997
3005
2998 return requirements
3006 return requirements
2999
3007
3000 def filterknowncreateopts(ui, createopts):
3008 def filterknowncreateopts(ui, createopts):
3001 """Filters a dict of repo creation options against options that are known.
3009 """Filters a dict of repo creation options against options that are known.
3002
3010
3003 Receives a dict of repo creation options and returns a dict of those
3011 Receives a dict of repo creation options and returns a dict of those
3004 options that we don't know how to handle.
3012 options that we don't know how to handle.
3005
3013
3006 This function is called as part of repository creation. If the
3014 This function is called as part of repository creation. If the
3007 returned dict contains any items, repository creation will not
3015 returned dict contains any items, repository creation will not
3008 be allowed, as it means there was a request to create a repository
3016 be allowed, as it means there was a request to create a repository
3009 with options not recognized by loaded code.
3017 with options not recognized by loaded code.
3010
3018
3011 Extensions can wrap this function to filter out creation options
3019 Extensions can wrap this function to filter out creation options
3012 they know how to handle.
3020 they know how to handle.
3013 """
3021 """
3014 known = {
3022 known = {
3015 'backend',
3023 'backend',
3016 'lfs',
3024 'lfs',
3017 'narrowfiles',
3025 'narrowfiles',
3018 'sharedrepo',
3026 'sharedrepo',
3019 'sharedrelative',
3027 'sharedrelative',
3020 'shareditems',
3028 'shareditems',
3021 'shallowfilestore',
3029 'shallowfilestore',
3022 }
3030 }
3023
3031
3024 return {k: v for k, v in createopts.items() if k not in known}
3032 return {k: v for k, v in createopts.items() if k not in known}
3025
3033
3026 def createrepository(ui, path, createopts=None):
3034 def createrepository(ui, path, createopts=None):
3027 """Create a new repository in a vfs.
3035 """Create a new repository in a vfs.
3028
3036
3029 ``path`` path to the new repo's working directory.
3037 ``path`` path to the new repo's working directory.
3030 ``createopts`` options for the new repository.
3038 ``createopts`` options for the new repository.
3031
3039
3032 The following keys for ``createopts`` are recognized:
3040 The following keys for ``createopts`` are recognized:
3033
3041
3034 backend
3042 backend
3035 The storage backend to use.
3043 The storage backend to use.
3036 lfs
3044 lfs
3037 Repository will be created with ``lfs`` requirement. The lfs extension
3045 Repository will be created with ``lfs`` requirement. The lfs extension
3038 will automatically be loaded when the repository is accessed.
3046 will automatically be loaded when the repository is accessed.
3039 narrowfiles
3047 narrowfiles
3040 Set up repository to support narrow file storage.
3048 Set up repository to support narrow file storage.
3041 sharedrepo
3049 sharedrepo
3042 Repository object from which storage should be shared.
3050 Repository object from which storage should be shared.
3043 sharedrelative
3051 sharedrelative
3044 Boolean indicating if the path to the shared repo should be
3052 Boolean indicating if the path to the shared repo should be
3045 stored as relative. By default, the pointer to the "parent" repo
3053 stored as relative. By default, the pointer to the "parent" repo
3046 is stored as an absolute path.
3054 is stored as an absolute path.
3047 shareditems
3055 shareditems
3048 Set of items to share to the new repository (in addition to storage).
3056 Set of items to share to the new repository (in addition to storage).
3049 shallowfilestore
3057 shallowfilestore
3050 Indicates that storage for files should be shallow (not all ancestor
3058 Indicates that storage for files should be shallow (not all ancestor
3051 revisions are known).
3059 revisions are known).
3052 """
3060 """
3053 createopts = defaultcreateopts(ui, createopts=createopts)
3061 createopts = defaultcreateopts(ui, createopts=createopts)
3054
3062
3055 unknownopts = filterknowncreateopts(ui, createopts)
3063 unknownopts = filterknowncreateopts(ui, createopts)
3056
3064
3057 if not isinstance(unknownopts, dict):
3065 if not isinstance(unknownopts, dict):
3058 raise error.ProgrammingError('filterknowncreateopts() did not return '
3066 raise error.ProgrammingError('filterknowncreateopts() did not return '
3059 'a dict')
3067 'a dict')
3060
3068
3061 if unknownopts:
3069 if unknownopts:
3062 raise error.Abort(_('unable to create repository because of unknown '
3070 raise error.Abort(_('unable to create repository because of unknown '
3063 'creation option: %s') %
3071 'creation option: %s') %
3064 ', '.join(sorted(unknownopts)),
3072 ', '.join(sorted(unknownopts)),
3065 hint=_('is a required extension not loaded?'))
3073 hint=_('is a required extension not loaded?'))
3066
3074
3067 requirements = newreporequirements(ui, createopts=createopts)
3075 requirements = newreporequirements(ui, createopts=createopts)
3068
3076
3069 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3077 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3070
3078
3071 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3079 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3072 if hgvfs.exists():
3080 if hgvfs.exists():
3073 raise error.RepoError(_('repository %s already exists') % path)
3081 raise error.RepoError(_('repository %s already exists') % path)
3074
3082
3075 if 'sharedrepo' in createopts:
3083 if 'sharedrepo' in createopts:
3076 sharedpath = createopts['sharedrepo'].sharedpath
3084 sharedpath = createopts['sharedrepo'].sharedpath
3077
3085
3078 if createopts.get('sharedrelative'):
3086 if createopts.get('sharedrelative'):
3079 try:
3087 try:
3080 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3088 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3081 except (IOError, ValueError) as e:
3089 except (IOError, ValueError) as e:
3082 # ValueError is raised on Windows if the drive letters differ
3090 # ValueError is raised on Windows if the drive letters differ
3083 # on each path.
3091 # on each path.
3084 raise error.Abort(_('cannot calculate relative path'),
3092 raise error.Abort(_('cannot calculate relative path'),
3085 hint=stringutil.forcebytestr(e))
3093 hint=stringutil.forcebytestr(e))
3086
3094
3087 if not wdirvfs.exists():
3095 if not wdirvfs.exists():
3088 wdirvfs.makedirs()
3096 wdirvfs.makedirs()
3089
3097
3090 hgvfs.makedir(notindexed=True)
3098 hgvfs.makedir(notindexed=True)
3091 if 'sharedrepo' not in createopts:
3099 if 'sharedrepo' not in createopts:
3092 hgvfs.mkdir(b'cache')
3100 hgvfs.mkdir(b'cache')
3093 hgvfs.mkdir(b'wcache')
3101 hgvfs.mkdir(b'wcache')
3094
3102
3095 if b'store' in requirements and 'sharedrepo' not in createopts:
3103 if b'store' in requirements and 'sharedrepo' not in createopts:
3096 hgvfs.mkdir(b'store')
3104 hgvfs.mkdir(b'store')
3097
3105
3098 # We create an invalid changelog outside the store so very old
3106 # We create an invalid changelog outside the store so very old
3099 # Mercurial versions (which didn't know about the requirements
3107 # Mercurial versions (which didn't know about the requirements
3100 # file) encounter an error on reading the changelog. This
3108 # file) encounter an error on reading the changelog. This
3101 # effectively locks out old clients and prevents them from
3109 # effectively locks out old clients and prevents them from
3102 # mucking with a repo in an unknown format.
3110 # mucking with a repo in an unknown format.
3103 #
3111 #
3104 # The revlog header has version 2, which won't be recognized by
3112 # The revlog header has version 2, which won't be recognized by
3105 # such old clients.
3113 # such old clients.
3106 hgvfs.append(b'00changelog.i',
3114 hgvfs.append(b'00changelog.i',
3107 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3115 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3108 b'layout')
3116 b'layout')
3109
3117
3110 scmutil.writerequires(hgvfs, requirements)
3118 scmutil.writerequires(hgvfs, requirements)
3111
3119
3112 # Write out file telling readers where to find the shared store.
3120 # Write out file telling readers where to find the shared store.
3113 if 'sharedrepo' in createopts:
3121 if 'sharedrepo' in createopts:
3114 hgvfs.write(b'sharedpath', sharedpath)
3122 hgvfs.write(b'sharedpath', sharedpath)
3115
3123
3116 if createopts.get('shareditems'):
3124 if createopts.get('shareditems'):
3117 shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n'
3125 shared = b'\n'.join(sorted(createopts['shareditems'])) + b'\n'
3118 hgvfs.write(b'shared', shared)
3126 hgvfs.write(b'shared', shared)
3119
3127
3120 def poisonrepository(repo):
3128 def poisonrepository(repo):
3121 """Poison a repository instance so it can no longer be used."""
3129 """Poison a repository instance so it can no longer be used."""
3122 # Perform any cleanup on the instance.
3130 # Perform any cleanup on the instance.
3123 repo.close()
3131 repo.close()
3124
3132
3125 # Our strategy is to replace the type of the object with one that
3133 # Our strategy is to replace the type of the object with one that
3126 # has all attribute lookups result in error.
3134 # has all attribute lookups result in error.
3127 #
3135 #
3128 # But we have to allow the close() method because some constructors
3136 # But we have to allow the close() method because some constructors
3129 # of repos call close() on repo references.
3137 # of repos call close() on repo references.
3130 class poisonedrepository(object):
3138 class poisonedrepository(object):
3131 def __getattribute__(self, item):
3139 def __getattribute__(self, item):
3132 if item == r'close':
3140 if item == r'close':
3133 return object.__getattribute__(self, item)
3141 return object.__getattribute__(self, item)
3134
3142
3135 raise error.ProgrammingError('repo instances should not be used '
3143 raise error.ProgrammingError('repo instances should not be used '
3136 'after unshare')
3144 'after unshare')
3137
3145
3138 def close(self):
3146 def close(self):
3139 pass
3147 pass
3140
3148
3141 # We may have a repoview, which intercepts __setattr__. So be sure
3149 # We may have a repoview, which intercepts __setattr__. So be sure
3142 # we operate at the lowest level possible.
3150 # we operate at the lowest level possible.
3143 object.__setattr__(repo, r'__class__', poisonedrepository)
3151 object.__setattr__(repo, r'__class__', poisonedrepository)
@@ -1,158 +1,167 b''
1
1
2 $ cat >> $HGRCPATH << EOF
2 $ cat >> $HGRCPATH << EOF
3 > [experimental]
3 > [experimental]
4 > copies.write-to=changeset-only
4 > copies.write-to=changeset-only
5 > copies.read-from=changeset-only
5 > copies.read-from=changeset-only
6 > [alias]
6 > [alias]
7 > changesetcopies = log -r . -T 'files: {files}
7 > changesetcopies = log -r . -T 'files: {files}
8 > {extras % "{ifcontains("copies", key, "{key}: {value}\n")}"}'
8 > {extras % "{ifcontains("copies", key, "{key}: {value}\n")}"}'
9 > showcopies = log -r . -T '{file_copies % "{source} -> {name}\n"}'
9 > showcopies = log -r . -T '{file_copies % "{source} -> {name}\n"}'
10 > [extensions]
10 > [extensions]
11 > rebase =
11 > rebase =
12 > EOF
12 > EOF
13
13
14 Check that copies are recorded correctly
14 Check that copies are recorded correctly
15
15
16 $ hg init repo
16 $ hg init repo
17 $ cd repo
17 $ cd repo
18 $ echo a > a
18 $ echo a > a
19 $ hg add a
19 $ hg add a
20 $ hg ci -m initial
20 $ hg ci -m initial
21 $ hg cp a b
21 $ hg cp a b
22 $ hg cp a c
22 $ hg cp a c
23 $ hg cp a d
23 $ hg cp a d
24 $ hg ci -m 'copy a to b, c, and d'
24 $ hg ci -m 'copy a to b, c, and d'
25 $ hg changesetcopies
25 $ hg changesetcopies
26 files: b c d
26 files: b c d
27 p1copies: b\x00a (esc)
27 p1copies: b\x00a (esc)
28 c\x00a (esc)
28 c\x00a (esc)
29 d\x00a (esc)
29 d\x00a (esc)
30 $ hg showcopies
30 $ hg showcopies
31 a -> b
31 a -> b
32 a -> c
32 a -> c
33 a -> d
33 a -> d
34 $ hg showcopies --config experimental.copies.read-from=compatibility
34 $ hg showcopies --config experimental.copies.read-from=compatibility
35 a -> b
35 a -> b
36 a -> c
36 a -> c
37 a -> d
37 a -> d
38 $ hg showcopies --config experimental.copies.read-from=filelog-only
38 $ hg showcopies --config experimental.copies.read-from=filelog-only
39
39
40 Check that renames are recorded correctly
40 Check that renames are recorded correctly
41
41
42 $ hg mv b b2
42 $ hg mv b b2
43 $ hg ci -m 'rename b to b2'
43 $ hg ci -m 'rename b to b2'
44 $ hg changesetcopies
44 $ hg changesetcopies
45 files: b b2
45 files: b b2
46 p1copies: b2\x00b (esc)
46 p1copies: b2\x00b (esc)
47 $ hg showcopies
47 $ hg showcopies
48 b -> b2
48 b -> b2
49
49
50 Rename onto existing file. This should get recorded in the changeset files list and in the extras,
50 Rename onto existing file. This should get recorded in the changeset files list and in the extras,
51 even though there is no filelog entry.
51 even though there is no filelog entry.
52
52
53 $ hg cp b2 c --force
53 $ hg cp b2 c --force
54 $ hg st --copies
54 $ hg st --copies
55 M c
55 M c
56 b2
56 b2
57 $ hg debugindex c
57 $ hg debugindex c
58 rev linkrev nodeid p1 p2
58 rev linkrev nodeid p1 p2
59 0 1 b789fdd96dc2 000000000000 000000000000
59 0 1 b789fdd96dc2 000000000000 000000000000
60 $ hg ci -m 'move b onto d'
60 $ hg ci -m 'move b onto d'
61 $ hg changesetcopies
61 $ hg changesetcopies
62 files: c
62 files: c
63 p1copies: c\x00b2 (esc)
63 p1copies: c\x00b2 (esc)
64 $ hg showcopies
64 $ hg showcopies
65 b2 -> c
65 b2 -> c
66 $ hg debugindex c
66 $ hg debugindex c
67 rev linkrev nodeid p1 p2
67 rev linkrev nodeid p1 p2
68 0 1 b789fdd96dc2 000000000000 000000000000
68 0 1 b789fdd96dc2 000000000000 000000000000
69
69
70 Create a merge commit with copying done during merge.
70 Create a merge commit with copying done during merge.
71
71
72 $ hg co 0
72 $ hg co 0
73 0 files updated, 0 files merged, 3 files removed, 0 files unresolved
73 0 files updated, 0 files merged, 3 files removed, 0 files unresolved
74 $ hg cp a e
74 $ hg cp a e
75 $ hg cp a f
75 $ hg cp a f
76 $ hg ci -m 'copy a to e and f'
76 $ hg ci -m 'copy a to e and f'
77 created new head
77 created new head
78 $ hg merge 3
78 $ hg merge 3
79 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
79 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
80 (branch merge, don't forget to commit)
80 (branch merge, don't forget to commit)
81 File 'a' exists on both sides, so 'g' could be recorded as being from p1 or p2, but we currently
81 File 'a' exists on both sides, so 'g' could be recorded as being from p1 or p2, but we currently
82 always record it as being from p1
82 always record it as being from p1
83 $ hg cp a g
83 $ hg cp a g
84 File 'd' exists only in p2, so 'h' should be from p2
84 File 'd' exists only in p2, so 'h' should be from p2
85 $ hg cp d h
85 $ hg cp d h
86 File 'f' exists only in p1, so 'i' should be from p1
86 File 'f' exists only in p1, so 'i' should be from p1
87 $ hg cp f i
87 $ hg cp f i
88 $ hg ci -m 'merge'
88 $ hg ci -m 'merge'
89 $ hg changesetcopies
89 $ hg changesetcopies
90 files: g h i
90 files: g h i
91 p1copies: g\x00a (esc)
91 p1copies: g\x00a (esc)
92 i\x00f (esc)
92 i\x00f (esc)
93 p2copies: h\x00d (esc)
93 p2copies: h\x00d (esc)
94 $ hg showcopies
94 $ hg showcopies
95 a -> g
95 a -> g
96 d -> h
96 d -> h
97 f -> i
97 f -> i
98
98
99 Test writing to both changeset and filelog
99 Test writing to both changeset and filelog
100
100
101 $ hg cp a j
101 $ hg cp a j
102 $ hg ci -m 'copy a to j' --config experimental.copies.write-to=compatibility
102 $ hg ci -m 'copy a to j' --config experimental.copies.write-to=compatibility
103 $ hg changesetcopies
103 $ hg changesetcopies
104 files: j
104 files: j
105 p1copies: j\x00a (esc)
105 p1copies: j\x00a (esc)
106 p2copies:
106 $ hg debugdata j 0
107 $ hg debugdata j 0
107 \x01 (esc)
108 \x01 (esc)
108 copy: a
109 copy: a
109 copyrev: b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3
110 copyrev: b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3
110 \x01 (esc)
111 \x01 (esc)
111 a
112 a
112 $ hg showcopies
113 $ hg showcopies
113 a -> j
114 a -> j
114 $ hg showcopies --config experimental.copies.read-from=compatibility
115 $ hg showcopies --config experimental.copies.read-from=compatibility
115 a -> j
116 a -> j
116 $ hg showcopies --config experimental.copies.read-from=filelog-only
117 $ hg showcopies --config experimental.copies.read-from=filelog-only
117 a -> j
118 a -> j
119 The entries should be written to extras even if they're empty (so the client
120 won't have to fall back to reading from filelogs)
121 $ echo x >> j
122 $ hg ci -m 'modify j' --config experimental.copies.write-to=compatibility
123 $ hg changesetcopies
124 files: j
125 p1copies:
126 p2copies:
118
127
119 Test writing only to filelog
128 Test writing only to filelog
120
129
121 $ hg cp a k
130 $ hg cp a k
122 $ hg ci -m 'copy a to k' --config experimental.copies.write-to=filelog-only
131 $ hg ci -m 'copy a to k' --config experimental.copies.write-to=filelog-only
123 $ hg changesetcopies
132 $ hg changesetcopies
124 files: k
133 files: k
125 $ hg debugdata k 0
134 $ hg debugdata k 0
126 \x01 (esc)
135 \x01 (esc)
127 copy: a
136 copy: a
128 copyrev: b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3
137 copyrev: b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3
129 \x01 (esc)
138 \x01 (esc)
130 a
139 a
131 $ hg showcopies
140 $ hg showcopies
132 $ hg showcopies --config experimental.copies.read-from=compatibility
141 $ hg showcopies --config experimental.copies.read-from=compatibility
133 a -> k
142 a -> k
134 $ hg showcopies --config experimental.copies.read-from=filelog-only
143 $ hg showcopies --config experimental.copies.read-from=filelog-only
135 a -> k
144 a -> k
136
145
137 $ cd ..
146 $ cd ..
138
147
139 Test rebasing a commit with copy information
148 Test rebasing a commit with copy information
140
149
141 $ hg init rebase-rename
150 $ hg init rebase-rename
142 $ cd rebase-rename
151 $ cd rebase-rename
143 $ echo a > a
152 $ echo a > a
144 $ hg ci -Aqm 'add a'
153 $ hg ci -Aqm 'add a'
145 $ echo a2 > a
154 $ echo a2 > a
146 $ hg ci -m 'modify a'
155 $ hg ci -m 'modify a'
147 $ hg co -q 0
156 $ hg co -q 0
148 $ hg mv a b
157 $ hg mv a b
149 $ hg ci -qm 'rename a to b'
158 $ hg ci -qm 'rename a to b'
150 $ hg rebase -d 1 --config rebase.experimental.inmemory=yes
159 $ hg rebase -d 1 --config rebase.experimental.inmemory=yes
151 rebasing 2:55d0b405c1b2 "rename a to b" (tip)
160 rebasing 2:55d0b405c1b2 "rename a to b" (tip)
152 merging a and b to b
161 merging a and b to b
153 saved backup bundle to $TESTTMP/rebase-rename/.hg/strip-backup/55d0b405c1b2-78df867e-rebase.hg
162 saved backup bundle to $TESTTMP/rebase-rename/.hg/strip-backup/55d0b405c1b2-78df867e-rebase.hg
154 $ hg st --change . --copies
163 $ hg st --change . --copies
155 A b
164 A b
156 a
165 a
157 R a
166 R a
158 $ cd ..
167 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now