##// END OF EJS Templates
obsutil: move 'successorssets' to the new modules...
obsutil: move 'successorssets' to the new modules We have a new 'obsutil' module now. We move this high level utility there to bring 'obsolete.py' back to a more reasonable size.

File last commit:

r33143:4f49810a default
r33143:4f49810a default
Show More
obsolete.py
1267 lines | 42.2 KiB | text/x-python | PythonLexer
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 # obsolete.py - obsolete markers handling
#
# Copyright 2012 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
# Logilab SA <contact@logilab.fr>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 """Obsolete marker handling
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
An obsolete marker maps an old changeset to a list of new
changesets. If the list of new changesets is empty, the old changeset
is said to be "killed". Otherwise, the old changeset is being
"replaced" by the new changesets.
Obsolete markers can be used to record and distribute changeset graph
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 transformations performed by history rewrite operations, and help
building new tools to reconcile conflicting rewrite actions. To
facilitate conflict resolution, markers include various annotations
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 besides old and news changeset identifiers, such as creation date or
author name.
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 The old obsoleted changeset is called a "precursor" and possible
replacements are called "successors". Markers that used changeset X as
a precursor are called "successor markers of X" because they hold
information about the successors of X. Markers that use changeset Y as
a successors are call "precursor markers of Y" because they hold
information about the precursors of Y.
Pierre-Yves David
obsolete: flip `obstore.successors` and `obsolete.precursors`...
r17776
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775 Examples:
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 - When changeset A is replaced by changeset A', one marker is stored:
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775
Martin Geisler
obsolete: fix one-element tuple in module docstring
r21166 (A, (A',))
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 - When changesets A and B are folded into a new changeset C, two markers are
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775 stored:
(A, (C,)) and (B, (C,))
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 - When changeset A is simply "pruned" from the graph, a marker is created:
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775
(A, ())
liscju
obsolete: fix minor module documentation issues
r29894 - When changeset A is split into B and C, a single marker is used:
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775
liscju
obsolete: fix minor module documentation issues
r29894 (A, (B, C))
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164 We use a single marker to distinguish the "split" case from the "divergence"
case. If two independent operations rewrite the same changeset A in to A' and
A'', we have an error case: divergent rewriting. We can detect it because
Pierre-Yves David
obsolete: add example of marker usage in the documentation...
r17775 two markers will be created independently:
(A, (B,)) and (A, (C,))
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Format
------
Markers are stored in an append-only file stored in
'.hg/store/obsstore'.
The file starts with a version header:
- 1 unsigned byte: version number, starting at zero.
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 The header is followed by the markers. Marker format depend of the version. See
comment associated with each format for details.
Martin Geisler
obsolete: fix language and grammar in module docstring
r21164
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 """
Gregory Szorc
obsolete: use absolute_import
r27332 from __future__ import absolute_import
import errno
import struct
from .i18n import _
from . import (
error,
node,
obsutil: move 'successorssets' to the new modules...
r33143 obsutil,
Gregory Szorc
obsolete: use absolute_import
r27332 phases,
Yuya Nishihara
parsers: switch to policy importer...
r32372 policy,
Gregory Szorc
obsolete: use absolute_import
r27332 util,
)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Yuya Nishihara
parsers: switch to policy importer...
r32372 parsers = policy.importmod(r'parsers')
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 _pack = struct.pack
_unpack = struct.unpack
Pierre-Yves David
obsstore: prefetch struct.calcsize...
r23498 _calcsize = struct.calcsize
Martin von Zweigbergk
obsolete: populate successors, precursors, children lazily...
r24046 propertycache = util.propertycache
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Mads Kiilerich
fix trivial spelling errors
r17424 # the obsolete feature is not mature enough to be enabled by default.
Pierre-Yves David
obsolete: introduce an `_enabled` switch to disable the feature by default...
r17296 # you have to rely on third party extension extension to enable this.
_enabled = False
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Durham Goode
obsolete: add createmarkers option...
r22951 # Options for obsolescence
createmarkersopt = 'createmarkers'
Durham Goode
obsolete: add allowunstable option...
r22952 allowunstableopt = 'allowunstable'
Durham Goode
obsolete: add exchange option...
r22953 exchangeopt = 'exchange'
Durham Goode
obsolete: add createmarkers option...
r22951
obsolete: move the 'isenabled' function at the top of the file...
r32333 def isenabled(repo, option):
"""Returns True if the given repository has the given obsolete option
enabled.
"""
result = set(repo.ui.configlist('experimental', 'evolution'))
if 'all' in result:
return True
# For migration purposes, temporarily return true if the config hasn't been
# set but _enabled is true.
if len(result) == 0 and _enabled:
return True
# createmarkers must be enabled if other options are enabled
if ((allowunstableopt in result or exchangeopt in result) and
not createmarkersopt in result):
raise error.Abort(_("'createmarkers' obsolete option must be enabled "
"if other obsolete options are enabled"))
return option in result
Pierre-Yves David
obsolete: add a flag that allows fixing "bumped" changeset...
r17831 ### obsolescence marker flag
## bumpedfix flag
#
# When a changeset A' succeed to a changeset A which became public, we call A'
# "bumped" because it's a successors of a public changesets
#
# o A' (bumped)
# |`:
# | o A
# |/
# o Z
#
# The way to solve this situation is to create a new changeset Ad as children
# of A. This changeset have the same content than A'. So the diff from A to A'
# is the same than the diff from A to Ad. Ad is marked as a successors of A'
#
# o Ad
# |`:
# | x A'
# |'|
# o | A
# |/
# o Z
#
# But by transitivity Ad is also a successors of A. To avoid having Ad marked
# as bumped too, we add the `bumpedfix` flag to the marker. <A', (Ad,)>.
Mads Kiilerich
spelling: fix some minor issues found by spell checker
r18644 # This flag mean that the successors express the changes between the public and
# bumped version and fix the situation, breaking the transitivity of
# "bumped" here.
Pierre-Yves David
obsolete: add a flag that allows fixing "bumped" changeset...
r17831 bumpedfix = 1
Pierre-Yves David
obsstore: add a flag for sha256 hashes...
r22850 usingsha256 = 2
Pierre-Yves David
obsolete: add a flag that allows fixing "bumped" changeset...
r17831
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 ## Parsing and writing of version "0"
#
# The header is followed by the markers. Each marker is made of:
#
Pierre-Yves David
obsolete: use uint## in the format documention...
r22849 # - 1 uint8 : number of new changesets "N", can be zero.
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 #
Pierre-Yves David
obsolete: use uint## in the format documention...
r22849 # - 1 uint32: metadata size "M" in bytes.
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 #
# - 1 byte: a bit field. It is reserved for flags used in common
# obsolete marker operations, to avoid repeated decoding of metadata
# entries.
#
# - 20 bytes: obsoleted changeset identifier.
#
# - N*20 bytes: new changesets identifiers.
#
# - M bytes: metadata as a sequence of nul-terminated strings. Each
# string contains a key and a value, separated by a colon ':', without
# additional encoding. Keys cannot contain '\0' or ':' and values
# cannot contain '\0'.
_fm0version = 0
_fm0fixed = '>BIB20s'
_fm0node = '20s'
Pierre-Yves David
obsstore: prefetch struct.calcsize...
r23498 _fm0fsize = _calcsize(_fm0fixed)
_fm0fnodesize = _calcsize(_fm0node)
Pierre-Yves David
obsolete: move _encodemarkers next to _readmarkers
r22334
Augie Fackler
obsolete: make optional offset parameter to fm*readmarkers required...
r24014 def _fm0readmarkers(data, off):
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 # Loop on markers
l = len(data)
Pierre-Yves David
obsolete: rename all _fm to _fm0...
r22327 while off + _fm0fsize <= l:
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 # read fixed part
Pierre-Yves David
obsolete: rename all _fm to _fm0...
r22327 cur = data[off:off + _fm0fsize]
off += _fm0fsize
Pierre-Yves David
obsolete: replace "nb" notation with "num" (for "number")...
r22685 numsuc, mdsize, flags, pre = _unpack(_fm0fixed, cur)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 # read replacement
sucs = ()
Pierre-Yves David
obsolete: replace "nb" notation with "num" (for "number")...
r22685 if numsuc:
s = (_fm0fnodesize * numsuc)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 cur = data[off:off + s]
Pierre-Yves David
obsolete: replace "nb" notation with "num" (for "number")...
r22685 sucs = _unpack(_fm0node * numsuc, cur)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 off += s
# read metadata
# (metadata will be decoded on demand)
metadata = data[off:off + mdsize]
if len(metadata) != mdsize:
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort(_('parsing obsolete marker: metadata is too '
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 'short, %d bytes expected, got %d')
Pierre-Yves David
obsolete: fix decoding error message arguments
r17253 % (mdsize, len(metadata)))
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 off += mdsize
Pierre-Yves David
obsolete: _rename decodemeta to _fm0decodemeta...
r22847 metadata = _fm0decodemeta(metadata)
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222 try:
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845 when, offset = metadata.pop('date', '0 0').split(' ')
Gregory Szorc
obsolete: avoid slow, generic date parsing...
r22309 date = float(when), int(offset)
except ValueError:
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222 date = (0., 0)
Pierre-Yves David
obsstore: also store the 'parents' field on disk...
r22258 parents = None
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845 if 'p2' in metadata:
parents = (metadata.pop('p1', None), metadata.pop('p2', None))
elif 'p1' in metadata:
parents = (metadata.pop('p1', None),)
elif 'p0' in metadata:
Pierre-Yves David
obsstore: also store the 'parents' field on disk...
r22258 parents = ()
if parents is not None:
try:
parents = tuple(node.bin(p) for p in parents)
# if parent content is not a nodeid, drop the data
for p in parents:
if len(p) != 20:
parents = None
break
except TypeError:
# if content cannot be translated to nodeid drop the data.
parents = None
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845 metadata = tuple(sorted(metadata.iteritems()))
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222
Pierre-Yves David
obsstore: also store the 'parents' field on disk...
r22258 yield (pre, sucs, flags, metadata, date, parents)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Pierre-Yves David
obsolete: move _fm0encodeonemarker next to _fm0readmarkers
r22330 def _fm0encodeonemarker(marker):
pre, sucs, flags, metadata, date, parents = marker
Pierre-Yves David
obsstore: add a flag for sha256 hashes...
r22850 if flags & usingsha256:
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort(_('cannot handle sha256 with old obsstore format'))
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845 metadata = dict(metadata)
Pierre-Yves David
obsstore: record data as floating point in fm0 format...
r23002 time, tz = date
metadata['date'] = '%r %i' % (time, tz)
Pierre-Yves David
obsolete: move _fm0encodeonemarker next to _fm0readmarkers
r22330 if parents is not None:
if not parents:
# mark that we explicitly recorded no parents
metadata['p0'] = ''
Gregory Szorc
obsolete: use 2 argument form of enumerate()...
r32278 for i, p in enumerate(parents, 1):
metadata['p%i' % i] = node.hex(p)
Pierre-Yves David
obsolete: _rename encodemeta to _fm0encodemeta...
r22846 metadata = _fm0encodemeta(metadata)
Pierre-Yves David
obsolete: replace "nb" notation with "num" (for "number")...
r22685 numsuc = len(sucs)
format = _fm0fixed + (_fm0node * numsuc)
data = [numsuc, len(metadata), flags, pre]
Pierre-Yves David
obsolete: move _fm0encodeonemarker next to _fm0readmarkers
r22330 data.extend(sucs)
return _pack(format, *data) + metadata
Pierre-Yves David
obsolete: gather _fm0 meta encoding with other _fm0 code
r22848 def _fm0encodemeta(meta):
"""Return encoded metadata string to string mapping.
Assume no ':' in key and no '\0' in both key and value."""
for key, value in meta.iteritems():
if ':' in key or '\0' in key:
raise ValueError("':' and '\0' are forbidden in metadata key'")
if '\0' in value:
raise ValueError("':' is forbidden in metadata value'")
return '\0'.join(['%s:%s' % (k, meta[k]) for k in sorted(meta)])
def _fm0decodemeta(data):
"""Return string to string dictionary from encoded version."""
d = {}
for l in data.split('\0'):
if l:
key, value = l.split(':')
d[key] = value
return d
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 ## Parsing and writing of version "1"
#
# The header is followed by the markers. Each marker is made of:
#
# - uint32: total size of the marker (including this field)
#
# - float64: date in seconds since epoch
#
# - int16: timezone offset in minutes
#
# - uint16: a bit field. It is reserved for flags used in common
# obsolete marker operations, to avoid repeated decoding of metadata
# entries.
#
# - uint8: number of successors "N", can be zero.
#
# - uint8: number of parents "P", can be zero.
#
# 0: parents data stored but no parent,
# 1: one parent stored,
# 2: two parents stored,
# 3: no parent data stored
#
# - uint8: number of metadata entries M
#
# - 20 or 32 bytes: precursor changeset identifier.
#
# - N*(20 or 32) bytes: successors changesets identifiers.
#
# - P*(20 or 32) bytes: parents of the precursors changesets.
#
# - M*(uint8, uint8): size of all metadata entries (key and value)
#
# - remaining bytes: the metadata, each (key, value) pair after the other.
_fm1version = 1
_fm1fixed = '>IdhHBBB20s'
_fm1nodesha1 = '20s'
_fm1nodesha256 = '32s'
Pierre-Yves David
obsstore: cache size computation for fm1 node...
r23499 _fm1nodesha1size = _calcsize(_fm1nodesha1)
_fm1nodesha256size = _calcsize(_fm1nodesha256)
Pierre-Yves David
obsstore: prefetch struct.calcsize...
r23498 _fm1fsize = _calcsize(_fm1fixed)
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 _fm1parentnone = 3
_fm1parentshift = 14
_fm1parentmask = (_fm1parentnone << _fm1parentshift)
_fm1metapair = 'BB'
Pierre-Yves David
obsstore: prefetch struct.calcsize...
r23498 _fm1metapairsize = _calcsize('BB')
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851
Martin von Zweigbergk
_fm1readmarkers: generate list in C...
r24019 def _fm1purereadmarkers(data, off):
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 # make some global constants local for performance
noneflag = _fm1parentnone
sha2flag = usingsha256
sha1size = _fm1nodesha1size
sha2size = _fm1nodesha256size
sha1fmt = _fm1nodesha1
sha2fmt = _fm1nodesha256
metasize = _fm1metapairsize
metafmt = _fm1metapair
fsize = _fm1fsize
unpack = _unpack
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 # Loop on markers
Matt Mackall
readmarkers: hoist subtraction out of loop comparison
r23799 stop = len(data) - _fm1fsize
Pierre-Yves David
util: drop the 'unpacker' helper...
r25211 ufixed = struct.Struct(_fm1fixed).unpack
Augie Fackler
obsolete: use parsers.fm1readmarker if it exists for a ~38% perf win...
r24018
Matt Mackall
readmarkers: hoist subtraction out of loop comparison
r23799 while off <= stop:
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 # read fixed part
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 o1 = off + fsize
Matt Mackall
readmarkers: drop a temporary...
r23800 t, secs, tz, flags, numsuc, numpar, nummeta, prec = ufixed(data[off:o1])
Matt Mackall
readmarkers: add some whitespace
r23792
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 if flags & sha2flag:
Matt Mackall
readmarkers: add a SHA256 fixme note
r23805 # FIXME: prec was read as a SHA1, needs to be amended
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 # read 0 or more successors
Matt Mackall
readmarkers: fast-path single successors and parents...
r23804 if numsuc == 1:
o2 = o1 + sha2size
sucs = (data[o1:o2],)
else:
o2 = o1 + sha2size * numsuc
sucs = unpack(sha2fmt * numsuc, data[o1:o2])
Matt Mackall
readmarkers: add some whitespace
r23792
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 # read parents
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 if numpar == noneflag:
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 o3 = o2
parents = None
Matt Mackall
readmarkers: fast-path single successors and parents...
r23804 elif numpar == 1:
o3 = o2 + sha2size
parents = (data[o2:o3],)
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 else:
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 o3 = o2 + sha2size * numpar
parents = unpack(sha2fmt * numpar, data[o2:o3])
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 else:
# read 0 or more successors
Matt Mackall
readmarkers: fast-path single successors and parents...
r23804 if numsuc == 1:
o2 = o1 + sha1size
sucs = (data[o1:o2],)
else:
o2 = o1 + sha1size * numsuc
sucs = unpack(sha1fmt * numsuc, data[o1:o2])
Matt Mackall
readmarkers: add some whitespace
r23792
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 # read parents
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 if numpar == noneflag:
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 o3 = o2
parents = None
Matt Mackall
readmarkers: fast-path single successors and parents...
r23804 elif numpar == 1:
o3 = o2 + sha1size
parents = (data[o2:o3],)
Matt Mackall
readmarkers: read node reading into node length conditional...
r23801 else:
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 o3 = o2 + sha1size * numpar
parents = unpack(sha1fmt * numpar, data[o2:o3])
Matt Mackall
readmarkers: add some whitespace
r23792
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 # read metadata
Matt Mackall
readmarkers: promote global constants to locals for performance
r23803 off = o3 + metasize * nummeta
metapairsize = unpack('>' + (metafmt * nummeta), data[o3:off])
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 metadata = []
for idx in xrange(0, len(metapairsize), 2):
Matt Mackall
readmarkers: streamline offset tracking...
r23798 o1 = off + metapairsize[idx]
o2 = o1 + metapairsize[idx + 1]
metadata.append((data[off:o1], data[o1:o2]))
off = o2
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851
Matt Mackall
readmarkers: drop a temporary...
r23800 yield (prec, sucs, flags, tuple(metadata), (secs, tz * 60), parents)
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851
def _fm1encodeonemarker(marker):
pre, sucs, flags, metadata, date, parents = marker
# determine node size
_fm1node = _fm1nodesha1
if flags & usingsha256:
_fm1node = _fm1nodesha256
numsuc = len(sucs)
numextranodes = numsuc
if parents is None:
numpar = _fm1parentnone
else:
numpar = len(parents)
numextranodes += numpar
formatnodes = _fm1node * numextranodes
formatmeta = _fm1metapair * len(metadata)
format = _fm1fixed + formatnodes + formatmeta
# tz is stored in minutes so we divide by 60
tz = date[1]//60
data = [None, date[0], tz, flags, numsuc, numpar, len(metadata), pre]
data.extend(sucs)
if parents is not None:
data.extend(parents)
Pierre-Yves David
obsstore: prefetch struct.calcsize...
r23498 totalsize = _calcsize(format)
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 for key, value in metadata:
lk = len(key)
lv = len(value)
data.append(lk)
data.append(lv)
totalsize += lk + lv
data[0] = totalsize
data = [_pack(format, *data)]
for key, value in metadata:
data.append(key)
data.append(value)
return ''.join(data)
Pierre-Yves David
obsolete: gather _fm0 meta encoding with other _fm0 code
r22848
Martin von Zweigbergk
_fm1readmarkers: generate list in C...
r24019 def _fm1readmarkers(data, off):
native = getattr(parsers, 'fm1readmarkers', None)
if not native:
return _fm1purereadmarkers(data, off)
stop = len(data) - _fm1fsize
return native(data, off, stop)
Pierre-Yves David
obsolete: support for any known obsstore format when reading or writing...
r22331 # mapping to read/write various marker formats
# <version> -> (decoder, encoder)
Pierre-Yves David
obsolete: introduce a new binary encoding for obsmarkers (version 1)...
r22851 formats = {_fm0version: (_fm0readmarkers, _fm0encodeonemarker),
_fm1version: (_fm1readmarkers, _fm1encodeonemarker)}
Pierre-Yves David
obsolete: support for any known obsstore format when reading or writing...
r22331
Jun Wu
obsstore: move marker version reading to a separate function...
r32689 def _readmarkerversion(data):
return _unpack('>B', data[0:1])[0]
Pierre-Yves David
obsstore: disable garbage collection during initialization (issue4456)...
r23497 @util.nogc
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 def _readmarkers(data):
"""Read and enumerate markers from raw data"""
Jun Wu
obsstore: move marker version reading to a separate function...
r32689 diskversion = _readmarkerversion(data)
off = 1
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 if diskversion not in formats:
obsolete: raise richer exception on unknown version...
r32591 msg = _('parsing obsolete marker: unknown version %r') % diskversion
raise error.UnknownVersion(msg, version=diskversion)
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 return diskversion, formats[diskversion][0](data, off)
Jun Wu
obsstore: move header encoding to a separate function...
r32692 def encodeheader(version=_fm0version):
return _pack('>B', version)
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 def encodemarkers(markers, addheader=False, version=_fm0version):
# Kept separate from flushmarkers(), it will be reused for
# markers exchange.
encodeone = formats[version][1]
if addheader:
Jun Wu
obsstore: move header encoding to a separate function...
r32692 yield encodeheader(version)
Pierre-Yves David
obsolete: gather all contents related to format version 0 in a single place...
r22612 for marker in markers:
yield encodeone(marker)
Pierre-Yves.David@ens-lyon.org
obsolete: helper class to access obsolete marker data
r17072 class marker(object):
"""Wrap obsolete marker raw data"""
def __init__(self, repo, data):
# the repo argument will be used to create changectx in later version
self._repo = repo
self._data = data
self._decodedmeta = None
Augie Fackler
obsolete: add __eq__ and __hash__ to marker to make set() deduplication work
r20031 def __hash__(self):
return hash(self._data)
def __eq__(self, other):
if type(other) != type(self):
return False
return self._data == other._data
Pierre-Yves.David@ens-lyon.org
obsolete: helper class to access obsolete marker data
r17072 def precnode(self):
"""Precursor changeset node identifier"""
return self._data[0]
def succnodes(self):
"""List of successor changesets node identifiers"""
return self._data[1]
Pierre-Yves David
obsmarkers: add a `parentnodes` method to retrieve parent information
r22259 def parentnodes(self):
"""Parents of the precursors (None if not recorded)"""
return self._data[5]
Pierre-Yves.David@ens-lyon.org
obsolete: helper class to access obsolete marker data
r17072 def metadata(self):
"""Decoded metadata dictionary"""
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845 return dict(self._data[3])
Pierre-Yves.David@ens-lyon.org
obsolete: helper class to access obsolete marker data
r17072
def date(self):
"""Creation date as (unixtime, offset)"""
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222 return self._data[4]
Pierre-Yves.David@ens-lyon.org
obsolete: helper class to access obsolete marker data
r17072
Pierre-Yves David
obsmarker: add a `flags` method...
r22215 def flags(self):
"""The flags field of the marker"""
return self._data[2]
Martin von Zweigbergk
obsolete: extract helpers from _load()...
r24044 @util.nogc
def _addsuccessors(successors, markers):
for mark in markers:
successors.setdefault(mark[0], set()).add(mark)
@util.nogc
def _addprecursors(precursors, markers):
for mark in markers:
for suc in mark[1]:
precursors.setdefault(suc, set()).add(mark)
@util.nogc
def _addchildren(children, markers):
for mark in markers:
parents = mark[5]
if parents is not None:
for p in parents:
children.setdefault(p, set()).add(mark)
Martin von Zweigbergk
obsolete: pass only new markers to _checkinvalidmarkers()...
r24045 def _checkinvalidmarkers(markers):
Pierre-Yves David
obsstore: make the invalid markers check wrap-able...
r23973 """search for marker with invalid data and raise error if needed
Exist as a separated function to allow the evolve extension for a more
subtle handling.
"""
Martin von Zweigbergk
obsolete: pass only new markers to _checkinvalidmarkers()...
r24045 for mark in markers:
if node.nullid in mark[1]:
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort(_('bad obsolescence marker detected: '
Martin von Zweigbergk
obsolete: pass only new markers to _checkinvalidmarkers()...
r24045 'invalid successors nullid'))
Pierre-Yves David
obsstore: make the invalid markers check wrap-able...
r23973
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 class obsstore(object):
"""Store obsolete markers
Markers can be accessed with two mappings:
Pierre-Yves David
obsolete: flip `obstore.successors` and `obsolete.precursors`...
r17776 - precursors[x] -> set(markers on precursors edges of x)
- successors[x] -> set(markers on successors edges of x)
Pierre-Yves David
obsstore: keep track of children information...
r22270 - children[x] -> set(markers on precursors edges of children(x)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070 """
Pierre-Yves David
obsstore: add a `parents` field...
r22254 fields = ('prec', 'succs', 'flag', 'meta', 'date', 'parents')
# prec: nodeid, precursor changesets
# succs: tuple of nodeid, successor changesets (0-N length)
# flag: integer, flag field carrying modifier for the markers (see doc)
# meta: binary blob, encoded metadata dictionary
# date: (float, int) tuple, date of marker creation
# parents: (tuple of nodeid) or None, parents of precursors
# None is used when no data has been recorded
Pierre-Yves David
obsstore: add fields attribute to track each field in a marker...
r22221
Siddharth Agarwal
obsolete: replace references to 'sopener' with 'svfs'
r25669 def __init__(self, svfs, defaultformat=_fm1version, readonly=False):
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 # caches for various obsolescence related cache
self.caches = {}
Siddharth Agarwal
obsolete: replace references to 'sopener' with 'svfs'
r25669 self.svfs = svfs
Jun Wu
obsstore: move _version to a propertycache...
r32691 self._defaultformat = defaultformat
Durham Goode
obsolete: add readonly flag to obstore constructor...
r22950 self._readonly = readonly
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Pierre-Yves.David@ens-lyon.org
obsolete: add easy way to iterate over obsolete marker object
r17073 def __iter__(self):
return iter(self._all)
Pierre-Yves David
obsstore: add a __len__ method...
r20585 def __len__(self):
return len(self._all)
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 def __nonzero__(self):
Yuya Nishihara
obsstore: fast path to check if obsstore is empty
r26310 if not self._cached('_all'):
try:
return self.svfs.stat('obsstore').st_size > 1
except OSError as inst:
if inst.errno != errno.ENOENT:
raise
# just build an empty _all list if no obsstore exists, which
# avoids further stat() syscalls
pass
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 return bool(self._all)
Gregory Szorc
py3: add __bool__ to every class defining __nonzero__...
r31476 __bool__ = __nonzero__
Pierre-Yves David
obsstore: make the readonly attribute accessible...
r26684 @property
def readonly(self):
"""True if marker creation is disabled
Remove me in the future when obsolete marker is always on."""
return self._readonly
Pierre-Yves David
obsstore: add a `parents` argument to obsstore.create...
r22255 def create(self, transaction, prec, succs=(), flag=0, parents=None,
Boris Feld
devel: use default-date config field when creating obsmarkers...
r32411 date=None, metadata=None, ui=None):
Pierre-Yves.David@ens-lyon.org
command: creation of obsolete marker...
r17071 """obsolete: add a new obsolete marker
* ensuring it is hashable
* check mandatory metadata
* encode metadata
Pierre-Yves David
obsstore: update create docstring to point to the coder friendly function...
r20516
If you are a human writing code creating marker you want to use the
`createmarkers` function in this module instead.
Pierre-Yves David
obsstore: `create` method return True if a marker is actually added...
r20584
return True if a new marker have been added, False if the markers
already existed (no op).
Pierre-Yves.David@ens-lyon.org
command: creation of obsolete marker...
r17071 """
if metadata is None:
metadata = {}
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222 if date is None:
if 'date' in metadata:
# as a courtesy for out-of-tree extensions
date = util.parsedate(metadata.pop('date'))
Boris Feld
devel: use default-date config field when creating obsmarkers...
r32411 elif ui is not None:
date = ui.configdate('devel', 'default-date')
if date is None:
date = util.makedate()
Pierre-Yves David
obsmarker: add `date` as an explicit field...
r22222 else:
Pierre-Yves David
obsstore: add an explicit `date` argument to obsstore.create...
r22217 date = util.makedate()
Pierre-Yves.David@ens-lyon.org
command: creation of obsolete marker...
r17071 if len(prec) != 20:
raise ValueError(prec)
for succ in succs:
if len(succ) != 20:
Pierre-Yves David
obsolete: fix error message at marker creation...
r17117 raise ValueError(succ)
Pierre-Yves David
obsstore.create: add a simple safeguard against cyclic markers...
r22177 if prec in succs:
raise ValueError(_('in-marker cycle with %s') % node.hex(prec))
Pierre-Yves David
obsolete: store metadata as a tuple of (key, value) pairs (API)...
r22845
metadata = tuple(sorted(metadata.iteritems()))
marker = (str(prec), tuple(succs), int(flag), metadata, date, parents)
Pierre-Yves David
obsstore: `create` method return True if a marker is actually added...
r20584 return bool(self.add(transaction, [marker]))
Pierre-Yves.David@ens-lyon.org
obsolete: obsstore.add now takes a list of markers....
r17220
def add(self, transaction, markers):
"""Add new markers to the store
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Pierre-Yves.David@ens-lyon.org
obsolete: obsstore.add now takes a list of markers....
r17220 Take care of filtering duplicate.
Return the number of new marker."""
Durham Goode
obsolete: add readonly flag to obstore constructor...
r22950 if self._readonly:
liscju
i18n: translate abort messages...
r29389 raise error.Abort(_('creating obsolete markers is not enabled on '
'this repo'))
Jun Wu
obsstore: do not load all markers to detect duplication...
r32774 known = set()
getsuccessors = self.successors.get
Pierre-Yves David
obsolete: do not accept duplicated marker during exchange...
r20030 new = []
for m in markers:
Jun Wu
obsstore: do not load all markers to detect duplication...
r32774 if m not in getsuccessors(m[0], ()) and m not in known:
Pierre-Yves David
obsolete: do not accept duplicated marker during exchange...
r20030 known.add(m)
new.append(m)
Pierre-Yves.David@ens-lyon.org
obsolete: obsstore.add now takes a list of markers....
r17220 if new:
Siddharth Agarwal
obsolete: replace references to 'sopener' with 'svfs'
r25669 f = self.svfs('obsstore', 'ab')
Pierre-Yves David
obsolete: move obsolete markers read/write logic to obsstore object...
r17124 try:
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126 offset = f.tell()
transaction.add('obsstore', offset)
Pierre-Yves.David@ens-lyon.org
obsolete: refactor writemarkers to only encode them...
r17219 # offset == 0: new file - add the version header
Pierre-Yves David
obsolete: make encodemarkers a public function...
r22335 for bytes in encodemarkers(new, offset == 0, self._version):
Pierre-Yves.David@ens-lyon.org
obsolete: refactor writemarkers to only encode them...
r17219 f.write(bytes)
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126 finally:
# XXX: f.close() == filecache invalidation == obsstore rebuilt.
# call 'filecacheentry.refresh()' here
Pierre-Yves David
obsolete: move obsolete markers read/write logic to obsstore object...
r17124 f.close()
Martin von Zweigbergk
obsolete: populate successors, precursors, children lazily...
r24046 self._addmarkers(new)
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 # new marker *may* have changed several set. invalidate the cache.
self.caches.clear()
Pierre-Yves David
obsmarker: record the number of new markers in the transaction...
r22339 # records the number of new markers for the transaction hooks
previous = int(transaction.hookargs.get('new_obsmarkers', '0'))
transaction.hookargs['new_obsmarkers'] = str(previous + len(new))
Pierre-Yves.David@ens-lyon.org
obsolete: obsstore.add now takes a list of markers....
r17220 return len(new)
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126
timeless@mozdev.org
spelling: transaction
r17524 def mergemarkers(self, transaction, data):
Pierre-Yves David
obsstore: have the `mergemarkers` method return the number of new markers...
r22325 """merge a binary stream of markers inside the obsstore
Returns the number of new markers added."""
Pierre-Yves David
obsolete: have _readmarkers return the format version...
r22332 version, markers = _readmarkers(data)
Pierre-Yves David
obsstore: have the `mergemarkers` method return the number of new markers...
r22325 return self.add(transaction, markers)
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Martin von Zweigbergk
obsolete: populate successors, precursors, children lazily...
r24046 @propertycache
Jun Wu
obsstore: separate marker parsing from obsstore reading...
r32690 def _data(self):
return self.svfs.tryread('obsstore')
@propertycache
Jun Wu
obsstore: move _version to a propertycache...
r32691 def _version(self):
if len(self._data) >= 1:
return _readmarkerversion(self._data)
else:
return self._defaultformat
@propertycache
Yuya Nishihara
obsstore: delay loading markers from obsstore file...
r26309 def _all(self):
Jun Wu
obsstore: separate marker parsing from obsstore reading...
r32690 data = self._data
Yuya Nishihara
obsstore: delay loading markers from obsstore file...
r26309 if not data:
return []
self._version, markers = _readmarkers(data)
markers = list(markers)
_checkinvalidmarkers(markers)
return markers
@propertycache
Martin von Zweigbergk
obsolete: populate successors, precursors, children lazily...
r24046 def successors(self):
successors = {}
_addsuccessors(successors, self._all)
return successors
@propertycache
def precursors(self):
precursors = {}
_addprecursors(precursors, self._all)
return precursors
@propertycache
def children(self):
children = {}
_addchildren(children, self._all)
return children
def _cached(self, attr):
return attr in self.__dict__
def _addmarkers(self, markers):
Martin von Zweigbergk
obsolete: extract helpers from _load()...
r24044 markers = list(markers) # to allow repeated iteration
self._all.extend(markers)
Martin von Zweigbergk
obsolete: populate successors, precursors, children lazily...
r24046 if self._cached('successors'):
_addsuccessors(self.successors, markers)
if self._cached('precursors'):
_addprecursors(self.precursors, markers)
if self._cached('children'):
_addchildren(self.children, markers)
Martin von Zweigbergk
obsolete: pass only new markers to _checkinvalidmarkers()...
r24045 _checkinvalidmarkers(markers)
Pierre-Yves David
obsstore: make the invalid markers check wrap-able...
r23973
Pierre-Yves David
obsstore: add relevantmarkers method...
r22271 def relevantmarkers(self, nodes):
"""return a set of all obsolescence markers relevant to a set of nodes.
"relevant" to a set of nodes mean:
- marker that use this changeset as successor
- prune marker of direct children on this changeset
- recursive application of the two rules on precursors of these markers
It is a set so you cannot rely on order."""
pendingnodes = set(nodes)
seenmarkers = set()
seennodes = set(pendingnodes)
precursorsmarkers = self.precursors
obsolete: fix relevant-obsmarkers computation on pruned changeset...
r32488 succsmarkers = self.successors
Pierre-Yves David
obsstore: add relevantmarkers method...
r22271 children = self.children
while pendingnodes:
direct = set()
for current in pendingnodes:
direct.update(precursorsmarkers.get(current, ()))
pruned = [m for m in children.get(current, ()) if not m[1]]
direct.update(pruned)
obsolete: fix relevant-obsmarkers computation on pruned changeset...
r32488 pruned = [m for m in succsmarkers.get(current, ()) if not m[1]]
direct.update(pruned)
Pierre-Yves David
obsstore: add relevantmarkers method...
r22271 direct -= seenmarkers
pendingnodes = set([m[0] for m in direct])
seenmarkers |= direct
pendingnodes -= seennodes
seennodes |= pendingnodes
return seenmarkers
Pierre-Yves.David@ens-lyon.org
obsolete: introduction of obsolete markers...
r17070
Gregory Szorc
obsolete: move obsstore creation logic from localrepo...
r32729 def makestore(ui, repo):
"""Create an obsstore instance from a repo."""
# read default format for new obsstore.
# developer config: format.obsstore-version
defaultformat = ui.configint('format', 'obsstore-version', None)
# rely on obsstore class default when possible.
kwargs = {}
if defaultformat is not None:
kwargs['defaultformat'] = defaultformat
readonly = not isenabled(repo, createmarkersopt)
store = obsstore(repo.svfs, readonly=readonly, **kwargs)
if store and readonly:
ui.warn(_('obsolete feature not enabled but %i markers found!\n')
% len(list(store)))
return store
obsolete: add a function to compute "exclusive-markers" for a set of nodes...
r32626 def _filterprunes(markers):
"""return a set with no prune markers"""
return set(m for m in markers if m[1])
def exclusivemarkers(repo, nodes):
"""set of markers relevant to "nodes" but no other locally-known nodes
This function compute the set of markers "exclusive" to a locally-known
node. This means we walk the markers starting from <nodes> until we reach a
locally-known precursors outside of <nodes>. Element of <nodes> with
locally-known successors outside of <nodes> are ignored (since their
precursors markers are also relevant to these successors).
For example:
# (A0 rewritten as A1)
#
# A0 <-1- A1 # Marker "1" is exclusive to A1
or
# (A0 rewritten as AX; AX rewritten as A1; AX is unkown locally)
#
# <-1- A0 <-2- AX <-3- A1 # Marker "2,3" are exclusive to A1
or
# (A0 has unknown precursors, A0 rewritten as A1 and A2 (divergence))
#
# <-2- A1 # Marker "2" is exclusive to A0,A1
# /
# <-1- A0
# \
# <-3- A2 # Marker "3" is exclusive to A0,A2
#
# in addition:
#
# Markers "2,3" are exclusive to A1,A2
# Markers "1,2,3" are exclusive to A0,A1,A2
exclusive-markers: update the dedicated test with list of exclusive markers...
r32627 See test/test-obsolete-bundle-strip.t for more examples.
obsolete: add a function to compute "exclusive-markers" for a set of nodes...
r32626 An example usage is strip. When stripping a changeset, we also want to
strip the markers exclusive to this changeset. Otherwise we would have
"dangling"" obsolescence markers from its precursors: Obsolescence markers
marking a node as obsolete without any successors available locally.
As for relevant markers, the prune markers for children will be followed.
Of course, they will only be followed if the pruned children is
locally-known. Since the prune markers are relevant to the pruned node.
However, while prune markers are considered relevant to the parent of the
pruned changesets, prune markers for locally-known changeset (with no
successors) are considered exclusive to the pruned nodes. This allows
to strip the prune markers (with the rest of the exclusive chain) alongside
the pruned changesets.
"""
# running on a filtered repository would be dangerous as markers could be
# reported as exclusive when they are relevant for other filtered nodes.
unfi = repo.unfiltered()
# shortcut to various useful item
nm = unfi.changelog.nodemap
precursorsmarkers = unfi.obsstore.precursors
successormarkers = unfi.obsstore.successors
childrenmarkers = unfi.obsstore.children
# exclusive markers (return of the function)
exclmarkers = set()
# we need fast membership testing
nodes = set(nodes)
# looking for head in the obshistory
#
# XXX we are ignoring all issues in regard with cycle for now.
stack = [n for n in nodes if not _filterprunes(successormarkers.get(n, ()))]
stack.sort()
# nodes already stacked
seennodes = set(stack)
while stack:
current = stack.pop()
# fetch precursors markers
markers = list(precursorsmarkers.get(current, ()))
# extend the list with prune markers
for mark in successormarkers.get(current, ()):
if not mark[1]:
markers.append(mark)
# and markers from children (looking for prune)
for mark in childrenmarkers.get(current, ()):
if not mark[1]:
markers.append(mark)
# traverse the markers
for mark in markers:
if mark in exclmarkers:
# markers already selected
continue
# If the markers is about the current node, select it
#
# (this delay the addition of markers from children)
if mark[1] or mark[0] == current:
exclmarkers.add(mark)
# should we keep traversing through the precursors?
prec = mark[0]
# nodes in the stack or already processed
if prec in seennodes:
continue
# is this a locally known node ?
known = prec in nm
# if locally-known and not in the <nodes> set the traversal
# stop here.
if known and prec not in nodes:
continue
# do not keep going if there are unselected markers pointing to this
# nodes. If we end up traversing these unselected markers later the
# node will be taken care of at that point.
precmarkers = _filterprunes(successormarkers.get(prec))
if precmarkers.issubset(exclmarkers):
seennodes.add(prec)
stack.append(prec)
return exclmarkers
Pierre-Yves David
obsolete: add a `commonversion` function...
r22345 def commonversion(versions):
"""Return the newest version listed in both versions and our local formats.
Returns None if no common version exists.
"""
versions.sort(reverse=True)
# search for highest version known on both side
for v in versions:
if v in formats:
return v
return None
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295
# arbitrary picked to fit into 8K limit from HTTP server
# you have to take in account:
# - the version header
# - the base85 encoding
_maxpayload = 5300
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075
Pierre-Yves David
obsolete: extract encoding of marker for pushkey from the list key function...
r20599 def _pushkeyescape(markers):
"""encode markers into a dict suitable for pushkey exchange
Mads Kiilerich
spelling: fixes from spell checker
r21024 - binary data is base85 encoded
- split in chunks smaller than 5300 bytes"""
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295 keys = {}
parts = []
currentlen = _maxpayload * 2 # ensure we create a new part
Pierre-Yves David
obsolete: extract encoding of marker for pushkey from the list key function...
r20599 for marker in markers:
Pierre-Yves David
obsolete: rename _encodeonemarker to _fm0encodeonemarkers...
r22329 nextdata = _fm0encodeonemarker(marker)
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295 if (len(nextdata) + currentlen > _maxpayload):
currentpart = []
currentlen = 0
parts.append(currentpart)
currentpart.append(nextdata)
Pierre-Yves David
obsolete: properly increment currentlen when building pushkey payload...
r17304 currentlen += len(nextdata)
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295 for idx, part in enumerate(reversed(parts)):
Pierre-Yves David
obsolete: rename all _fm to _fm0...
r22327 data = ''.join([_pack('>B', _fm0version)] + part)
Yuya Nishihara
base85: proxy through util module...
r32200 keys['dump%i' % idx] = util.b85encode(data)
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295 return keys
Pierre-Yves.David@ens-lyon.org
obsolete: add easy way to iterate over obsolete marker object
r17073
Pierre-Yves David
obsolete: extract encoding of marker for pushkey from the list key function...
r20599 def listmarkers(repo):
"""List markers over pushkey"""
if not repo.obsstore:
return {}
Pierre-Yves David
obsolete: sort obsmarkers during exchange...
r25118 return _pushkeyescape(sorted(repo.obsstore))
Pierre-Yves David
obsolete: extract encoding of marker for pushkey from the list key function...
r20599
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 def pushmarker(repo, key, old, new):
"""Push markers over pushkey"""
Pierre-Yves David
pushkey: splits obsolete marker exchange into multiple keys...
r17295 if not key.startswith('dump'):
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 repo.ui.warn(_('unknown key: %r') % key)
Martin von Zweigbergk
pushkey: use False/True for return values from push functions...
r32822 return False
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 if old:
FUJIWARA Katsunori
obsolete: add '%' specifier to the format string to avoid TypeError at runtime...
r21098 repo.ui.warn(_('unexpected old value for %r') % key)
Martin von Zweigbergk
pushkey: use False/True for return values from push functions...
r32822 return False
Yuya Nishihara
base85: proxy through util module...
r32200 data = util.b85decode(new)
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 lock = repo.lock()
try:
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126 tr = repo.transaction('pushkey: obsolete markers')
try:
repo.obsstore.mergemarkers(tr, data)
obsolete: invalidate "volatile" set cache after merging marker...
r32314 repo.invalidatevolatilesets()
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126 tr.close()
Martin von Zweigbergk
pushkey: use False/True for return values from push functions...
r32822 return True
Pierre-Yves David
obsolete: write obsolete marker inside a transaction...
r17126 finally:
tr.release()
Pierre-Yves.David@ens-lyon.org
obsolete: exchange obsolete marker over pushkey...
r17075 finally:
lock.release()
Pierre-Yves.David@ens-lyon.org
obsolete: add easy way to iterate over obsolete marker object
r17073
obsolete: add a function to compute "exclusive-markers" for a set of nodes...
r32626 def getmarkers(repo, nodes=None, exclusive=False):
Pierre-Yves David
debugobsolete: add a --rev argument...
r22274 """returns markers known in a repository
If <nodes> is specified, only markers "relevant" to those nodes are are
returned"""
if nodes is None:
rawmarkers = repo.obsstore
obsolete: add a function to compute "exclusive-markers" for a set of nodes...
r32626 elif exclusive:
rawmarkers = exclusivemarkers(repo, nodes)
Pierre-Yves David
debugobsolete: add a --rev argument...
r22274 else:
rawmarkers = repo.obsstore.relevantmarkers(nodes)
for markerdata in rawmarkers:
Pierre-Yves.David@ens-lyon.org
obsolete: add easy way to iterate over obsolete marker object
r17073 yield marker(repo, markerdata)
Pierre-Yves David
debugobsolete: add a --rev argument...
r22274 def relevantmarkers(repo, node):
"""all obsolete markers relevant to some revision"""
for markerdata in repo.obsstore.relevantmarkers(node):
yield marker(repo, markerdata)
Pierre-Yves.David@ens-lyon.org
obsolete: function and method to access some obsolete data...
r17076 def precursormarkers(ctx):
Pierre-Yves David
obsolete: flip `obstore.successors` and `obsolete.precursors`...
r17776 """obsolete marker marking this changeset as a successors"""
Matt Harbison
obsolete: replace 'ctx._repo' with 'ctx.repo()'
r24335 for data in ctx.repo().obsstore.precursors.get(ctx.node(), ()):
yield marker(ctx.repo(), data)
Pierre-Yves.David@ens-lyon.org
obsolete: function and method to access some obsolete data...
r17076
def successormarkers(ctx):
Pierre-Yves David
obsolete: flip `obstore.successors` and `obsolete.precursors`...
r17776 """obsolete marker making this changeset obsolete"""
Matt Harbison
obsolete: replace 'ctx._repo' with 'ctx.repo()'
r24335 for data in ctx.repo().obsstore.successors.get(ctx.node(), ()):
yield marker(ctx.repo(), data)
Pierre-Yves.David@ens-lyon.org
obsolete: function and method to access some obsolete data...
r17076
Pierre-Yves David
obsolete: add a flag that allows fixing "bumped" changeset...
r17831 def allsuccessors(obsstore, nodes, ignoreflags=0):
Pierre-Yves David
obsolete: have `allsuccessors` takes a list of nodes...
r17827 """Yield node for every successor of <nodes>.
Some successors may be unknown locally.
Pierre-Yves David
obsolete: add an any successors function...
r17213
Pierre-Yves David
obsolete: improve allsuccessors doc string...
r20204 This is a linear yield unsuited to detecting split changesets. It includes
initial nodes too."""
Pierre-Yves David
obsolete: have `allsuccessors` takes a list of nodes...
r17827 remaining = set(nodes)
Pierre-Yves David
obsolete: add an any successors function...
r17213 seen = set(remaining)
while remaining:
current = remaining.pop()
yield current
Pierre-Yves David
obsolete: flip `obstore.successors` and `obsolete.precursors`...
r17776 for mark in obsstore.successors.get(current, ()):
Pierre-Yves David
obsolete: fix bad comment...
r20203 # ignore marker flagged with specified flag
Pierre-Yves David
obsolete: add a flag that allows fixing "bumped" changeset...
r17831 if mark[2] & ignoreflags:
continue
Pierre-Yves David
obsolete: add an any successors function...
r17213 for suc in mark[1]:
if suc not in seen:
seen.add(suc)
remaining.add(suc)
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469
Pierre-Yves David
obsolete: add an allprecursors method mirroring allsuccessors one....
r20206 def allprecursors(obsstore, nodes, ignoreflags=0):
"""Yield node for every precursors of <nodes>.
Some precursors may be unknown locally.
This is a linear yield unsuited to detecting folded changesets. It includes
initial nodes too."""
remaining = set(nodes)
seen = set(remaining)
while remaining:
current = remaining.pop()
yield current
for mark in obsstore.precursors.get(current, ()):
# ignore marker flagged with specified flag
if mark[2] & ignoreflags:
continue
suc = mark[0]
if suc not in seen:
seen.add(suc)
remaining.add(suc)
Pierre-Yves David
obsolete: extract foreground computation from bookmark.validdest...
r18984 def foreground(repo, nodes):
"""return all nodes in the "foreground" of other node
The foreground of a revision is anything reachable using parent -> children
Mads Kiilerich
spelling: random spell checker fixes
r19951 or precursor -> successor relation. It is very similar to "descendant" but
Pierre-Yves David
obsolete: extract foreground computation from bookmark.validdest...
r18984 augmented with obsolescence information.
Mads Kiilerich
spelling: random spell checker fixes
r19951 Beware that possible obsolescence cycle may result if complex situation.
Pierre-Yves David
obsolete: extract foreground computation from bookmark.validdest...
r18984 """
repo = repo.unfiltered()
foreground = set(repo.set('%ln::', nodes))
if repo.obsstore:
# We only need this complicated logic if there is obsolescence
# XXX will probably deserve an optimised revset.
nm = repo.changelog.nodemap
plen = -1
# compute the whole set of successors or descendants
while len(foreground) != plen:
plen = len(foreground)
succs = set(c.node() for c in foreground)
mutable = [c.node() for c in foreground if c.mutable()]
succs.update(allsuccessors(repo.obsstore, mutable))
known = (n for n in succs if n in nm)
foreground = set(repo.set('%ln::', known))
return set(c.node() for c in foreground)
Pierre-Yves David
obsolete: compute successors set...
r18068 def successorssets(repo, initialnode, cache=None):
obsutil: move 'successorssets' to the new modules...
r33143 movemsg = 'obsolete.successorssets moved to obsutil.successorssets'
repo.ui.deprecwarn(movemsg, '4.3')
return obsutil.successorssets(repo, initialnode, cache=cache)
Pierre-Yves David
obsolete: compute successors set...
r18068
Pierre-Yves David
obsolete: add the detection of bumped changeset....
r17828 # mapping of 'set-name' -> <function to compute this set>
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 cachefuncs = {}
def cachefor(name):
"""Decorator to register a function as computing the cache for a set"""
def decorator(func):
Pierre-Yves David
obsolete: use ProgrammingError over assert for volatile set registration...
r32884 if name in cachefuncs:
msg = "duplicated registration for volatileset '%s' (existing: %r)"
raise error.ProgrammingError(msg % (name, cachefuncs[name]))
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 cachefuncs[name] = func
return func
return decorator
Pierre-Yves David
obsolete: rename `getobscache` into `getrevs`...
r17825 def getrevs(repo, name):
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 """Return the set of revision that belong to the <name> set
Such access may compute the set and cache it for future use"""
Pierre-Yves David
clfilter: unfilter computation of obsolescence related computation...
r18001 repo = repo.unfiltered()
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 if not repo.obsstore:
Pierre-Yves David
obsolete: ensure that `getrevs` always return a set...
r22507 return frozenset()
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 if name not in repo.obsstore.caches:
repo.obsstore.caches[name] = cachefuncs[name](repo)
return repo.obsstore.caches[name]
# To be simple we need to invalidate obsolescence cache when:
#
# - new changeset is added:
# - public phase is changed
# - obsolescence marker are added
# - strip is used a repo
def clearobscaches(repo):
"""Remove all obsolescence related cache from a repo
This remove all cache in obsstore is the obsstore already exist on the
repo.
(We could be smarter here given the exact event that trigger the cache
clearing)"""
# only clear cache is there is obsstore data in this repo
if 'obsstore' in repo._filecache:
repo.obsstore.caches.clear()
obsolete: provide a small function to retrieve all mutable revisions...
r33124 def _mutablerevs(repo):
"""the set of mutable revision in the repository"""
return repo._phasecache.getrevset(repo, (phases.draft, phases.secret))
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469 @cachefor('obsolete')
def _computeobsoleteset(repo):
"""the set of obsolete revisions"""
Laurent Charignon
obsolete: make _computeobsoleteset much faster...
r27784 getnode = repo.changelog.node
obsolete: provide a small function to retrieve all mutable revisions...
r33124 notpublic = _mutablerevs(repo)
Jun Wu
obsstore: minor optimization for the obsolete revset...
r32688 isobs = repo.obsstore.successors.__contains__
obs = set(r for r in notpublic if isobs(getnode(r)))
Pierre-Yves David
performance: speedup computation of obsolete revisions...
r18271 return obs
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469
@cachefor('unstable')
def _computeunstableset(repo):
"""the set of non obsolete revisions with obsolete parents"""
obsolete: skip 'changectx' usage in unstable computation...
r33125 pfunc = repo.changelog.parentrevs
mutable = _mutablerevs(repo)
obsolete = getrevs(repo, 'obsolete')
others = mutable - obsolete
Laurent Charignon
obsolete: speed up unstable computation...
r24928 unstable = set()
obsolete: skip 'changectx' usage in unstable computation...
r33125 for r in sorted(others):
Laurent Charignon
obsolete: speed up unstable computation...
r24928 # A rev is unstable if one of its parent is obsolete or unstable
# this works since we traverse following growing rev order
obsolete: skip 'changectx' usage in unstable computation...
r33125 for p in pfunc(r):
if p in obsolete or p in unstable:
unstable.add(r)
break
Laurent Charignon
obsolete: speed up unstable computation...
r24928 return unstable
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469
@cachefor('suspended')
def _computesuspendedset(repo):
"""the set of obsolete parents with non obsolete descendants"""
Pierre-Yves David
performance: speedup computation of suspended revisions...
r18276 suspended = repo.changelog.ancestors(getrevs(repo, 'unstable'))
return set(r for r in getrevs(repo, 'obsolete') if r in suspended)
Pierre-Yves David
obsolete: introduce caches for all meaningful sets...
r17469
@cachefor('extinct')
def _computeextinctset(repo):
"""the set of obsolete parents without non obsolete descendants"""
Pierre-Yves David
performance: speedup computation of extinct revisions...
r18277 return getrevs(repo, 'obsolete') - getrevs(repo, 'suspended')
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474
Pierre-Yves David
obsolete: add the detection of bumped changeset....
r17828
@cachefor('bumped')
def _computebumpedset(repo):
"""the set of revs trying to obsolete public revisions"""
Pierre-Yves David
obsolete: order of magnitude speedup in _computebumpedset...
r20207 bumped = set()
Mads Kiilerich
spelling: fixes from spell checker
r21024 # util function (avoid attribute lookup in the loop)
Pierre-Yves David
obsolete: order of magnitude speedup in _computebumpedset...
r20207 phase = repo._phasecache.phase # would be faster to grab the full list
public = phases.public
cl = repo.changelog
torev = cl.nodemap.get
Laurent Charignon
obsolete: speed up computation of bumped revset...
r24927 for ctx in repo.set('(not public()) and (not obsolete())'):
rev = ctx.rev()
Pierre-Yves David
obsolete: order of magnitude speedup in _computebumpedset...
r20207 # We only evaluate mutable, non-obsolete revision
Laurent Charignon
obsolete: speed up computation of bumped revset...
r24927 node = ctx.node()
# (future) A cache of precursors may worth if split is very common
for pnode in allprecursors(repo.obsstore, [node],
ignoreflags=bumpedfix):
prev = torev(pnode) # unfiltered! but so is phasecache
if (prev is not None) and (phase(repo, prev) <= public):
timeless
obsolete: fix grammar
r29281 # we have a public precursor
Laurent Charignon
obsolete: speed up computation of bumped revset...
r24927 bumped.add(rev)
break # Next draft!
Pierre-Yves David
obsolete: order of magnitude speedup in _computebumpedset...
r20207 return bumped
Pierre-Yves David
obsolete: add the detection of bumped changeset....
r17828
Pierre-Yves David
obsolete: detect divergent changesets...
r18070 @cachefor('divergent')
def _computedivergentset(repo):
"""the set of rev that compete to be the final successors of some revision.
"""
divergent = set()
obsstore = repo.obsstore
newermap = {}
for ctx in repo.set('(not public()) - obsolete()'):
mark = obsstore.precursors.get(ctx.node(), ())
toprocess = set(mark)
Pierre-Yves David
obsolete: avoid infinite loop from obs-cycle in divergence (issue4126)...
r24393 seen = set()
Pierre-Yves David
obsolete: detect divergent changesets...
r18070 while toprocess:
prec = toprocess.pop()[0]
Pierre-Yves David
obsolete: avoid infinite loop from obs-cycle in divergence (issue4126)...
r24393 if prec in seen:
continue # emergency cycle hanging prevention
seen.add(prec)
Pierre-Yves David
obsolete: detect divergent changesets...
r18070 if prec not in newermap:
obsutil: move 'successorssets' to the new modules...
r33143 obsutil.successorssets(repo, prec, newermap)
Pierre-Yves David
obsolete: detect divergent changesets...
r18070 newer = [n for n in newermap[prec] if n]
if len(newer) > 1:
divergent.add(ctx.rev())
break
toprocess.update(obsstore.precursors.get(prec, ()))
return divergent
Durham Goode
obsolete: add operation metadata to rebase/amend/histedit obsmarkers...
r32327 def createmarkers(repo, relations, flag=0, date=None, metadata=None,
operation=None):
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 """Add obsolete markers between changesets in a repo
Pierre-Yves David
createmarkers: allow to pass metadata for a marker only...
r20517 <relations> must be an iterable of (<old>, (<new>, ...)[,{metadata}])
Mads Kiilerich
spelling: fixes from spell checker
r21024 tuple. `old` and `news` are changectx. metadata is an optional dictionary
Pierre-Yves David
createmarkers: allow to pass metadata for a marker only...
r20517 containing metadata for this marker only. It is merged with the global
metadata specified through the `metadata` argument of this function,
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474
Trying to obsolete a public changeset will raise an exception.
Current user and date are used except if specified otherwise in the
metadata attribute.
This function operates within a transaction of its own, but does
not take any lock on the repo.
"""
# prepare metadata
if metadata is None:
metadata = {}
if 'user' not in metadata:
metadata['user'] = repo.ui.username()
obsmarker: add an experimental flag controlling "operation" recording...
r32354 useoperation = repo.ui.configbool('experimental',
'evolution.track-operation',
False)
if useoperation and operation:
Durham Goode
obsolete: add operation metadata to rebase/amend/histedit obsmarkers...
r32327 metadata['operation'] = operation
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 tr = repo.transaction('add-obsolescence-marker')
try:
Durham Goode
obsolete: fix n^2 marker computation behavior...
r27984 markerargs = []
Pierre-Yves David
createmarkers: allow to pass metadata for a marker only...
r20517 for rel in relations:
prec = rel[0]
sucs = rel[1]
localmetadata = metadata.copy()
if 2 < len(rel):
localmetadata.update(rel[2])
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 if not prec.mutable():
liscju
i18n: translate abort messages...
r29389 raise error.Abort(_("cannot obsolete public changeset: %s")
Jordi GutiƩrrez Hermoso
phases: add `hg help phases` hint to failures to edit public commits...
r25412 % prec,
timeless
obsolete: use single quotes in use warning
r29976 hint="see 'hg help phases' for details")
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 nprec = prec.node()
nsucs = tuple(s.node() for s in sucs)
Pierre-Yves David
createmarkers: automatically record the parent of pruned changesets...
r22256 npare = None
if not nsucs:
npare = tuple(p.node() for p in prec.parents())
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 if nprec in nsucs:
liscju
i18n: translate abort messages...
r29389 raise error.Abort(_("changeset %s cannot obsolete itself")
% prec)
Durham Goode
obsolete: fix n^2 marker computation behavior...
r27984
# Creating the marker causes the hidden cache to become invalid,
# which causes recomputation when we ask for prec.parents() above.
# Resulting in n^2 behavior. So let's prepare all of the args
# first, then create the markers.
markerargs.append((nprec, nsucs, npare, localmetadata))
for args in markerargs:
nprec, nsucs, npare, localmetadata = args
Pierre-Yves David
createmarkers: automatically record the parent of pruned changesets...
r22256 repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
Boris Feld
devel: use default-date config field when creating obsmarkers...
r32411 date=date, metadata=localmetadata,
ui=repo.ui)
Pierre-Yves David
clfilter: add a cache on repo for set of revision to filter for a given set....
r18101 repo.filteredrevcache.clear()
Pierre-Yves David
obsolete: add a high level function to create an obsolete marker...
r17474 tr.close()
finally:
tr.release()