##// END OF EJS Templates
obsolete: use the `version` argument in encodemarkers...
Pierre-Yves David -
r22613:e623898b default
parent child Browse files
Show More
@@ -1,1007 +1,1007 b''
1 # obsolete.py - obsolete markers handling
1 # obsolete.py - obsolete markers handling
2 #
2 #
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
3 # Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
4 # Logilab SA <contact@logilab.fr>
4 # Logilab SA <contact@logilab.fr>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 """Obsolete marker handling
9 """Obsolete marker handling
10
10
11 An obsolete marker maps an old changeset to a list of new
11 An obsolete marker maps an old changeset to a list of new
12 changesets. If the list of new changesets is empty, the old changeset
12 changesets. If the list of new changesets is empty, the old changeset
13 is said to be "killed". Otherwise, the old changeset is being
13 is said to be "killed". Otherwise, the old changeset is being
14 "replaced" by the new changesets.
14 "replaced" by the new changesets.
15
15
16 Obsolete markers can be used to record and distribute changeset graph
16 Obsolete markers can be used to record and distribute changeset graph
17 transformations performed by history rewrite operations, and help
17 transformations performed by history rewrite operations, and help
18 building new tools to reconcile conflicting rewrite actions. To
18 building new tools to reconcile conflicting rewrite actions. To
19 facilitate conflict resolution, markers include various annotations
19 facilitate conflict resolution, markers include various annotations
20 besides old and news changeset identifiers, such as creation date or
20 besides old and news changeset identifiers, such as creation date or
21 author name.
21 author name.
22
22
23 The old obsoleted changeset is called a "precursor" and possible
23 The old obsoleted changeset is called a "precursor" and possible
24 replacements are called "successors". Markers that used changeset X as
24 replacements are called "successors". Markers that used changeset X as
25 a precursor are called "successor markers of X" because they hold
25 a precursor are called "successor markers of X" because they hold
26 information about the successors of X. Markers that use changeset Y as
26 information about the successors of X. Markers that use changeset Y as
27 a successors are call "precursor markers of Y" because they hold
27 a successors are call "precursor markers of Y" because they hold
28 information about the precursors of Y.
28 information about the precursors of Y.
29
29
30 Examples:
30 Examples:
31
31
32 - When changeset A is replaced by changeset A', one marker is stored:
32 - When changeset A is replaced by changeset A', one marker is stored:
33
33
34 (A, (A',))
34 (A, (A',))
35
35
36 - When changesets A and B are folded into a new changeset C, two markers are
36 - When changesets A and B are folded into a new changeset C, two markers are
37 stored:
37 stored:
38
38
39 (A, (C,)) and (B, (C,))
39 (A, (C,)) and (B, (C,))
40
40
41 - When changeset A is simply "pruned" from the graph, a marker is created:
41 - When changeset A is simply "pruned" from the graph, a marker is created:
42
42
43 (A, ())
43 (A, ())
44
44
45 - When changeset A is split into B and C, a single marker are used:
45 - When changeset A is split into B and C, a single marker are used:
46
46
47 (A, (C, C))
47 (A, (C, C))
48
48
49 We use a single marker to distinguish the "split" case from the "divergence"
49 We use a single marker to distinguish the "split" case from the "divergence"
50 case. If two independent operations rewrite the same changeset A in to A' and
50 case. If two independent operations rewrite the same changeset A in to A' and
51 A'', we have an error case: divergent rewriting. We can detect it because
51 A'', we have an error case: divergent rewriting. We can detect it because
52 two markers will be created independently:
52 two markers will be created independently:
53
53
54 (A, (B,)) and (A, (C,))
54 (A, (B,)) and (A, (C,))
55
55
56 Format
56 Format
57 ------
57 ------
58
58
59 Markers are stored in an append-only file stored in
59 Markers are stored in an append-only file stored in
60 '.hg/store/obsstore'.
60 '.hg/store/obsstore'.
61
61
62 The file starts with a version header:
62 The file starts with a version header:
63
63
64 - 1 unsigned byte: version number, starting at zero.
64 - 1 unsigned byte: version number, starting at zero.
65
65
66 The header is followed by the markers. Marker format depend of the version. See
66 The header is followed by the markers. Marker format depend of the version. See
67 comment associated with each format for details.
67 comment associated with each format for details.
68
68
69 """
69 """
70 import struct
70 import struct
71 import util, base85, node
71 import util, base85, node
72 import phases
72 import phases
73 from i18n import _
73 from i18n import _
74
74
75 _pack = struct.pack
75 _pack = struct.pack
76 _unpack = struct.unpack
76 _unpack = struct.unpack
77
77
78 _SEEK_END = 2 # os.SEEK_END was introduced in Python 2.5
78 _SEEK_END = 2 # os.SEEK_END was introduced in Python 2.5
79
79
80 # the obsolete feature is not mature enough to be enabled by default.
80 # the obsolete feature is not mature enough to be enabled by default.
81 # you have to rely on third party extension extension to enable this.
81 # you have to rely on third party extension extension to enable this.
82 _enabled = False
82 _enabled = False
83
83
84 ### obsolescence marker flag
84 ### obsolescence marker flag
85
85
86 ## bumpedfix flag
86 ## bumpedfix flag
87 #
87 #
88 # When a changeset A' succeed to a changeset A which became public, we call A'
88 # When a changeset A' succeed to a changeset A which became public, we call A'
89 # "bumped" because it's a successors of a public changesets
89 # "bumped" because it's a successors of a public changesets
90 #
90 #
91 # o A' (bumped)
91 # o A' (bumped)
92 # |`:
92 # |`:
93 # | o A
93 # | o A
94 # |/
94 # |/
95 # o Z
95 # o Z
96 #
96 #
97 # The way to solve this situation is to create a new changeset Ad as children
97 # The way to solve this situation is to create a new changeset Ad as children
98 # of A. This changeset have the same content than A'. So the diff from A to A'
98 # of A. This changeset have the same content than A'. So the diff from A to A'
99 # is the same than the diff from A to Ad. Ad is marked as a successors of A'
99 # is the same than the diff from A to Ad. Ad is marked as a successors of A'
100 #
100 #
101 # o Ad
101 # o Ad
102 # |`:
102 # |`:
103 # | x A'
103 # | x A'
104 # |'|
104 # |'|
105 # o | A
105 # o | A
106 # |/
106 # |/
107 # o Z
107 # o Z
108 #
108 #
109 # But by transitivity Ad is also a successors of A. To avoid having Ad marked
109 # But by transitivity Ad is also a successors of A. To avoid having Ad marked
110 # as bumped too, we add the `bumpedfix` flag to the marker. <A', (Ad,)>.
110 # as bumped too, we add the `bumpedfix` flag to the marker. <A', (Ad,)>.
111 # This flag mean that the successors express the changes between the public and
111 # This flag mean that the successors express the changes between the public and
112 # bumped version and fix the situation, breaking the transitivity of
112 # bumped version and fix the situation, breaking the transitivity of
113 # "bumped" here.
113 # "bumped" here.
114 bumpedfix = 1
114 bumpedfix = 1
115
115
116 ## Parsing and writing of version "0"
116 ## Parsing and writing of version "0"
117 #
117 #
118 # The header is followed by the markers. Each marker is made of:
118 # The header is followed by the markers. Each marker is made of:
119 #
119 #
120 # - 1 unsigned byte: number of new changesets "N", can be zero.
120 # - 1 unsigned byte: number of new changesets "N", can be zero.
121 #
121 #
122 # - 1 unsigned 32-bits integer: metadata size "M" in bytes.
122 # - 1 unsigned 32-bits integer: metadata size "M" in bytes.
123 #
123 #
124 # - 1 byte: a bit field. It is reserved for flags used in common
124 # - 1 byte: a bit field. It is reserved for flags used in common
125 # obsolete marker operations, to avoid repeated decoding of metadata
125 # obsolete marker operations, to avoid repeated decoding of metadata
126 # entries.
126 # entries.
127 #
127 #
128 # - 20 bytes: obsoleted changeset identifier.
128 # - 20 bytes: obsoleted changeset identifier.
129 #
129 #
130 # - N*20 bytes: new changesets identifiers.
130 # - N*20 bytes: new changesets identifiers.
131 #
131 #
132 # - M bytes: metadata as a sequence of nul-terminated strings. Each
132 # - M bytes: metadata as a sequence of nul-terminated strings. Each
133 # string contains a key and a value, separated by a colon ':', without
133 # string contains a key and a value, separated by a colon ':', without
134 # additional encoding. Keys cannot contain '\0' or ':' and values
134 # additional encoding. Keys cannot contain '\0' or ':' and values
135 # cannot contain '\0'.
135 # cannot contain '\0'.
136 _fm0version = 0
136 _fm0version = 0
137 _fm0fixed = '>BIB20s'
137 _fm0fixed = '>BIB20s'
138 _fm0node = '20s'
138 _fm0node = '20s'
139 _fm0fsize = struct.calcsize(_fm0fixed)
139 _fm0fsize = struct.calcsize(_fm0fixed)
140 _fm0fnodesize = struct.calcsize(_fm0node)
140 _fm0fnodesize = struct.calcsize(_fm0node)
141
141
142 def _fm0readmarkers(data, off=0):
142 def _fm0readmarkers(data, off=0):
143 # Loop on markers
143 # Loop on markers
144 l = len(data)
144 l = len(data)
145 while off + _fm0fsize <= l:
145 while off + _fm0fsize <= l:
146 # read fixed part
146 # read fixed part
147 cur = data[off:off + _fm0fsize]
147 cur = data[off:off + _fm0fsize]
148 off += _fm0fsize
148 off += _fm0fsize
149 nbsuc, mdsize, flags, pre = _unpack(_fm0fixed, cur)
149 nbsuc, mdsize, flags, pre = _unpack(_fm0fixed, cur)
150 # read replacement
150 # read replacement
151 sucs = ()
151 sucs = ()
152 if nbsuc:
152 if nbsuc:
153 s = (_fm0fnodesize * nbsuc)
153 s = (_fm0fnodesize * nbsuc)
154 cur = data[off:off + s]
154 cur = data[off:off + s]
155 sucs = _unpack(_fm0node * nbsuc, cur)
155 sucs = _unpack(_fm0node * nbsuc, cur)
156 off += s
156 off += s
157 # read metadata
157 # read metadata
158 # (metadata will be decoded on demand)
158 # (metadata will be decoded on demand)
159 metadata = data[off:off + mdsize]
159 metadata = data[off:off + mdsize]
160 if len(metadata) != mdsize:
160 if len(metadata) != mdsize:
161 raise util.Abort(_('parsing obsolete marker: metadata is too '
161 raise util.Abort(_('parsing obsolete marker: metadata is too '
162 'short, %d bytes expected, got %d')
162 'short, %d bytes expected, got %d')
163 % (mdsize, len(metadata)))
163 % (mdsize, len(metadata)))
164 off += mdsize
164 off += mdsize
165 meta = decodemeta(metadata)
165 meta = decodemeta(metadata)
166 try:
166 try:
167 when, offset = meta.pop('date', '0 0').split(' ')
167 when, offset = meta.pop('date', '0 0').split(' ')
168 date = float(when), int(offset)
168 date = float(when), int(offset)
169 except ValueError:
169 except ValueError:
170 date = (0., 0)
170 date = (0., 0)
171 parents = None
171 parents = None
172 if 'p2' in meta:
172 if 'p2' in meta:
173 parents = (meta.pop('p1', None), meta.pop('p2', None))
173 parents = (meta.pop('p1', None), meta.pop('p2', None))
174 elif 'p1' in meta:
174 elif 'p1' in meta:
175 parents = (meta.pop('p1', None),)
175 parents = (meta.pop('p1', None),)
176 elif 'p0' in meta:
176 elif 'p0' in meta:
177 parents = ()
177 parents = ()
178 if parents is not None:
178 if parents is not None:
179 try:
179 try:
180 parents = tuple(node.bin(p) for p in parents)
180 parents = tuple(node.bin(p) for p in parents)
181 # if parent content is not a nodeid, drop the data
181 # if parent content is not a nodeid, drop the data
182 for p in parents:
182 for p in parents:
183 if len(p) != 20:
183 if len(p) != 20:
184 parents = None
184 parents = None
185 break
185 break
186 except TypeError:
186 except TypeError:
187 # if content cannot be translated to nodeid drop the data.
187 # if content cannot be translated to nodeid drop the data.
188 parents = None
188 parents = None
189
189
190 metadata = encodemeta(meta)
190 metadata = encodemeta(meta)
191
191
192 yield (pre, sucs, flags, metadata, date, parents)
192 yield (pre, sucs, flags, metadata, date, parents)
193
193
194 def _fm0encodeonemarker(marker):
194 def _fm0encodeonemarker(marker):
195 pre, sucs, flags, metadata, date, parents = marker
195 pre, sucs, flags, metadata, date, parents = marker
196 metadata = decodemeta(metadata)
196 metadata = decodemeta(metadata)
197 metadata['date'] = '%d %i' % date
197 metadata['date'] = '%d %i' % date
198 if parents is not None:
198 if parents is not None:
199 if not parents:
199 if not parents:
200 # mark that we explicitly recorded no parents
200 # mark that we explicitly recorded no parents
201 metadata['p0'] = ''
201 metadata['p0'] = ''
202 for i, p in enumerate(parents):
202 for i, p in enumerate(parents):
203 metadata['p%i' % (i + 1)] = node.hex(p)
203 metadata['p%i' % (i + 1)] = node.hex(p)
204 metadata = encodemeta(metadata)
204 metadata = encodemeta(metadata)
205 nbsuc = len(sucs)
205 nbsuc = len(sucs)
206 format = _fm0fixed + (_fm0node * nbsuc)
206 format = _fm0fixed + (_fm0node * nbsuc)
207 data = [nbsuc, len(metadata), flags, pre]
207 data = [nbsuc, len(metadata), flags, pre]
208 data.extend(sucs)
208 data.extend(sucs)
209 return _pack(format, *data) + metadata
209 return _pack(format, *data) + metadata
210
210
211 # mapping to read/write various marker formats
211 # mapping to read/write various marker formats
212 # <version> -> (decoder, encoder)
212 # <version> -> (decoder, encoder)
213 formats = {0: (_fm0readmarkers, _fm0encodeonemarker)}
213 formats = {0: (_fm0readmarkers, _fm0encodeonemarker)}
214
214
215 def _readmarkers(data):
215 def _readmarkers(data):
216 """Read and enumerate markers from raw data"""
216 """Read and enumerate markers from raw data"""
217 off = 0
217 off = 0
218 diskversion = _unpack('>B', data[off:off + 1])[0]
218 diskversion = _unpack('>B', data[off:off + 1])[0]
219 off += 1
219 off += 1
220 if diskversion not in formats:
220 if diskversion not in formats:
221 raise util.Abort(_('parsing obsolete marker: unknown version %r')
221 raise util.Abort(_('parsing obsolete marker: unknown version %r')
222 % diskversion)
222 % diskversion)
223 return diskversion, formats[diskversion][0](data, off)
223 return diskversion, formats[diskversion][0](data, off)
224
224
225 def encodemarkers(markers, addheader=False, version=_fm0version):
225 def encodemarkers(markers, addheader=False, version=_fm0version):
226 # Kept separate from flushmarkers(), it will be reused for
226 # Kept separate from flushmarkers(), it will be reused for
227 # markers exchange.
227 # markers exchange.
228 encodeone = formats[version][1]
228 encodeone = formats[version][1]
229 if addheader:
229 if addheader:
230 yield _pack('>B', _fm0version)
230 yield _pack('>B', version)
231 for marker in markers:
231 for marker in markers:
232 yield encodeone(marker)
232 yield encodeone(marker)
233
233
234
234
235 def encodemeta(meta):
235 def encodemeta(meta):
236 """Return encoded metadata string to string mapping.
236 """Return encoded metadata string to string mapping.
237
237
238 Assume no ':' in key and no '\0' in both key and value."""
238 Assume no ':' in key and no '\0' in both key and value."""
239 for key, value in meta.iteritems():
239 for key, value in meta.iteritems():
240 if ':' in key or '\0' in key:
240 if ':' in key or '\0' in key:
241 raise ValueError("':' and '\0' are forbidden in metadata key'")
241 raise ValueError("':' and '\0' are forbidden in metadata key'")
242 if '\0' in value:
242 if '\0' in value:
243 raise ValueError("':' is forbidden in metadata value'")
243 raise ValueError("':' is forbidden in metadata value'")
244 return '\0'.join(['%s:%s' % (k, meta[k]) for k in sorted(meta)])
244 return '\0'.join(['%s:%s' % (k, meta[k]) for k in sorted(meta)])
245
245
246 def decodemeta(data):
246 def decodemeta(data):
247 """Return string to string dictionary from encoded version."""
247 """Return string to string dictionary from encoded version."""
248 d = {}
248 d = {}
249 for l in data.split('\0'):
249 for l in data.split('\0'):
250 if l:
250 if l:
251 key, value = l.split(':')
251 key, value = l.split(':')
252 d[key] = value
252 d[key] = value
253 return d
253 return d
254
254
255 class marker(object):
255 class marker(object):
256 """Wrap obsolete marker raw data"""
256 """Wrap obsolete marker raw data"""
257
257
258 def __init__(self, repo, data):
258 def __init__(self, repo, data):
259 # the repo argument will be used to create changectx in later version
259 # the repo argument will be used to create changectx in later version
260 self._repo = repo
260 self._repo = repo
261 self._data = data
261 self._data = data
262 self._decodedmeta = None
262 self._decodedmeta = None
263
263
264 def __hash__(self):
264 def __hash__(self):
265 return hash(self._data)
265 return hash(self._data)
266
266
267 def __eq__(self, other):
267 def __eq__(self, other):
268 if type(other) != type(self):
268 if type(other) != type(self):
269 return False
269 return False
270 return self._data == other._data
270 return self._data == other._data
271
271
272 def precnode(self):
272 def precnode(self):
273 """Precursor changeset node identifier"""
273 """Precursor changeset node identifier"""
274 return self._data[0]
274 return self._data[0]
275
275
276 def succnodes(self):
276 def succnodes(self):
277 """List of successor changesets node identifiers"""
277 """List of successor changesets node identifiers"""
278 return self._data[1]
278 return self._data[1]
279
279
280 def parentnodes(self):
280 def parentnodes(self):
281 """Parents of the precursors (None if not recorded)"""
281 """Parents of the precursors (None if not recorded)"""
282 return self._data[5]
282 return self._data[5]
283
283
284 def metadata(self):
284 def metadata(self):
285 """Decoded metadata dictionary"""
285 """Decoded metadata dictionary"""
286 if self._decodedmeta is None:
286 if self._decodedmeta is None:
287 self._decodedmeta = decodemeta(self._data[3])
287 self._decodedmeta = decodemeta(self._data[3])
288 return self._decodedmeta
288 return self._decodedmeta
289
289
290 def date(self):
290 def date(self):
291 """Creation date as (unixtime, offset)"""
291 """Creation date as (unixtime, offset)"""
292 return self._data[4]
292 return self._data[4]
293
293
294 def flags(self):
294 def flags(self):
295 """The flags field of the marker"""
295 """The flags field of the marker"""
296 return self._data[2]
296 return self._data[2]
297
297
298 class obsstore(object):
298 class obsstore(object):
299 """Store obsolete markers
299 """Store obsolete markers
300
300
301 Markers can be accessed with two mappings:
301 Markers can be accessed with two mappings:
302 - precursors[x] -> set(markers on precursors edges of x)
302 - precursors[x] -> set(markers on precursors edges of x)
303 - successors[x] -> set(markers on successors edges of x)
303 - successors[x] -> set(markers on successors edges of x)
304 - children[x] -> set(markers on precursors edges of children(x)
304 - children[x] -> set(markers on precursors edges of children(x)
305 """
305 """
306
306
307 fields = ('prec', 'succs', 'flag', 'meta', 'date', 'parents')
307 fields = ('prec', 'succs', 'flag', 'meta', 'date', 'parents')
308 # prec: nodeid, precursor changesets
308 # prec: nodeid, precursor changesets
309 # succs: tuple of nodeid, successor changesets (0-N length)
309 # succs: tuple of nodeid, successor changesets (0-N length)
310 # flag: integer, flag field carrying modifier for the markers (see doc)
310 # flag: integer, flag field carrying modifier for the markers (see doc)
311 # meta: binary blob, encoded metadata dictionary
311 # meta: binary blob, encoded metadata dictionary
312 # date: (float, int) tuple, date of marker creation
312 # date: (float, int) tuple, date of marker creation
313 # parents: (tuple of nodeid) or None, parents of precursors
313 # parents: (tuple of nodeid) or None, parents of precursors
314 # None is used when no data has been recorded
314 # None is used when no data has been recorded
315
315
316 def __init__(self, sopener):
316 def __init__(self, sopener):
317 # caches for various obsolescence related cache
317 # caches for various obsolescence related cache
318 self.caches = {}
318 self.caches = {}
319 self._all = []
319 self._all = []
320 self.precursors = {}
320 self.precursors = {}
321 self.successors = {}
321 self.successors = {}
322 self.children = {}
322 self.children = {}
323 self.sopener = sopener
323 self.sopener = sopener
324 data = sopener.tryread('obsstore')
324 data = sopener.tryread('obsstore')
325 self._version = _fm0version
325 self._version = _fm0version
326 if data:
326 if data:
327 self._version, markers = _readmarkers(data)
327 self._version, markers = _readmarkers(data)
328 self._load(markers)
328 self._load(markers)
329
329
330 def __iter__(self):
330 def __iter__(self):
331 return iter(self._all)
331 return iter(self._all)
332
332
333 def __len__(self):
333 def __len__(self):
334 return len(self._all)
334 return len(self._all)
335
335
336 def __nonzero__(self):
336 def __nonzero__(self):
337 return bool(self._all)
337 return bool(self._all)
338
338
339 def create(self, transaction, prec, succs=(), flag=0, parents=None,
339 def create(self, transaction, prec, succs=(), flag=0, parents=None,
340 date=None, metadata=None):
340 date=None, metadata=None):
341 """obsolete: add a new obsolete marker
341 """obsolete: add a new obsolete marker
342
342
343 * ensuring it is hashable
343 * ensuring it is hashable
344 * check mandatory metadata
344 * check mandatory metadata
345 * encode metadata
345 * encode metadata
346
346
347 If you are a human writing code creating marker you want to use the
347 If you are a human writing code creating marker you want to use the
348 `createmarkers` function in this module instead.
348 `createmarkers` function in this module instead.
349
349
350 return True if a new marker have been added, False if the markers
350 return True if a new marker have been added, False if the markers
351 already existed (no op).
351 already existed (no op).
352 """
352 """
353 if metadata is None:
353 if metadata is None:
354 metadata = {}
354 metadata = {}
355 if date is None:
355 if date is None:
356 if 'date' in metadata:
356 if 'date' in metadata:
357 # as a courtesy for out-of-tree extensions
357 # as a courtesy for out-of-tree extensions
358 date = util.parsedate(metadata.pop('date'))
358 date = util.parsedate(metadata.pop('date'))
359 else:
359 else:
360 date = util.makedate()
360 date = util.makedate()
361 if len(prec) != 20:
361 if len(prec) != 20:
362 raise ValueError(prec)
362 raise ValueError(prec)
363 for succ in succs:
363 for succ in succs:
364 if len(succ) != 20:
364 if len(succ) != 20:
365 raise ValueError(succ)
365 raise ValueError(succ)
366 if prec in succs:
366 if prec in succs:
367 raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
367 raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
368 marker = (str(prec), tuple(succs), int(flag), encodemeta(metadata),
368 marker = (str(prec), tuple(succs), int(flag), encodemeta(metadata),
369 date, parents)
369 date, parents)
370 return bool(self.add(transaction, [marker]))
370 return bool(self.add(transaction, [marker]))
371
371
372 def add(self, transaction, markers):
372 def add(self, transaction, markers):
373 """Add new markers to the store
373 """Add new markers to the store
374
374
375 Take care of filtering duplicate.
375 Take care of filtering duplicate.
376 Return the number of new marker."""
376 Return the number of new marker."""
377 if not _enabled:
377 if not _enabled:
378 raise util.Abort('obsolete feature is not enabled on this repo')
378 raise util.Abort('obsolete feature is not enabled on this repo')
379 known = set(self._all)
379 known = set(self._all)
380 new = []
380 new = []
381 for m in markers:
381 for m in markers:
382 if m not in known:
382 if m not in known:
383 known.add(m)
383 known.add(m)
384 new.append(m)
384 new.append(m)
385 if new:
385 if new:
386 f = self.sopener('obsstore', 'ab')
386 f = self.sopener('obsstore', 'ab')
387 try:
387 try:
388 # Whether the file's current position is at the begin or at
388 # Whether the file's current position is at the begin or at
389 # the end after opening a file for appending is implementation
389 # the end after opening a file for appending is implementation
390 # defined. So we must seek to the end before calling tell(),
390 # defined. So we must seek to the end before calling tell(),
391 # or we may get a zero offset for non-zero sized files on
391 # or we may get a zero offset for non-zero sized files on
392 # some platforms (issue3543).
392 # some platforms (issue3543).
393 f.seek(0, _SEEK_END)
393 f.seek(0, _SEEK_END)
394 offset = f.tell()
394 offset = f.tell()
395 transaction.add('obsstore', offset)
395 transaction.add('obsstore', offset)
396 # offset == 0: new file - add the version header
396 # offset == 0: new file - add the version header
397 for bytes in encodemarkers(new, offset == 0, self._version):
397 for bytes in encodemarkers(new, offset == 0, self._version):
398 f.write(bytes)
398 f.write(bytes)
399 finally:
399 finally:
400 # XXX: f.close() == filecache invalidation == obsstore rebuilt.
400 # XXX: f.close() == filecache invalidation == obsstore rebuilt.
401 # call 'filecacheentry.refresh()' here
401 # call 'filecacheentry.refresh()' here
402 f.close()
402 f.close()
403 self._load(new)
403 self._load(new)
404 # new marker *may* have changed several set. invalidate the cache.
404 # new marker *may* have changed several set. invalidate the cache.
405 self.caches.clear()
405 self.caches.clear()
406 # records the number of new markers for the transaction hooks
406 # records the number of new markers for the transaction hooks
407 previous = int(transaction.hookargs.get('new_obsmarkers', '0'))
407 previous = int(transaction.hookargs.get('new_obsmarkers', '0'))
408 transaction.hookargs['new_obsmarkers'] = str(previous + len(new))
408 transaction.hookargs['new_obsmarkers'] = str(previous + len(new))
409 return len(new)
409 return len(new)
410
410
411 def mergemarkers(self, transaction, data):
411 def mergemarkers(self, transaction, data):
412 """merge a binary stream of markers inside the obsstore
412 """merge a binary stream of markers inside the obsstore
413
413
414 Returns the number of new markers added."""
414 Returns the number of new markers added."""
415 version, markers = _readmarkers(data)
415 version, markers = _readmarkers(data)
416 return self.add(transaction, markers)
416 return self.add(transaction, markers)
417
417
418 def _load(self, markers):
418 def _load(self, markers):
419 for mark in markers:
419 for mark in markers:
420 self._all.append(mark)
420 self._all.append(mark)
421 pre, sucs = mark[:2]
421 pre, sucs = mark[:2]
422 self.successors.setdefault(pre, set()).add(mark)
422 self.successors.setdefault(pre, set()).add(mark)
423 for suc in sucs:
423 for suc in sucs:
424 self.precursors.setdefault(suc, set()).add(mark)
424 self.precursors.setdefault(suc, set()).add(mark)
425 parents = mark[5]
425 parents = mark[5]
426 if parents is not None:
426 if parents is not None:
427 for p in parents:
427 for p in parents:
428 self.children.setdefault(p, set()).add(mark)
428 self.children.setdefault(p, set()).add(mark)
429 if node.nullid in self.precursors:
429 if node.nullid in self.precursors:
430 raise util.Abort(_('bad obsolescence marker detected: '
430 raise util.Abort(_('bad obsolescence marker detected: '
431 'invalid successors nullid'))
431 'invalid successors nullid'))
432 def relevantmarkers(self, nodes):
432 def relevantmarkers(self, nodes):
433 """return a set of all obsolescence markers relevant to a set of nodes.
433 """return a set of all obsolescence markers relevant to a set of nodes.
434
434
435 "relevant" to a set of nodes mean:
435 "relevant" to a set of nodes mean:
436
436
437 - marker that use this changeset as successor
437 - marker that use this changeset as successor
438 - prune marker of direct children on this changeset
438 - prune marker of direct children on this changeset
439 - recursive application of the two rules on precursors of these markers
439 - recursive application of the two rules on precursors of these markers
440
440
441 It is a set so you cannot rely on order."""
441 It is a set so you cannot rely on order."""
442
442
443 pendingnodes = set(nodes)
443 pendingnodes = set(nodes)
444 seenmarkers = set()
444 seenmarkers = set()
445 seennodes = set(pendingnodes)
445 seennodes = set(pendingnodes)
446 precursorsmarkers = self.precursors
446 precursorsmarkers = self.precursors
447 children = self.children
447 children = self.children
448 while pendingnodes:
448 while pendingnodes:
449 direct = set()
449 direct = set()
450 for current in pendingnodes:
450 for current in pendingnodes:
451 direct.update(precursorsmarkers.get(current, ()))
451 direct.update(precursorsmarkers.get(current, ()))
452 pruned = [m for m in children.get(current, ()) if not m[1]]
452 pruned = [m for m in children.get(current, ()) if not m[1]]
453 direct.update(pruned)
453 direct.update(pruned)
454 direct -= seenmarkers
454 direct -= seenmarkers
455 pendingnodes = set([m[0] for m in direct])
455 pendingnodes = set([m[0] for m in direct])
456 seenmarkers |= direct
456 seenmarkers |= direct
457 pendingnodes -= seennodes
457 pendingnodes -= seennodes
458 seennodes |= pendingnodes
458 seennodes |= pendingnodes
459 return seenmarkers
459 return seenmarkers
460
460
461 def commonversion(versions):
461 def commonversion(versions):
462 """Return the newest version listed in both versions and our local formats.
462 """Return the newest version listed in both versions and our local formats.
463
463
464 Returns None if no common version exists.
464 Returns None if no common version exists.
465 """
465 """
466 versions.sort(reverse=True)
466 versions.sort(reverse=True)
467 # search for highest version known on both side
467 # search for highest version known on both side
468 for v in versions:
468 for v in versions:
469 if v in formats:
469 if v in formats:
470 return v
470 return v
471 return None
471 return None
472
472
473 # arbitrary picked to fit into 8K limit from HTTP server
473 # arbitrary picked to fit into 8K limit from HTTP server
474 # you have to take in account:
474 # you have to take in account:
475 # - the version header
475 # - the version header
476 # - the base85 encoding
476 # - the base85 encoding
477 _maxpayload = 5300
477 _maxpayload = 5300
478
478
479 def _pushkeyescape(markers):
479 def _pushkeyescape(markers):
480 """encode markers into a dict suitable for pushkey exchange
480 """encode markers into a dict suitable for pushkey exchange
481
481
482 - binary data is base85 encoded
482 - binary data is base85 encoded
483 - split in chunks smaller than 5300 bytes"""
483 - split in chunks smaller than 5300 bytes"""
484 keys = {}
484 keys = {}
485 parts = []
485 parts = []
486 currentlen = _maxpayload * 2 # ensure we create a new part
486 currentlen = _maxpayload * 2 # ensure we create a new part
487 for marker in markers:
487 for marker in markers:
488 nextdata = _fm0encodeonemarker(marker)
488 nextdata = _fm0encodeonemarker(marker)
489 if (len(nextdata) + currentlen > _maxpayload):
489 if (len(nextdata) + currentlen > _maxpayload):
490 currentpart = []
490 currentpart = []
491 currentlen = 0
491 currentlen = 0
492 parts.append(currentpart)
492 parts.append(currentpart)
493 currentpart.append(nextdata)
493 currentpart.append(nextdata)
494 currentlen += len(nextdata)
494 currentlen += len(nextdata)
495 for idx, part in enumerate(reversed(parts)):
495 for idx, part in enumerate(reversed(parts)):
496 data = ''.join([_pack('>B', _fm0version)] + part)
496 data = ''.join([_pack('>B', _fm0version)] + part)
497 keys['dump%i' % idx] = base85.b85encode(data)
497 keys['dump%i' % idx] = base85.b85encode(data)
498 return keys
498 return keys
499
499
500 def listmarkers(repo):
500 def listmarkers(repo):
501 """List markers over pushkey"""
501 """List markers over pushkey"""
502 if not repo.obsstore:
502 if not repo.obsstore:
503 return {}
503 return {}
504 return _pushkeyescape(repo.obsstore)
504 return _pushkeyescape(repo.obsstore)
505
505
506 def pushmarker(repo, key, old, new):
506 def pushmarker(repo, key, old, new):
507 """Push markers over pushkey"""
507 """Push markers over pushkey"""
508 if not key.startswith('dump'):
508 if not key.startswith('dump'):
509 repo.ui.warn(_('unknown key: %r') % key)
509 repo.ui.warn(_('unknown key: %r') % key)
510 return 0
510 return 0
511 if old:
511 if old:
512 repo.ui.warn(_('unexpected old value for %r') % key)
512 repo.ui.warn(_('unexpected old value for %r') % key)
513 return 0
513 return 0
514 data = base85.b85decode(new)
514 data = base85.b85decode(new)
515 lock = repo.lock()
515 lock = repo.lock()
516 try:
516 try:
517 tr = repo.transaction('pushkey: obsolete markers')
517 tr = repo.transaction('pushkey: obsolete markers')
518 try:
518 try:
519 repo.obsstore.mergemarkers(tr, data)
519 repo.obsstore.mergemarkers(tr, data)
520 tr.close()
520 tr.close()
521 return 1
521 return 1
522 finally:
522 finally:
523 tr.release()
523 tr.release()
524 finally:
524 finally:
525 lock.release()
525 lock.release()
526
526
527 def getmarkers(repo, nodes=None):
527 def getmarkers(repo, nodes=None):
528 """returns markers known in a repository
528 """returns markers known in a repository
529
529
530 If <nodes> is specified, only markers "relevant" to those nodes are are
530 If <nodes> is specified, only markers "relevant" to those nodes are are
531 returned"""
531 returned"""
532 if nodes is None:
532 if nodes is None:
533 rawmarkers = repo.obsstore
533 rawmarkers = repo.obsstore
534 else:
534 else:
535 rawmarkers = repo.obsstore.relevantmarkers(nodes)
535 rawmarkers = repo.obsstore.relevantmarkers(nodes)
536
536
537 for markerdata in rawmarkers:
537 for markerdata in rawmarkers:
538 yield marker(repo, markerdata)
538 yield marker(repo, markerdata)
539
539
540 def relevantmarkers(repo, node):
540 def relevantmarkers(repo, node):
541 """all obsolete markers relevant to some revision"""
541 """all obsolete markers relevant to some revision"""
542 for markerdata in repo.obsstore.relevantmarkers(node):
542 for markerdata in repo.obsstore.relevantmarkers(node):
543 yield marker(repo, markerdata)
543 yield marker(repo, markerdata)
544
544
545
545
546 def precursormarkers(ctx):
546 def precursormarkers(ctx):
547 """obsolete marker marking this changeset as a successors"""
547 """obsolete marker marking this changeset as a successors"""
548 for data in ctx._repo.obsstore.precursors.get(ctx.node(), ()):
548 for data in ctx._repo.obsstore.precursors.get(ctx.node(), ()):
549 yield marker(ctx._repo, data)
549 yield marker(ctx._repo, data)
550
550
551 def successormarkers(ctx):
551 def successormarkers(ctx):
552 """obsolete marker making this changeset obsolete"""
552 """obsolete marker making this changeset obsolete"""
553 for data in ctx._repo.obsstore.successors.get(ctx.node(), ()):
553 for data in ctx._repo.obsstore.successors.get(ctx.node(), ()):
554 yield marker(ctx._repo, data)
554 yield marker(ctx._repo, data)
555
555
556 def allsuccessors(obsstore, nodes, ignoreflags=0):
556 def allsuccessors(obsstore, nodes, ignoreflags=0):
557 """Yield node for every successor of <nodes>.
557 """Yield node for every successor of <nodes>.
558
558
559 Some successors may be unknown locally.
559 Some successors may be unknown locally.
560
560
561 This is a linear yield unsuited to detecting split changesets. It includes
561 This is a linear yield unsuited to detecting split changesets. It includes
562 initial nodes too."""
562 initial nodes too."""
563 remaining = set(nodes)
563 remaining = set(nodes)
564 seen = set(remaining)
564 seen = set(remaining)
565 while remaining:
565 while remaining:
566 current = remaining.pop()
566 current = remaining.pop()
567 yield current
567 yield current
568 for mark in obsstore.successors.get(current, ()):
568 for mark in obsstore.successors.get(current, ()):
569 # ignore marker flagged with specified flag
569 # ignore marker flagged with specified flag
570 if mark[2] & ignoreflags:
570 if mark[2] & ignoreflags:
571 continue
571 continue
572 for suc in mark[1]:
572 for suc in mark[1]:
573 if suc not in seen:
573 if suc not in seen:
574 seen.add(suc)
574 seen.add(suc)
575 remaining.add(suc)
575 remaining.add(suc)
576
576
577 def allprecursors(obsstore, nodes, ignoreflags=0):
577 def allprecursors(obsstore, nodes, ignoreflags=0):
578 """Yield node for every precursors of <nodes>.
578 """Yield node for every precursors of <nodes>.
579
579
580 Some precursors may be unknown locally.
580 Some precursors may be unknown locally.
581
581
582 This is a linear yield unsuited to detecting folded changesets. It includes
582 This is a linear yield unsuited to detecting folded changesets. It includes
583 initial nodes too."""
583 initial nodes too."""
584
584
585 remaining = set(nodes)
585 remaining = set(nodes)
586 seen = set(remaining)
586 seen = set(remaining)
587 while remaining:
587 while remaining:
588 current = remaining.pop()
588 current = remaining.pop()
589 yield current
589 yield current
590 for mark in obsstore.precursors.get(current, ()):
590 for mark in obsstore.precursors.get(current, ()):
591 # ignore marker flagged with specified flag
591 # ignore marker flagged with specified flag
592 if mark[2] & ignoreflags:
592 if mark[2] & ignoreflags:
593 continue
593 continue
594 suc = mark[0]
594 suc = mark[0]
595 if suc not in seen:
595 if suc not in seen:
596 seen.add(suc)
596 seen.add(suc)
597 remaining.add(suc)
597 remaining.add(suc)
598
598
599 def foreground(repo, nodes):
599 def foreground(repo, nodes):
600 """return all nodes in the "foreground" of other node
600 """return all nodes in the "foreground" of other node
601
601
602 The foreground of a revision is anything reachable using parent -> children
602 The foreground of a revision is anything reachable using parent -> children
603 or precursor -> successor relation. It is very similar to "descendant" but
603 or precursor -> successor relation. It is very similar to "descendant" but
604 augmented with obsolescence information.
604 augmented with obsolescence information.
605
605
606 Beware that possible obsolescence cycle may result if complex situation.
606 Beware that possible obsolescence cycle may result if complex situation.
607 """
607 """
608 repo = repo.unfiltered()
608 repo = repo.unfiltered()
609 foreground = set(repo.set('%ln::', nodes))
609 foreground = set(repo.set('%ln::', nodes))
610 if repo.obsstore:
610 if repo.obsstore:
611 # We only need this complicated logic if there is obsolescence
611 # We only need this complicated logic if there is obsolescence
612 # XXX will probably deserve an optimised revset.
612 # XXX will probably deserve an optimised revset.
613 nm = repo.changelog.nodemap
613 nm = repo.changelog.nodemap
614 plen = -1
614 plen = -1
615 # compute the whole set of successors or descendants
615 # compute the whole set of successors or descendants
616 while len(foreground) != plen:
616 while len(foreground) != plen:
617 plen = len(foreground)
617 plen = len(foreground)
618 succs = set(c.node() for c in foreground)
618 succs = set(c.node() for c in foreground)
619 mutable = [c.node() for c in foreground if c.mutable()]
619 mutable = [c.node() for c in foreground if c.mutable()]
620 succs.update(allsuccessors(repo.obsstore, mutable))
620 succs.update(allsuccessors(repo.obsstore, mutable))
621 known = (n for n in succs if n in nm)
621 known = (n for n in succs if n in nm)
622 foreground = set(repo.set('%ln::', known))
622 foreground = set(repo.set('%ln::', known))
623 return set(c.node() for c in foreground)
623 return set(c.node() for c in foreground)
624
624
625
625
626 def successorssets(repo, initialnode, cache=None):
626 def successorssets(repo, initialnode, cache=None):
627 """Return all set of successors of initial nodes
627 """Return all set of successors of initial nodes
628
628
629 The successors set of a changeset A are a group of revisions that succeed
629 The successors set of a changeset A are a group of revisions that succeed
630 A. It succeeds A as a consistent whole, each revision being only a partial
630 A. It succeeds A as a consistent whole, each revision being only a partial
631 replacement. The successors set contains non-obsolete changesets only.
631 replacement. The successors set contains non-obsolete changesets only.
632
632
633 This function returns the full list of successor sets which is why it
633 This function returns the full list of successor sets which is why it
634 returns a list of tuples and not just a single tuple. Each tuple is a valid
634 returns a list of tuples and not just a single tuple. Each tuple is a valid
635 successors set. Not that (A,) may be a valid successors set for changeset A
635 successors set. Not that (A,) may be a valid successors set for changeset A
636 (see below).
636 (see below).
637
637
638 In most cases, a changeset A will have a single element (e.g. the changeset
638 In most cases, a changeset A will have a single element (e.g. the changeset
639 A is replaced by A') in its successors set. Though, it is also common for a
639 A is replaced by A') in its successors set. Though, it is also common for a
640 changeset A to have no elements in its successor set (e.g. the changeset
640 changeset A to have no elements in its successor set (e.g. the changeset
641 has been pruned). Therefore, the returned list of successors sets will be
641 has been pruned). Therefore, the returned list of successors sets will be
642 [(A',)] or [], respectively.
642 [(A',)] or [], respectively.
643
643
644 When a changeset A is split into A' and B', however, it will result in a
644 When a changeset A is split into A' and B', however, it will result in a
645 successors set containing more than a single element, i.e. [(A',B')].
645 successors set containing more than a single element, i.e. [(A',B')].
646 Divergent changesets will result in multiple successors sets, i.e. [(A',),
646 Divergent changesets will result in multiple successors sets, i.e. [(A',),
647 (A'')].
647 (A'')].
648
648
649 If a changeset A is not obsolete, then it will conceptually have no
649 If a changeset A is not obsolete, then it will conceptually have no
650 successors set. To distinguish this from a pruned changeset, the successor
650 successors set. To distinguish this from a pruned changeset, the successor
651 set will only contain itself, i.e. [(A,)].
651 set will only contain itself, i.e. [(A,)].
652
652
653 Finally, successors unknown locally are considered to be pruned (obsoleted
653 Finally, successors unknown locally are considered to be pruned (obsoleted
654 without any successors).
654 without any successors).
655
655
656 The optional `cache` parameter is a dictionary that may contain precomputed
656 The optional `cache` parameter is a dictionary that may contain precomputed
657 successors sets. It is meant to reuse the computation of a previous call to
657 successors sets. It is meant to reuse the computation of a previous call to
658 `successorssets` when multiple calls are made at the same time. The cache
658 `successorssets` when multiple calls are made at the same time. The cache
659 dictionary is updated in place. The caller is responsible for its live
659 dictionary is updated in place. The caller is responsible for its live
660 spawn. Code that makes multiple calls to `successorssets` *must* use this
660 spawn. Code that makes multiple calls to `successorssets` *must* use this
661 cache mechanism or suffer terrible performances.
661 cache mechanism or suffer terrible performances.
662
662
663 """
663 """
664
664
665 succmarkers = repo.obsstore.successors
665 succmarkers = repo.obsstore.successors
666
666
667 # Stack of nodes we search successors sets for
667 # Stack of nodes we search successors sets for
668 toproceed = [initialnode]
668 toproceed = [initialnode]
669 # set version of above list for fast loop detection
669 # set version of above list for fast loop detection
670 # element added to "toproceed" must be added here
670 # element added to "toproceed" must be added here
671 stackedset = set(toproceed)
671 stackedset = set(toproceed)
672 if cache is None:
672 if cache is None:
673 cache = {}
673 cache = {}
674
674
675 # This while loop is the flattened version of a recursive search for
675 # This while loop is the flattened version of a recursive search for
676 # successors sets
676 # successors sets
677 #
677 #
678 # def successorssets(x):
678 # def successorssets(x):
679 # successors = directsuccessors(x)
679 # successors = directsuccessors(x)
680 # ss = [[]]
680 # ss = [[]]
681 # for succ in directsuccessors(x):
681 # for succ in directsuccessors(x):
682 # # product as in itertools cartesian product
682 # # product as in itertools cartesian product
683 # ss = product(ss, successorssets(succ))
683 # ss = product(ss, successorssets(succ))
684 # return ss
684 # return ss
685 #
685 #
686 # But we can not use plain recursive calls here:
686 # But we can not use plain recursive calls here:
687 # - that would blow the python call stack
687 # - that would blow the python call stack
688 # - obsolescence markers may have cycles, we need to handle them.
688 # - obsolescence markers may have cycles, we need to handle them.
689 #
689 #
690 # The `toproceed` list act as our call stack. Every node we search
690 # The `toproceed` list act as our call stack. Every node we search
691 # successors set for are stacked there.
691 # successors set for are stacked there.
692 #
692 #
693 # The `stackedset` is set version of this stack used to check if a node is
693 # The `stackedset` is set version of this stack used to check if a node is
694 # already stacked. This check is used to detect cycles and prevent infinite
694 # already stacked. This check is used to detect cycles and prevent infinite
695 # loop.
695 # loop.
696 #
696 #
697 # successors set of all nodes are stored in the `cache` dictionary.
697 # successors set of all nodes are stored in the `cache` dictionary.
698 #
698 #
699 # After this while loop ends we use the cache to return the successors sets
699 # After this while loop ends we use the cache to return the successors sets
700 # for the node requested by the caller.
700 # for the node requested by the caller.
701 while toproceed:
701 while toproceed:
702 # Every iteration tries to compute the successors sets of the topmost
702 # Every iteration tries to compute the successors sets of the topmost
703 # node of the stack: CURRENT.
703 # node of the stack: CURRENT.
704 #
704 #
705 # There are four possible outcomes:
705 # There are four possible outcomes:
706 #
706 #
707 # 1) We already know the successors sets of CURRENT:
707 # 1) We already know the successors sets of CURRENT:
708 # -> mission accomplished, pop it from the stack.
708 # -> mission accomplished, pop it from the stack.
709 # 2) Node is not obsolete:
709 # 2) Node is not obsolete:
710 # -> the node is its own successors sets. Add it to the cache.
710 # -> the node is its own successors sets. Add it to the cache.
711 # 3) We do not know successors set of direct successors of CURRENT:
711 # 3) We do not know successors set of direct successors of CURRENT:
712 # -> We add those successors to the stack.
712 # -> We add those successors to the stack.
713 # 4) We know successors sets of all direct successors of CURRENT:
713 # 4) We know successors sets of all direct successors of CURRENT:
714 # -> We can compute CURRENT successors set and add it to the
714 # -> We can compute CURRENT successors set and add it to the
715 # cache.
715 # cache.
716 #
716 #
717 current = toproceed[-1]
717 current = toproceed[-1]
718 if current in cache:
718 if current in cache:
719 # case (1): We already know the successors sets
719 # case (1): We already know the successors sets
720 stackedset.remove(toproceed.pop())
720 stackedset.remove(toproceed.pop())
721 elif current not in succmarkers:
721 elif current not in succmarkers:
722 # case (2): The node is not obsolete.
722 # case (2): The node is not obsolete.
723 if current in repo:
723 if current in repo:
724 # We have a valid last successors.
724 # We have a valid last successors.
725 cache[current] = [(current,)]
725 cache[current] = [(current,)]
726 else:
726 else:
727 # Final obsolete version is unknown locally.
727 # Final obsolete version is unknown locally.
728 # Do not count that as a valid successors
728 # Do not count that as a valid successors
729 cache[current] = []
729 cache[current] = []
730 else:
730 else:
731 # cases (3) and (4)
731 # cases (3) and (4)
732 #
732 #
733 # We proceed in two phases. Phase 1 aims to distinguish case (3)
733 # We proceed in two phases. Phase 1 aims to distinguish case (3)
734 # from case (4):
734 # from case (4):
735 #
735 #
736 # For each direct successors of CURRENT, we check whether its
736 # For each direct successors of CURRENT, we check whether its
737 # successors sets are known. If they are not, we stack the
737 # successors sets are known. If they are not, we stack the
738 # unknown node and proceed to the next iteration of the while
738 # unknown node and proceed to the next iteration of the while
739 # loop. (case 3)
739 # loop. (case 3)
740 #
740 #
741 # During this step, we may detect obsolescence cycles: a node
741 # During this step, we may detect obsolescence cycles: a node
742 # with unknown successors sets but already in the call stack.
742 # with unknown successors sets but already in the call stack.
743 # In such a situation, we arbitrary set the successors sets of
743 # In such a situation, we arbitrary set the successors sets of
744 # the node to nothing (node pruned) to break the cycle.
744 # the node to nothing (node pruned) to break the cycle.
745 #
745 #
746 # If no break was encountered we proceed to phase 2.
746 # If no break was encountered we proceed to phase 2.
747 #
747 #
748 # Phase 2 computes successors sets of CURRENT (case 4); see details
748 # Phase 2 computes successors sets of CURRENT (case 4); see details
749 # in phase 2 itself.
749 # in phase 2 itself.
750 #
750 #
751 # Note the two levels of iteration in each phase.
751 # Note the two levels of iteration in each phase.
752 # - The first one handles obsolescence markers using CURRENT as
752 # - The first one handles obsolescence markers using CURRENT as
753 # precursor (successors markers of CURRENT).
753 # precursor (successors markers of CURRENT).
754 #
754 #
755 # Having multiple entry here means divergence.
755 # Having multiple entry here means divergence.
756 #
756 #
757 # - The second one handles successors defined in each marker.
757 # - The second one handles successors defined in each marker.
758 #
758 #
759 # Having none means pruned node, multiple successors means split,
759 # Having none means pruned node, multiple successors means split,
760 # single successors are standard replacement.
760 # single successors are standard replacement.
761 #
761 #
762 for mark in sorted(succmarkers[current]):
762 for mark in sorted(succmarkers[current]):
763 for suc in mark[1]:
763 for suc in mark[1]:
764 if suc not in cache:
764 if suc not in cache:
765 if suc in stackedset:
765 if suc in stackedset:
766 # cycle breaking
766 # cycle breaking
767 cache[suc] = []
767 cache[suc] = []
768 else:
768 else:
769 # case (3) If we have not computed successors sets
769 # case (3) If we have not computed successors sets
770 # of one of those successors we add it to the
770 # of one of those successors we add it to the
771 # `toproceed` stack and stop all work for this
771 # `toproceed` stack and stop all work for this
772 # iteration.
772 # iteration.
773 toproceed.append(suc)
773 toproceed.append(suc)
774 stackedset.add(suc)
774 stackedset.add(suc)
775 break
775 break
776 else:
776 else:
777 continue
777 continue
778 break
778 break
779 else:
779 else:
780 # case (4): we know all successors sets of all direct
780 # case (4): we know all successors sets of all direct
781 # successors
781 # successors
782 #
782 #
783 # Successors set contributed by each marker depends on the
783 # Successors set contributed by each marker depends on the
784 # successors sets of all its "successors" node.
784 # successors sets of all its "successors" node.
785 #
785 #
786 # Each different marker is a divergence in the obsolescence
786 # Each different marker is a divergence in the obsolescence
787 # history. It contributes successors sets distinct from other
787 # history. It contributes successors sets distinct from other
788 # markers.
788 # markers.
789 #
789 #
790 # Within a marker, a successor may have divergent successors
790 # Within a marker, a successor may have divergent successors
791 # sets. In such a case, the marker will contribute multiple
791 # sets. In such a case, the marker will contribute multiple
792 # divergent successors sets. If multiple successors have
792 # divergent successors sets. If multiple successors have
793 # divergent successors sets, a Cartesian product is used.
793 # divergent successors sets, a Cartesian product is used.
794 #
794 #
795 # At the end we post-process successors sets to remove
795 # At the end we post-process successors sets to remove
796 # duplicated entry and successors set that are strict subset of
796 # duplicated entry and successors set that are strict subset of
797 # another one.
797 # another one.
798 succssets = []
798 succssets = []
799 for mark in sorted(succmarkers[current]):
799 for mark in sorted(succmarkers[current]):
800 # successors sets contributed by this marker
800 # successors sets contributed by this marker
801 markss = [[]]
801 markss = [[]]
802 for suc in mark[1]:
802 for suc in mark[1]:
803 # cardinal product with previous successors
803 # cardinal product with previous successors
804 productresult = []
804 productresult = []
805 for prefix in markss:
805 for prefix in markss:
806 for suffix in cache[suc]:
806 for suffix in cache[suc]:
807 newss = list(prefix)
807 newss = list(prefix)
808 for part in suffix:
808 for part in suffix:
809 # do not duplicated entry in successors set
809 # do not duplicated entry in successors set
810 # first entry wins.
810 # first entry wins.
811 if part not in newss:
811 if part not in newss:
812 newss.append(part)
812 newss.append(part)
813 productresult.append(newss)
813 productresult.append(newss)
814 markss = productresult
814 markss = productresult
815 succssets.extend(markss)
815 succssets.extend(markss)
816 # remove duplicated and subset
816 # remove duplicated and subset
817 seen = []
817 seen = []
818 final = []
818 final = []
819 candidate = sorted(((set(s), s) for s in succssets if s),
819 candidate = sorted(((set(s), s) for s in succssets if s),
820 key=lambda x: len(x[1]), reverse=True)
820 key=lambda x: len(x[1]), reverse=True)
821 for setversion, listversion in candidate:
821 for setversion, listversion in candidate:
822 for seenset in seen:
822 for seenset in seen:
823 if setversion.issubset(seenset):
823 if setversion.issubset(seenset):
824 break
824 break
825 else:
825 else:
826 final.append(listversion)
826 final.append(listversion)
827 seen.append(setversion)
827 seen.append(setversion)
828 final.reverse() # put small successors set first
828 final.reverse() # put small successors set first
829 cache[current] = final
829 cache[current] = final
830 return cache[initialnode]
830 return cache[initialnode]
831
831
832 def _knownrevs(repo, nodes):
832 def _knownrevs(repo, nodes):
833 """yield revision numbers of known nodes passed in parameters
833 """yield revision numbers of known nodes passed in parameters
834
834
835 Unknown revisions are silently ignored."""
835 Unknown revisions are silently ignored."""
836 torev = repo.changelog.nodemap.get
836 torev = repo.changelog.nodemap.get
837 for n in nodes:
837 for n in nodes:
838 rev = torev(n)
838 rev = torev(n)
839 if rev is not None:
839 if rev is not None:
840 yield rev
840 yield rev
841
841
842 # mapping of 'set-name' -> <function to compute this set>
842 # mapping of 'set-name' -> <function to compute this set>
843 cachefuncs = {}
843 cachefuncs = {}
844 def cachefor(name):
844 def cachefor(name):
845 """Decorator to register a function as computing the cache for a set"""
845 """Decorator to register a function as computing the cache for a set"""
846 def decorator(func):
846 def decorator(func):
847 assert name not in cachefuncs
847 assert name not in cachefuncs
848 cachefuncs[name] = func
848 cachefuncs[name] = func
849 return func
849 return func
850 return decorator
850 return decorator
851
851
852 def getrevs(repo, name):
852 def getrevs(repo, name):
853 """Return the set of revision that belong to the <name> set
853 """Return the set of revision that belong to the <name> set
854
854
855 Such access may compute the set and cache it for future use"""
855 Such access may compute the set and cache it for future use"""
856 repo = repo.unfiltered()
856 repo = repo.unfiltered()
857 if not repo.obsstore:
857 if not repo.obsstore:
858 return frozenset()
858 return frozenset()
859 if name not in repo.obsstore.caches:
859 if name not in repo.obsstore.caches:
860 repo.obsstore.caches[name] = cachefuncs[name](repo)
860 repo.obsstore.caches[name] = cachefuncs[name](repo)
861 return repo.obsstore.caches[name]
861 return repo.obsstore.caches[name]
862
862
863 # To be simple we need to invalidate obsolescence cache when:
863 # To be simple we need to invalidate obsolescence cache when:
864 #
864 #
865 # - new changeset is added:
865 # - new changeset is added:
866 # - public phase is changed
866 # - public phase is changed
867 # - obsolescence marker are added
867 # - obsolescence marker are added
868 # - strip is used a repo
868 # - strip is used a repo
869 def clearobscaches(repo):
869 def clearobscaches(repo):
870 """Remove all obsolescence related cache from a repo
870 """Remove all obsolescence related cache from a repo
871
871
872 This remove all cache in obsstore is the obsstore already exist on the
872 This remove all cache in obsstore is the obsstore already exist on the
873 repo.
873 repo.
874
874
875 (We could be smarter here given the exact event that trigger the cache
875 (We could be smarter here given the exact event that trigger the cache
876 clearing)"""
876 clearing)"""
877 # only clear cache is there is obsstore data in this repo
877 # only clear cache is there is obsstore data in this repo
878 if 'obsstore' in repo._filecache:
878 if 'obsstore' in repo._filecache:
879 repo.obsstore.caches.clear()
879 repo.obsstore.caches.clear()
880
880
881 @cachefor('obsolete')
881 @cachefor('obsolete')
882 def _computeobsoleteset(repo):
882 def _computeobsoleteset(repo):
883 """the set of obsolete revisions"""
883 """the set of obsolete revisions"""
884 obs = set()
884 obs = set()
885 getrev = repo.changelog.nodemap.get
885 getrev = repo.changelog.nodemap.get
886 getphase = repo._phasecache.phase
886 getphase = repo._phasecache.phase
887 for n in repo.obsstore.successors:
887 for n in repo.obsstore.successors:
888 rev = getrev(n)
888 rev = getrev(n)
889 if rev is not None and getphase(repo, rev):
889 if rev is not None and getphase(repo, rev):
890 obs.add(rev)
890 obs.add(rev)
891 return obs
891 return obs
892
892
893 @cachefor('unstable')
893 @cachefor('unstable')
894 def _computeunstableset(repo):
894 def _computeunstableset(repo):
895 """the set of non obsolete revisions with obsolete parents"""
895 """the set of non obsolete revisions with obsolete parents"""
896 # revset is not efficient enough here
896 # revset is not efficient enough here
897 # we do (obsolete()::) - obsolete() by hand
897 # we do (obsolete()::) - obsolete() by hand
898 obs = getrevs(repo, 'obsolete')
898 obs = getrevs(repo, 'obsolete')
899 if not obs:
899 if not obs:
900 return set()
900 return set()
901 cl = repo.changelog
901 cl = repo.changelog
902 return set(r for r in cl.descendants(obs) if r not in obs)
902 return set(r for r in cl.descendants(obs) if r not in obs)
903
903
904 @cachefor('suspended')
904 @cachefor('suspended')
905 def _computesuspendedset(repo):
905 def _computesuspendedset(repo):
906 """the set of obsolete parents with non obsolete descendants"""
906 """the set of obsolete parents with non obsolete descendants"""
907 suspended = repo.changelog.ancestors(getrevs(repo, 'unstable'))
907 suspended = repo.changelog.ancestors(getrevs(repo, 'unstable'))
908 return set(r for r in getrevs(repo, 'obsolete') if r in suspended)
908 return set(r for r in getrevs(repo, 'obsolete') if r in suspended)
909
909
910 @cachefor('extinct')
910 @cachefor('extinct')
911 def _computeextinctset(repo):
911 def _computeextinctset(repo):
912 """the set of obsolete parents without non obsolete descendants"""
912 """the set of obsolete parents without non obsolete descendants"""
913 return getrevs(repo, 'obsolete') - getrevs(repo, 'suspended')
913 return getrevs(repo, 'obsolete') - getrevs(repo, 'suspended')
914
914
915
915
916 @cachefor('bumped')
916 @cachefor('bumped')
917 def _computebumpedset(repo):
917 def _computebumpedset(repo):
918 """the set of revs trying to obsolete public revisions"""
918 """the set of revs trying to obsolete public revisions"""
919 bumped = set()
919 bumped = set()
920 # util function (avoid attribute lookup in the loop)
920 # util function (avoid attribute lookup in the loop)
921 phase = repo._phasecache.phase # would be faster to grab the full list
921 phase = repo._phasecache.phase # would be faster to grab the full list
922 public = phases.public
922 public = phases.public
923 cl = repo.changelog
923 cl = repo.changelog
924 torev = cl.nodemap.get
924 torev = cl.nodemap.get
925 obs = getrevs(repo, 'obsolete')
925 obs = getrevs(repo, 'obsolete')
926 for rev in repo:
926 for rev in repo:
927 # We only evaluate mutable, non-obsolete revision
927 # We only evaluate mutable, non-obsolete revision
928 if (public < phase(repo, rev)) and (rev not in obs):
928 if (public < phase(repo, rev)) and (rev not in obs):
929 node = cl.node(rev)
929 node = cl.node(rev)
930 # (future) A cache of precursors may worth if split is very common
930 # (future) A cache of precursors may worth if split is very common
931 for pnode in allprecursors(repo.obsstore, [node],
931 for pnode in allprecursors(repo.obsstore, [node],
932 ignoreflags=bumpedfix):
932 ignoreflags=bumpedfix):
933 prev = torev(pnode) # unfiltered! but so is phasecache
933 prev = torev(pnode) # unfiltered! but so is phasecache
934 if (prev is not None) and (phase(repo, prev) <= public):
934 if (prev is not None) and (phase(repo, prev) <= public):
935 # we have a public precursors
935 # we have a public precursors
936 bumped.add(rev)
936 bumped.add(rev)
937 break # Next draft!
937 break # Next draft!
938 return bumped
938 return bumped
939
939
940 @cachefor('divergent')
940 @cachefor('divergent')
941 def _computedivergentset(repo):
941 def _computedivergentset(repo):
942 """the set of rev that compete to be the final successors of some revision.
942 """the set of rev that compete to be the final successors of some revision.
943 """
943 """
944 divergent = set()
944 divergent = set()
945 obsstore = repo.obsstore
945 obsstore = repo.obsstore
946 newermap = {}
946 newermap = {}
947 for ctx in repo.set('(not public()) - obsolete()'):
947 for ctx in repo.set('(not public()) - obsolete()'):
948 mark = obsstore.precursors.get(ctx.node(), ())
948 mark = obsstore.precursors.get(ctx.node(), ())
949 toprocess = set(mark)
949 toprocess = set(mark)
950 while toprocess:
950 while toprocess:
951 prec = toprocess.pop()[0]
951 prec = toprocess.pop()[0]
952 if prec not in newermap:
952 if prec not in newermap:
953 successorssets(repo, prec, newermap)
953 successorssets(repo, prec, newermap)
954 newer = [n for n in newermap[prec] if n]
954 newer = [n for n in newermap[prec] if n]
955 if len(newer) > 1:
955 if len(newer) > 1:
956 divergent.add(ctx.rev())
956 divergent.add(ctx.rev())
957 break
957 break
958 toprocess.update(obsstore.precursors.get(prec, ()))
958 toprocess.update(obsstore.precursors.get(prec, ()))
959 return divergent
959 return divergent
960
960
961
961
962 def createmarkers(repo, relations, flag=0, date=None, metadata=None):
962 def createmarkers(repo, relations, flag=0, date=None, metadata=None):
963 """Add obsolete markers between changesets in a repo
963 """Add obsolete markers between changesets in a repo
964
964
965 <relations> must be an iterable of (<old>, (<new>, ...)[,{metadata}])
965 <relations> must be an iterable of (<old>, (<new>, ...)[,{metadata}])
966 tuple. `old` and `news` are changectx. metadata is an optional dictionary
966 tuple. `old` and `news` are changectx. metadata is an optional dictionary
967 containing metadata for this marker only. It is merged with the global
967 containing metadata for this marker only. It is merged with the global
968 metadata specified through the `metadata` argument of this function,
968 metadata specified through the `metadata` argument of this function,
969
969
970 Trying to obsolete a public changeset will raise an exception.
970 Trying to obsolete a public changeset will raise an exception.
971
971
972 Current user and date are used except if specified otherwise in the
972 Current user and date are used except if specified otherwise in the
973 metadata attribute.
973 metadata attribute.
974
974
975 This function operates within a transaction of its own, but does
975 This function operates within a transaction of its own, but does
976 not take any lock on the repo.
976 not take any lock on the repo.
977 """
977 """
978 # prepare metadata
978 # prepare metadata
979 if metadata is None:
979 if metadata is None:
980 metadata = {}
980 metadata = {}
981 if 'user' not in metadata:
981 if 'user' not in metadata:
982 metadata['user'] = repo.ui.username()
982 metadata['user'] = repo.ui.username()
983 tr = repo.transaction('add-obsolescence-marker')
983 tr = repo.transaction('add-obsolescence-marker')
984 try:
984 try:
985 for rel in relations:
985 for rel in relations:
986 prec = rel[0]
986 prec = rel[0]
987 sucs = rel[1]
987 sucs = rel[1]
988 localmetadata = metadata.copy()
988 localmetadata = metadata.copy()
989 if 2 < len(rel):
989 if 2 < len(rel):
990 localmetadata.update(rel[2])
990 localmetadata.update(rel[2])
991
991
992 if not prec.mutable():
992 if not prec.mutable():
993 raise util.Abort("cannot obsolete immutable changeset: %s"
993 raise util.Abort("cannot obsolete immutable changeset: %s"
994 % prec)
994 % prec)
995 nprec = prec.node()
995 nprec = prec.node()
996 nsucs = tuple(s.node() for s in sucs)
996 nsucs = tuple(s.node() for s in sucs)
997 npare = None
997 npare = None
998 if not nsucs:
998 if not nsucs:
999 npare = tuple(p.node() for p in prec.parents())
999 npare = tuple(p.node() for p in prec.parents())
1000 if nprec in nsucs:
1000 if nprec in nsucs:
1001 raise util.Abort("changeset %s cannot obsolete itself" % prec)
1001 raise util.Abort("changeset %s cannot obsolete itself" % prec)
1002 repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
1002 repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
1003 date=date, metadata=localmetadata)
1003 date=date, metadata=localmetadata)
1004 repo.filteredrevcache.clear()
1004 repo.filteredrevcache.clear()
1005 tr.close()
1005 tr.close()
1006 finally:
1006 finally:
1007 tr.release()
1007 tr.release()
General Comments 0
You need to be logged in to leave comments. Login now