diff --git a/mercurial/cext/revlog.c b/mercurial/cext/revlog.c --- a/mercurial/cext/revlog.c +++ b/mercurial/cext/revlog.c @@ -1,2984 +1,3018 @@ /* parsers.c - efficient content parsing Copyright 2008 Olivia Mackall and others This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #define PY_SSIZE_T_CLEAN #include #include #include #include #include #include #include #include #include "bitmanipulation.h" #include "charencode.h" #include "compat.h" #include "revlog.h" #include "util.h" #ifdef IS_PY3K /* The mapping of Python types is meant to be temporary to get Python * 3 to compile. We should remove this once Python 3 support is fully * supported and proper types are used in the extensions themselves. */ #define PyInt_Check PyLong_Check #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #endif typedef struct indexObjectStruct indexObject; typedef struct { int children[16]; } nodetreenode; typedef struct { int abi_version; Py_ssize_t (*index_length)(const indexObject *); const char *(*index_node)(indexObject *, Py_ssize_t); int (*index_parents)(PyObject *, int, int *); } Revlog_CAPI; /* * A base-16 trie for fast node->rev mapping. * * Positive value is index of the next node in the trie * Negative value is a leaf: -(rev + 2) * Zero is empty */ typedef struct { indexObject *index; nodetreenode *nodes; Py_ssize_t nodelen; size_t length; /* # nodes in use */ size_t capacity; /* # nodes allocated */ int depth; /* maximum depth of tree */ int splits; /* # splits performed */ } nodetree; typedef struct { PyObject_HEAD /* ; */ nodetree nt; } nodetreeObject; /* * This class has two behaviors. * * When used in a list-like way (with integer keys), we decode an * entry in a RevlogNG index file on demand. We have limited support for * integer-keyed insert and delete, only at elements right before the * end. * * With string keys, we lazily perform a reverse mapping from node to * rev, using a base-16 trie. */ struct indexObjectStruct { PyObject_HEAD /* Type-specific fields go here. */ PyObject *data; /* raw bytes of index */ Py_ssize_t nodelen; /* digest size of the hash, 20 for SHA-1 */ PyObject *nullentry; /* fast path for references to null */ Py_buffer buf; /* buffer of data */ const char **offsets; /* populated on demand */ Py_ssize_t length; /* current on-disk number of elements */ unsigned new_length; /* number of added elements */ unsigned added_length; /* space reserved for added elements */ char *added; /* populated on demand */ PyObject *headrevs; /* cache, invalidated on changes */ PyObject *filteredrevs; /* filtered revs set */ nodetree nt; /* base-16 trie */ int ntinitialized; /* 0 or 1 */ int ntrev; /* last rev scanned */ int ntlookups; /* # lookups */ int ntmisses; /* # lookups that miss the cache */ int inlined; long hdrsize; /* size of index headers. Differs in v1 v.s. v2 format */ }; static Py_ssize_t index_length(const indexObject *self) { return self->length + self->new_length; } static const char nullid[32] = {0}; static const Py_ssize_t nullrev = -1; static Py_ssize_t inline_scan(indexObject *self, const char **offsets); static int index_find_node(indexObject *self, const char *node); #if LONG_MAX == 0x7fffffffL static const char *const v1_tuple_format = PY23("Kiiiiiis#", "Kiiiiiiy#"); static const char *const v2_tuple_format = PY23("Kiiiiiis#Ki", "Kiiiiiiy#Ki"); #else static const char *const v1_tuple_format = PY23("kiiiiiis#", "kiiiiiiy#"); static const char *const v2_tuple_format = PY23("kiiiiiis#ki", "kiiiiiiy#ki"); #endif /* A RevlogNG v1 index entry is 64 bytes long. */ static const long v1_hdrsize = 64; /* A Revlogv2 index entry is 96 bytes long. */ static const long v2_hdrsize = 96; static void raise_revlog_error(void) { PyObject *mod = NULL, *dict = NULL, *errclass = NULL; mod = PyImport_ImportModule("mercurial.error"); if (mod == NULL) { goto cleanup; } dict = PyModule_GetDict(mod); if (dict == NULL) { goto cleanup; } Py_INCREF(dict); errclass = PyDict_GetItemString(dict, "RevlogError"); if (errclass == NULL) { PyErr_SetString(PyExc_SystemError, "could not find RevlogError"); goto cleanup; } /* value of exception is ignored by callers */ PyErr_SetString(errclass, "RevlogError"); cleanup: Py_XDECREF(dict); Py_XDECREF(mod); } /* * Return a pointer to the beginning of a RevlogNG record. */ static const char *index_deref(indexObject *self, Py_ssize_t pos) { if (pos >= self->length) return self->added + (pos - self->length) * self->hdrsize; if (self->inlined && pos > 0) { if (self->offsets == NULL) { Py_ssize_t ret; self->offsets = PyMem_Malloc(self->length * sizeof(*self->offsets)); if (self->offsets == NULL) return (const char *)PyErr_NoMemory(); ret = inline_scan(self, self->offsets); if (ret == -1) { return NULL; }; } return self->offsets[pos]; } return (const char *)(self->buf.buf) + pos * self->hdrsize; } /* * Get parents of the given rev. * * The specified rev must be valid and must not be nullrev. A returned * parent revision may be nullrev, but is guaranteed to be in valid range. */ static inline int index_get_parents(indexObject *self, Py_ssize_t rev, int *ps, int maxrev) { const char *data = index_deref(self, rev); ps[0] = getbe32(data + 24); ps[1] = getbe32(data + 28); /* If index file is corrupted, ps[] may point to invalid revisions. So * there is a risk of buffer overflow to trust them unconditionally. */ if (ps[0] < -1 || ps[0] > maxrev || ps[1] < -1 || ps[1] > maxrev) { PyErr_SetString(PyExc_ValueError, "parent out of range"); return -1; } return 0; } /* * Get parents of the given rev. * * If the specified rev is out of range, IndexError will be raised. If the * revlog entry is corrupted, ValueError may be raised. * * Returns 0 on success or -1 on failure. */ static int HgRevlogIndex_GetParents(PyObject *op, int rev, int *ps) { int tiprev; if (!op || !HgRevlogIndex_Check(op) || !ps) { PyErr_BadInternalCall(); return -1; } tiprev = (int)index_length((indexObject *)op) - 1; if (rev < -1 || rev > tiprev) { PyErr_Format(PyExc_IndexError, "rev out of range: %d", rev); return -1; } else if (rev == -1) { ps[0] = ps[1] = -1; return 0; } else { return index_get_parents((indexObject *)op, rev, ps, tiprev); } } static inline int64_t index_get_start(indexObject *self, Py_ssize_t rev) { const char *data; uint64_t offset; if (rev == nullrev) return 0; data = index_deref(self, rev); offset = getbe32(data + 4); if (rev == 0) { /* mask out version number for the first entry */ offset &= 0xFFFF; } else { uint32_t offset_high = getbe32(data); offset |= ((uint64_t)offset_high) << 32; } return (int64_t)(offset >> 16); } static inline int index_get_length(indexObject *self, Py_ssize_t rev) { const char *data; int tmp; if (rev == nullrev) return 0; data = index_deref(self, rev); tmp = (int)getbe32(data + 8); if (tmp < 0) { PyErr_Format(PyExc_OverflowError, "revlog entry size out of bound (%d)", tmp); return -1; } return tmp; } /* * RevlogNG format (all in big endian, data may be inlined): * 6 bytes: offset * 2 bytes: flags * 4 bytes: compressed length * 4 bytes: uncompressed length * 4 bytes: base revision * 4 bytes: link revision * 4 bytes: parent 1 revision * 4 bytes: parent 2 revision * 32 bytes: nodeid (only 20 bytes used with SHA-1) */ static PyObject *index_get(indexObject *self, Py_ssize_t pos) { uint64_t offset_flags, sidedata_offset; int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2, sidedata_comp_len; const char *c_node_id; const char *data; Py_ssize_t length = index_length(self); if (pos == nullrev) { Py_INCREF(self->nullentry); return self->nullentry; } if (pos < 0 || pos >= length) { PyErr_SetString(PyExc_IndexError, "revlog index out of range"); return NULL; } data = index_deref(self, pos); if (data == NULL) return NULL; offset_flags = getbe32(data + 4); /* * The first entry on-disk needs the version number masked out, * but this doesn't apply if entries are added to an empty index. */ if (self->length && pos == 0) offset_flags &= 0xFFFF; else { uint32_t offset_high = getbe32(data); offset_flags |= ((uint64_t)offset_high) << 32; } comp_len = getbe32(data + 8); uncomp_len = getbe32(data + 12); base_rev = getbe32(data + 16); link_rev = getbe32(data + 20); parent_1 = getbe32(data + 24); parent_2 = getbe32(data + 28); c_node_id = data + 32; if (self->hdrsize == v1_hdrsize) { return Py_BuildValue(v1_tuple_format, offset_flags, comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2, c_node_id, self->nodelen); } else { sidedata_offset = getbe64(data + 64); sidedata_comp_len = getbe32(data + 72); return Py_BuildValue(v2_tuple_format, offset_flags, comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2, c_node_id, self->nodelen, sidedata_offset, sidedata_comp_len); } } +/* + * Return the raw binary string representing a revision + */ +static PyObject *index_entry_binary(indexObject *self, PyObject *args) +{ + long rev; + int header; + const char *data; + char entry[v2_hdrsize]; + + Py_ssize_t length = index_length(self); + + if (!PyArg_ParseTuple(args, "lI", &rev, &header)) { + return NULL; + } + if (rev < 0 || rev >= length) { + PyErr_Format(PyExc_ValueError, "revlog index out of range: %ld", + rev); + return NULL; + }; + + data = index_deref(self, rev); + if (data == NULL) + return NULL; + if (rev == 0) { + // put the header at the start of the first entry + memcpy(entry, data, self->hdrsize); + putbe32(header, entry); + return PyBytes_FromStringAndSize(entry, self->hdrsize); + } + return PyBytes_FromStringAndSize(data, self->hdrsize); +} /* * Return the hash of node corresponding to the given rev. */ static const char *index_node(indexObject *self, Py_ssize_t pos) { Py_ssize_t length = index_length(self); const char *data; if (pos == nullrev) return nullid; if (pos >= length) return NULL; data = index_deref(self, pos); return data ? data + 32 : NULL; } /* * Return the hash of the node corresponding to the given rev. The * rev is assumed to be existing. If not, an exception is set. */ static const char *index_node_existing(indexObject *self, Py_ssize_t pos) { const char *node = index_node(self, pos); if (node == NULL) { PyErr_Format(PyExc_IndexError, "could not access rev %d", (int)pos); } return node; } static int nt_insert(nodetree *self, const char *node, int rev); static int node_check(Py_ssize_t nodelen, PyObject *obj, char **node) { Py_ssize_t thisnodelen; if (PyBytes_AsStringAndSize(obj, node, &thisnodelen) == -1) return -1; if (nodelen == thisnodelen) return 0; PyErr_Format(PyExc_ValueError, "node len %zd != expected node len %zd", thisnodelen, nodelen); return -1; } static PyObject *index_append(indexObject *self, PyObject *obj) { uint64_t offset_flags, sidedata_offset; int rev, comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2; Py_ssize_t c_node_id_len, sidedata_comp_len; const char *c_node_id; char *data; if (self->hdrsize == v1_hdrsize) { if (!PyArg_ParseTuple(obj, v1_tuple_format, &offset_flags, &comp_len, &uncomp_len, &base_rev, &link_rev, &parent_1, &parent_2, &c_node_id, &c_node_id_len)) { PyErr_SetString(PyExc_TypeError, "8-tuple required"); return NULL; } } else { if (!PyArg_ParseTuple(obj, v2_tuple_format, &offset_flags, &comp_len, &uncomp_len, &base_rev, &link_rev, &parent_1, &parent_2, &c_node_id, &c_node_id_len, &sidedata_offset, &sidedata_comp_len)) { PyErr_SetString(PyExc_TypeError, "10-tuple required"); return NULL; } } if (c_node_id_len != self->nodelen) { PyErr_SetString(PyExc_TypeError, "invalid node"); return NULL; } if (self->new_length == self->added_length) { size_t new_added_length = self->added_length ? self->added_length * 2 : 4096; void *new_added = PyMem_Realloc(self->added, new_added_length * self->hdrsize); if (!new_added) return PyErr_NoMemory(); self->added = new_added; self->added_length = new_added_length; } rev = self->length + self->new_length; data = self->added + self->hdrsize * self->new_length++; putbe32(offset_flags >> 32, data); putbe32(offset_flags & 0xffffffffU, data + 4); putbe32(comp_len, data + 8); putbe32(uncomp_len, data + 12); putbe32(base_rev, data + 16); putbe32(link_rev, data + 20); putbe32(parent_1, data + 24); putbe32(parent_2, data + 28); memcpy(data + 32, c_node_id, c_node_id_len); /* Padding since SHA-1 is only 20 bytes for now */ memset(data + 32 + c_node_id_len, 0, 32 - c_node_id_len); if (self->hdrsize != v1_hdrsize) { putbe64(sidedata_offset, data + 64); putbe32(sidedata_comp_len, data + 72); /* Padding for 96 bytes alignment */ memset(data + 76, 0, self->hdrsize - 76); } if (self->ntinitialized) nt_insert(&self->nt, c_node_id, rev); Py_CLEAR(self->headrevs); Py_RETURN_NONE; } /* Replace an existing index entry's sidedata offset and length with new ones. This cannot be used outside of the context of sidedata rewriting, inside the transaction that creates the given revision. */ static PyObject *index_replace_sidedata_info(indexObject *self, PyObject *args) { uint64_t sidedata_offset; int rev; Py_ssize_t sidedata_comp_len; char *data; #if LONG_MAX == 0x7fffffffL const char *const sidedata_format = PY23("nKi", "nKi"); #else const char *const sidedata_format = PY23("nki", "nki"); #endif if (self->hdrsize == v1_hdrsize || self->inlined) { /* There is a bug in the transaction handling when going from an inline revlog to a separate index and data file. Turn it off until it's fixed, since v2 revlogs sometimes get rewritten on exchange. See issue6485. */ raise_revlog_error(); return NULL; } if (!PyArg_ParseTuple(args, sidedata_format, &rev, &sidedata_offset, &sidedata_comp_len)) return NULL; if (rev < 0 || rev >= index_length(self)) { PyErr_SetString(PyExc_IndexError, "revision outside index"); return NULL; } if (rev < self->length) { PyErr_SetString( PyExc_IndexError, "cannot rewrite entries outside of this transaction"); return NULL; } /* Find the newly added node, offset from the "already on-disk" length */ data = self->added + self->hdrsize * (rev - self->length); putbe64(sidedata_offset, data + 64); putbe32(sidedata_comp_len, data + 72); Py_RETURN_NONE; } static PyObject *index_stats(indexObject *self) { PyObject *obj = PyDict_New(); PyObject *s = NULL; PyObject *t = NULL; if (obj == NULL) return NULL; #define istat(__n, __d) \ do { \ s = PyBytes_FromString(__d); \ t = PyInt_FromSsize_t(self->__n); \ if (!s || !t) \ goto bail; \ if (PyDict_SetItem(obj, s, t) == -1) \ goto bail; \ Py_CLEAR(s); \ Py_CLEAR(t); \ } while (0) if (self->added_length) istat(new_length, "index entries added"); istat(length, "revs in memory"); istat(ntlookups, "node trie lookups"); istat(ntmisses, "node trie misses"); istat(ntrev, "node trie last rev scanned"); if (self->ntinitialized) { istat(nt.capacity, "node trie capacity"); istat(nt.depth, "node trie depth"); istat(nt.length, "node trie count"); istat(nt.splits, "node trie splits"); } #undef istat return obj; bail: Py_XDECREF(obj); Py_XDECREF(s); Py_XDECREF(t); return NULL; } /* * When we cache a list, we want to be sure the caller can't mutate * the cached copy. */ static PyObject *list_copy(PyObject *list) { Py_ssize_t len = PyList_GET_SIZE(list); PyObject *newlist = PyList_New(len); Py_ssize_t i; if (newlist == NULL) return NULL; for (i = 0; i < len; i++) { PyObject *obj = PyList_GET_ITEM(list, i); Py_INCREF(obj); PyList_SET_ITEM(newlist, i, obj); } return newlist; } static int check_filter(PyObject *filter, Py_ssize_t arg) { if (filter) { PyObject *arglist, *result; int isfiltered; arglist = Py_BuildValue("(n)", arg); if (!arglist) { return -1; } result = PyObject_Call(filter, arglist, NULL); Py_DECREF(arglist); if (!result) { return -1; } /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error, * same as this function, so we can just return it directly.*/ isfiltered = PyObject_IsTrue(result); Py_DECREF(result); return isfiltered; } else { return 0; } } static inline void set_phase_from_parents(char *phases, int parent_1, int parent_2, Py_ssize_t i) { if (parent_1 >= 0 && phases[parent_1] > phases[i]) phases[i] = phases[parent_1]; if (parent_2 >= 0 && phases[parent_2] > phases[i]) phases[i] = phases[parent_2]; } static PyObject *reachableroots2(indexObject *self, PyObject *args) { /* Input */ long minroot; PyObject *includepatharg = NULL; int includepath = 0; /* heads and roots are lists */ PyObject *heads = NULL; PyObject *roots = NULL; PyObject *reachable = NULL; PyObject *val; Py_ssize_t len = index_length(self); long revnum; Py_ssize_t k; Py_ssize_t i; Py_ssize_t l; int r; int parents[2]; /* Internal data structure: * tovisit: array of length len+1 (all revs + nullrev), filled upto * lentovisit * * revstates: array of length len+1 (all revs + nullrev) */ int *tovisit = NULL; long lentovisit = 0; enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 }; char *revstates = NULL; /* Get arguments */ if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads, &PyList_Type, &roots, &PyBool_Type, &includepatharg)) goto bail; if (includepatharg == Py_True) includepath = 1; /* Initialize return set */ reachable = PyList_New(0); if (reachable == NULL) goto bail; /* Initialize internal datastructures */ tovisit = (int *)malloc((len + 1) * sizeof(int)); if (tovisit == NULL) { PyErr_NoMemory(); goto bail; } revstates = (char *)calloc(len + 1, 1); if (revstates == NULL) { PyErr_NoMemory(); goto bail; } l = PyList_GET_SIZE(roots); for (i = 0; i < l; i++) { revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i)); if (revnum == -1 && PyErr_Occurred()) goto bail; /* If root is out of range, e.g. wdir(), it must be unreachable * from heads. So we can just ignore it. */ if (revnum + 1 < 0 || revnum + 1 >= len + 1) continue; revstates[revnum + 1] |= RS_ROOT; } /* Populate tovisit with all the heads */ l = PyList_GET_SIZE(heads); for (i = 0; i < l; i++) { revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i)); if (revnum == -1 && PyErr_Occurred()) goto bail; if (revnum + 1 < 0 || revnum + 1 >= len + 1) { PyErr_SetString(PyExc_IndexError, "head out of range"); goto bail; } if (!(revstates[revnum + 1] & RS_SEEN)) { tovisit[lentovisit++] = (int)revnum; revstates[revnum + 1] |= RS_SEEN; } } /* Visit the tovisit list and find the reachable roots */ k = 0; while (k < lentovisit) { /* Add the node to reachable if it is a root*/ revnum = tovisit[k++]; if (revstates[revnum + 1] & RS_ROOT) { revstates[revnum + 1] |= RS_REACHABLE; val = PyInt_FromLong(revnum); if (val == NULL) goto bail; r = PyList_Append(reachable, val); Py_DECREF(val); if (r < 0) goto bail; if (includepath == 0) continue; } /* Add its parents to the list of nodes to visit */ if (revnum == nullrev) continue; r = index_get_parents(self, revnum, parents, (int)len - 1); if (r < 0) goto bail; for (i = 0; i < 2; i++) { if (!(revstates[parents[i] + 1] & RS_SEEN) && parents[i] >= minroot) { tovisit[lentovisit++] = parents[i]; revstates[parents[i] + 1] |= RS_SEEN; } } } /* Find all the nodes in between the roots we found and the heads * and add them to the reachable set */ if (includepath == 1) { long minidx = minroot; if (minidx < 0) minidx = 0; for (i = minidx; i < len; i++) { if (!(revstates[i + 1] & RS_SEEN)) continue; r = index_get_parents(self, i, parents, (int)len - 1); /* Corrupted index file, error is set from * index_get_parents */ if (r < 0) goto bail; if (((revstates[parents[0] + 1] | revstates[parents[1] + 1]) & RS_REACHABLE) && !(revstates[i + 1] & RS_REACHABLE)) { revstates[i + 1] |= RS_REACHABLE; val = PyInt_FromSsize_t(i); if (val == NULL) goto bail; r = PyList_Append(reachable, val); Py_DECREF(val); if (r < 0) goto bail; } } } free(revstates); free(tovisit); return reachable; bail: Py_XDECREF(reachable); free(revstates); free(tovisit); return NULL; } static int add_roots_get_min(indexObject *self, PyObject *roots, char *phases, char phase) { Py_ssize_t len = index_length(self); PyObject *item; PyObject *iterator; int rev, minrev = -1; char *node; if (!PySet_Check(roots)) { PyErr_SetString(PyExc_TypeError, "roots must be a set of nodes"); return -2; } iterator = PyObject_GetIter(roots); if (iterator == NULL) return -2; while ((item = PyIter_Next(iterator))) { if (node_check(self->nodelen, item, &node) == -1) goto failed; rev = index_find_node(self, node); /* null is implicitly public, so negative is invalid */ if (rev < 0 || rev >= len) goto failed; phases[rev] = phase; if (minrev == -1 || minrev > rev) minrev = rev; Py_DECREF(item); } Py_DECREF(iterator); return minrev; failed: Py_DECREF(iterator); Py_DECREF(item); return -2; } static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args) { /* 0: public (untracked), 1: draft, 2: secret, 32: archive, 96: internal */ static const char trackedphases[] = {1, 2, 32, 96}; PyObject *roots = Py_None; PyObject *phasesetsdict = NULL; PyObject *phasesets[4] = {NULL, NULL, NULL, NULL}; Py_ssize_t len = index_length(self); char *phases = NULL; int minphaserev = -1, rev, i; const int numphases = (int)(sizeof(phasesets) / sizeof(phasesets[0])); if (!PyArg_ParseTuple(args, "O", &roots)) return NULL; if (roots == NULL || !PyDict_Check(roots)) { PyErr_SetString(PyExc_TypeError, "roots must be a dictionary"); return NULL; } phases = calloc(len, 1); if (phases == NULL) { PyErr_NoMemory(); return NULL; } for (i = 0; i < numphases; ++i) { PyObject *pyphase = PyInt_FromLong(trackedphases[i]); PyObject *phaseroots = NULL; if (pyphase == NULL) goto release; phaseroots = PyDict_GetItem(roots, pyphase); Py_DECREF(pyphase); if (phaseroots == NULL) continue; rev = add_roots_get_min(self, phaseroots, phases, trackedphases[i]); if (rev == -2) goto release; if (rev != -1 && (minphaserev == -1 || rev < minphaserev)) minphaserev = rev; } for (i = 0; i < numphases; ++i) { phasesets[i] = PySet_New(NULL); if (phasesets[i] == NULL) goto release; } if (minphaserev == -1) minphaserev = len; for (rev = minphaserev; rev < len; ++rev) { PyObject *pyphase = NULL; PyObject *pyrev = NULL; int parents[2]; /* * The parent lookup could be skipped for phaseroots, but * phase --force would historically not recompute them * correctly, leaving descendents with a lower phase around. * As such, unconditionally recompute the phase. */ if (index_get_parents(self, rev, parents, (int)len - 1) < 0) goto release; set_phase_from_parents(phases, parents[0], parents[1], rev); switch (phases[rev]) { case 0: continue; case 1: pyphase = phasesets[0]; break; case 2: pyphase = phasesets[1]; break; case 32: pyphase = phasesets[2]; break; case 96: pyphase = phasesets[3]; break; default: /* this should never happen since the phase number is * specified by this function. */ PyErr_SetString(PyExc_SystemError, "bad phase number in internal list"); goto release; } pyrev = PyInt_FromLong(rev); if (pyrev == NULL) goto release; if (PySet_Add(pyphase, pyrev) == -1) { Py_DECREF(pyrev); goto release; } Py_DECREF(pyrev); } phasesetsdict = _dict_new_presized(numphases); if (phasesetsdict == NULL) goto release; for (i = 0; i < numphases; ++i) { PyObject *pyphase = PyInt_FromLong(trackedphases[i]); if (pyphase == NULL) goto release; if (PyDict_SetItem(phasesetsdict, pyphase, phasesets[i]) == -1) { Py_DECREF(pyphase); goto release; } Py_DECREF(phasesets[i]); phasesets[i] = NULL; } return Py_BuildValue("nN", len, phasesetsdict); release: for (i = 0; i < numphases; ++i) Py_XDECREF(phasesets[i]); Py_XDECREF(phasesetsdict); free(phases); return NULL; } static PyObject *index_headrevs(indexObject *self, PyObject *args) { Py_ssize_t i, j, len; char *nothead = NULL; PyObject *heads = NULL; PyObject *filter = NULL; PyObject *filteredrevs = Py_None; if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) { return NULL; } if (self->headrevs && filteredrevs == self->filteredrevs) return list_copy(self->headrevs); Py_DECREF(self->filteredrevs); self->filteredrevs = filteredrevs; Py_INCREF(filteredrevs); if (filteredrevs != Py_None) { filter = PyObject_GetAttrString(filteredrevs, "__contains__"); if (!filter) { PyErr_SetString( PyExc_TypeError, "filteredrevs has no attribute __contains__"); goto bail; } } len = index_length(self); heads = PyList_New(0); if (heads == NULL) goto bail; if (len == 0) { PyObject *nullid = PyInt_FromLong(-1); if (nullid == NULL || PyList_Append(heads, nullid) == -1) { Py_XDECREF(nullid); goto bail; } goto done; } nothead = calloc(len, 1); if (nothead == NULL) { PyErr_NoMemory(); goto bail; } for (i = len - 1; i >= 0; i--) { int isfiltered; int parents[2]; /* If nothead[i] == 1, it means we've seen an unfiltered child * of this node already, and therefore this node is not * filtered. So we can skip the expensive check_filter step. */ if (nothead[i] != 1) { isfiltered = check_filter(filter, i); if (isfiltered == -1) { PyErr_SetString(PyExc_TypeError, "unable to check filter"); goto bail; } if (isfiltered) { nothead[i] = 1; continue; } } if (index_get_parents(self, i, parents, (int)len - 1) < 0) goto bail; for (j = 0; j < 2; j++) { if (parents[j] >= 0) nothead[parents[j]] = 1; } } for (i = 0; i < len; i++) { PyObject *head; if (nothead[i]) continue; head = PyInt_FromSsize_t(i); if (head == NULL || PyList_Append(heads, head) == -1) { Py_XDECREF(head); goto bail; } } done: self->headrevs = heads; Py_XDECREF(filter); free(nothead); return list_copy(self->headrevs); bail: Py_XDECREF(filter); Py_XDECREF(heads); free(nothead); return NULL; } /** * Obtain the base revision index entry. * * Callers must ensure that rev >= 0 or illegal memory access may occur. */ static inline int index_baserev(indexObject *self, int rev) { const char *data; int result; data = index_deref(self, rev); if (data == NULL) return -2; result = getbe32(data + 16); if (result > rev) { PyErr_Format( PyExc_ValueError, "corrupted revlog, revision base above revision: %d, %d", rev, result); return -2; } if (result < -1) { PyErr_Format( PyExc_ValueError, "corrupted revlog, revision base out of range: %d, %d", rev, result); return -2; } return result; } /** * Find if a revision is a snapshot or not * * Only relevant for sparse-revlog case. * Callers must ensure that rev is in a valid range. */ static int index_issnapshotrev(indexObject *self, Py_ssize_t rev) { int ps[2]; Py_ssize_t base; while (rev >= 0) { base = (Py_ssize_t)index_baserev(self, rev); if (base == rev) { base = -1; } if (base == -2) { assert(PyErr_Occurred()); return -1; } if (base == -1) { return 1; } if (index_get_parents(self, rev, ps, (int)rev) < 0) { assert(PyErr_Occurred()); return -1; }; if (base == ps[0] || base == ps[1]) { return 0; } rev = base; } return rev == -1; } static PyObject *index_issnapshot(indexObject *self, PyObject *value) { long rev; int issnap; Py_ssize_t length = index_length(self); if (!pylong_to_long(value, &rev)) { return NULL; } if (rev < -1 || rev >= length) { PyErr_Format(PyExc_ValueError, "revlog index out of range: %ld", rev); return NULL; }; issnap = index_issnapshotrev(self, (Py_ssize_t)rev); if (issnap < 0) { return NULL; }; return PyBool_FromLong((long)issnap); } static PyObject *index_findsnapshots(indexObject *self, PyObject *args) { Py_ssize_t start_rev; PyObject *cache; Py_ssize_t base; Py_ssize_t rev; PyObject *key = NULL; PyObject *value = NULL; const Py_ssize_t length = index_length(self); if (!PyArg_ParseTuple(args, "O!n", &PyDict_Type, &cache, &start_rev)) { return NULL; } for (rev = start_rev; rev < length; rev++) { int issnap; PyObject *allvalues = NULL; issnap = index_issnapshotrev(self, rev); if (issnap < 0) { goto bail; } if (issnap == 0) { continue; } base = (Py_ssize_t)index_baserev(self, rev); if (base == rev) { base = -1; } if (base == -2) { assert(PyErr_Occurred()); goto bail; } key = PyInt_FromSsize_t(base); allvalues = PyDict_GetItem(cache, key); if (allvalues == NULL && PyErr_Occurred()) { goto bail; } if (allvalues == NULL) { int r; allvalues = PyList_New(0); if (!allvalues) { goto bail; } r = PyDict_SetItem(cache, key, allvalues); Py_DECREF(allvalues); if (r < 0) { goto bail; } } value = PyInt_FromSsize_t(rev); if (PyList_Append(allvalues, value)) { goto bail; } Py_CLEAR(key); Py_CLEAR(value); } Py_RETURN_NONE; bail: Py_XDECREF(key); Py_XDECREF(value); return NULL; } static PyObject *index_deltachain(indexObject *self, PyObject *args) { int rev, generaldelta; PyObject *stoparg; int stoprev, iterrev, baserev = -1; int stopped; PyObject *chain = NULL, *result = NULL; const Py_ssize_t length = index_length(self); if (!PyArg_ParseTuple(args, "iOi", &rev, &stoparg, &generaldelta)) { return NULL; } if (PyInt_Check(stoparg)) { stoprev = (int)PyInt_AsLong(stoparg); if (stoprev == -1 && PyErr_Occurred()) { return NULL; } } else if (stoparg == Py_None) { stoprev = -2; } else { PyErr_SetString(PyExc_ValueError, "stoprev must be integer or None"); return NULL; } if (rev < 0 || rev >= length) { PyErr_SetString(PyExc_ValueError, "revlog index out of range"); return NULL; } chain = PyList_New(0); if (chain == NULL) { return NULL; } baserev = index_baserev(self, rev); /* This should never happen. */ if (baserev <= -2) { /* Error should be set by index_deref() */ assert(PyErr_Occurred()); goto bail; } iterrev = rev; while (iterrev != baserev && iterrev != stoprev) { PyObject *value = PyInt_FromLong(iterrev); if (value == NULL) { goto bail; } if (PyList_Append(chain, value)) { Py_DECREF(value); goto bail; } Py_DECREF(value); if (generaldelta) { iterrev = baserev; } else { iterrev--; } if (iterrev < 0) { break; } if (iterrev >= length) { PyErr_SetString(PyExc_IndexError, "revision outside index"); return NULL; } baserev = index_baserev(self, iterrev); /* This should never happen. */ if (baserev <= -2) { /* Error should be set by index_deref() */ assert(PyErr_Occurred()); goto bail; } } if (iterrev == stoprev) { stopped = 1; } else { PyObject *value = PyInt_FromLong(iterrev); if (value == NULL) { goto bail; } if (PyList_Append(chain, value)) { Py_DECREF(value); goto bail; } Py_DECREF(value); stopped = 0; } if (PyList_Reverse(chain)) { goto bail; } result = Py_BuildValue("OO", chain, stopped ? Py_True : Py_False); Py_DECREF(chain); return result; bail: Py_DECREF(chain); return NULL; } static inline int64_t index_segment_span(indexObject *self, Py_ssize_t start_rev, Py_ssize_t end_rev) { int64_t start_offset; int64_t end_offset; int end_size; start_offset = index_get_start(self, start_rev); if (start_offset < 0) { return -1; } end_offset = index_get_start(self, end_rev); if (end_offset < 0) { return -1; } end_size = index_get_length(self, end_rev); if (end_size < 0) { return -1; } if (end_offset < start_offset) { PyErr_Format(PyExc_ValueError, "corrupted revlog index: inconsistent offset " "between revisions (%zd) and (%zd)", start_rev, end_rev); return -1; } return (end_offset - start_offset) + (int64_t)end_size; } /* returns endidx so that revs[startidx:endidx] has no empty trailing revs */ static Py_ssize_t trim_endidx(indexObject *self, const Py_ssize_t *revs, Py_ssize_t startidx, Py_ssize_t endidx) { int length; while (endidx > 1 && endidx > startidx) { length = index_get_length(self, revs[endidx - 1]); if (length < 0) { return -1; } if (length != 0) { break; } endidx -= 1; } return endidx; } struct Gap { int64_t size; Py_ssize_t idx; }; static int gap_compare(const void *left, const void *right) { const struct Gap *l_left = ((const struct Gap *)left); const struct Gap *l_right = ((const struct Gap *)right); if (l_left->size < l_right->size) { return -1; } else if (l_left->size > l_right->size) { return 1; } return 0; } static int Py_ssize_t_compare(const void *left, const void *right) { const Py_ssize_t l_left = *(const Py_ssize_t *)left; const Py_ssize_t l_right = *(const Py_ssize_t *)right; if (l_left < l_right) { return -1; } else if (l_left > l_right) { return 1; } return 0; } static PyObject *index_slicechunktodensity(indexObject *self, PyObject *args) { /* method arguments */ PyObject *list_revs = NULL; /* revisions in the chain */ double targetdensity = 0; /* min density to achieve */ Py_ssize_t mingapsize = 0; /* threshold to ignore gaps */ /* other core variables */ Py_ssize_t idxlen = index_length(self); Py_ssize_t i; /* used for various iteration */ PyObject *result = NULL; /* the final return of the function */ /* generic information about the delta chain being slice */ Py_ssize_t num_revs = 0; /* size of the full delta chain */ Py_ssize_t *revs = NULL; /* native array of revision in the chain */ int64_t chainpayload = 0; /* sum of all delta in the chain */ int64_t deltachainspan = 0; /* distance from first byte to last byte */ /* variable used for slicing the delta chain */ int64_t readdata = 0; /* amount of data currently planned to be read */ double density = 0; /* ration of payload data compared to read ones */ int64_t previous_end; struct Gap *gaps = NULL; /* array of notable gap in the chain */ Py_ssize_t num_gaps = 0; /* total number of notable gap recorded so far */ Py_ssize_t *selected_indices = NULL; /* indices of gap skipped over */ Py_ssize_t num_selected = 0; /* number of gaps skipped */ PyObject *chunk = NULL; /* individual slice */ PyObject *allchunks = NULL; /* all slices */ Py_ssize_t previdx; /* parsing argument */ if (!PyArg_ParseTuple(args, "O!dn", &PyList_Type, &list_revs, &targetdensity, &mingapsize)) { goto bail; } /* If the delta chain contains a single element, we do not need slicing */ num_revs = PyList_GET_SIZE(list_revs); if (num_revs <= 1) { result = PyTuple_Pack(1, list_revs); goto done; } /* Turn the python list into a native integer array (for efficiency) */ revs = (Py_ssize_t *)calloc(num_revs, sizeof(Py_ssize_t)); if (revs == NULL) { PyErr_NoMemory(); goto bail; } for (i = 0; i < num_revs; i++) { Py_ssize_t revnum = PyInt_AsLong(PyList_GET_ITEM(list_revs, i)); if (revnum == -1 && PyErr_Occurred()) { goto bail; } if (revnum < nullrev || revnum >= idxlen) { PyErr_Format(PyExc_IndexError, "index out of range: %zd", revnum); goto bail; } revs[i] = revnum; } /* Compute and check various property of the unsliced delta chain */ deltachainspan = index_segment_span(self, revs[0], revs[num_revs - 1]); if (deltachainspan < 0) { goto bail; } if (deltachainspan <= mingapsize) { result = PyTuple_Pack(1, list_revs); goto done; } chainpayload = 0; for (i = 0; i < num_revs; i++) { int tmp = index_get_length(self, revs[i]); if (tmp < 0) { goto bail; } chainpayload += tmp; } readdata = deltachainspan; density = 1.0; if (0 < deltachainspan) { density = (double)chainpayload / (double)deltachainspan; } if (density >= targetdensity) { result = PyTuple_Pack(1, list_revs); goto done; } /* if chain is too sparse, look for relevant gaps */ gaps = (struct Gap *)calloc(num_revs, sizeof(struct Gap)); if (gaps == NULL) { PyErr_NoMemory(); goto bail; } previous_end = -1; for (i = 0; i < num_revs; i++) { int64_t revstart; int revsize; revstart = index_get_start(self, revs[i]); if (revstart < 0) { goto bail; }; revsize = index_get_length(self, revs[i]); if (revsize < 0) { goto bail; }; if (revsize == 0) { continue; } if (previous_end >= 0) { int64_t gapsize = revstart - previous_end; if (gapsize > mingapsize) { gaps[num_gaps].size = gapsize; gaps[num_gaps].idx = i; num_gaps += 1; } } previous_end = revstart + revsize; } if (num_gaps == 0) { result = PyTuple_Pack(1, list_revs); goto done; } qsort(gaps, num_gaps, sizeof(struct Gap), &gap_compare); /* Slice the largest gap first, they improve the density the most */ selected_indices = (Py_ssize_t *)malloc((num_gaps + 1) * sizeof(Py_ssize_t)); if (selected_indices == NULL) { PyErr_NoMemory(); goto bail; } for (i = num_gaps - 1; i >= 0; i--) { selected_indices[num_selected] = gaps[i].idx; readdata -= gaps[i].size; num_selected += 1; if (readdata <= 0) { density = 1.0; } else { density = (double)chainpayload / (double)readdata; } if (density >= targetdensity) { break; } } qsort(selected_indices, num_selected, sizeof(Py_ssize_t), &Py_ssize_t_compare); /* create the resulting slice */ allchunks = PyList_New(0); if (allchunks == NULL) { goto bail; } previdx = 0; selected_indices[num_selected] = num_revs; for (i = 0; i <= num_selected; i++) { Py_ssize_t idx = selected_indices[i]; Py_ssize_t endidx = trim_endidx(self, revs, previdx, idx); if (endidx < 0) { goto bail; } if (previdx < endidx) { chunk = PyList_GetSlice(list_revs, previdx, endidx); if (chunk == NULL) { goto bail; } if (PyList_Append(allchunks, chunk) == -1) { goto bail; } Py_DECREF(chunk); chunk = NULL; } previdx = idx; } result = allchunks; goto done; bail: Py_XDECREF(allchunks); Py_XDECREF(chunk); done: free(revs); free(gaps); free(selected_indices); return result; } static inline int nt_level(const char *node, Py_ssize_t level) { int v = node[level >> 1]; if (!(level & 1)) v >>= 4; return v & 0xf; } /* * Return values: * * -4: match is ambiguous (multiple candidates) * -2: not found * rest: valid rev */ static int nt_find(nodetree *self, const char *node, Py_ssize_t nodelen, int hex) { int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level; int level, maxlevel, off; /* If the input is binary, do a fast check for the nullid first. */ if (!hex && nodelen == self->nodelen && node[0] == '\0' && node[1] == '\0' && memcmp(node, nullid, self->nodelen) == 0) return -1; if (hex) maxlevel = nodelen; else maxlevel = 2 * nodelen; if (maxlevel > 2 * self->nodelen) maxlevel = 2 * self->nodelen; for (level = off = 0; level < maxlevel; level++) { int k = getnybble(node, level); nodetreenode *n = &self->nodes[off]; int v = n->children[k]; if (v < 0) { const char *n; Py_ssize_t i; v = -(v + 2); n = index_node(self->index, v); if (n == NULL) return -2; for (i = level; i < maxlevel; i++) if (getnybble(node, i) != nt_level(n, i)) return -2; return v; } if (v == 0) return -2; off = v; } /* multiple matches against an ambiguous prefix */ return -4; } static int nt_new(nodetree *self) { if (self->length == self->capacity) { size_t newcapacity; nodetreenode *newnodes; newcapacity = self->capacity * 2; if (newcapacity >= SIZE_MAX / sizeof(nodetreenode)) { PyErr_SetString(PyExc_MemoryError, "overflow in nt_new"); return -1; } newnodes = realloc(self->nodes, newcapacity * sizeof(nodetreenode)); if (newnodes == NULL) { PyErr_SetString(PyExc_MemoryError, "out of memory"); return -1; } self->capacity = newcapacity; self->nodes = newnodes; memset(&self->nodes[self->length], 0, sizeof(nodetreenode) * (self->capacity - self->length)); } return self->length++; } static int nt_insert(nodetree *self, const char *node, int rev) { int level = 0; int off = 0; while (level < 2 * self->nodelen) { int k = nt_level(node, level); nodetreenode *n; int v; n = &self->nodes[off]; v = n->children[k]; if (v == 0) { n->children[k] = -rev - 2; return 0; } if (v < 0) { const char *oldnode = index_node_existing(self->index, -(v + 2)); int noff; if (oldnode == NULL) return -1; if (!memcmp(oldnode, node, self->nodelen)) { n->children[k] = -rev - 2; return 0; } noff = nt_new(self); if (noff == -1) return -1; /* self->nodes may have been changed by realloc */ self->nodes[off].children[k] = noff; off = noff; n = &self->nodes[off]; n->children[nt_level(oldnode, ++level)] = v; if (level > self->depth) self->depth = level; self->splits += 1; } else { level += 1; off = v; } } return -1; } static PyObject *ntobj_insert(nodetreeObject *self, PyObject *args) { Py_ssize_t rev; const char *node; Py_ssize_t length; if (!PyArg_ParseTuple(args, "n", &rev)) return NULL; length = index_length(self->nt.index); if (rev < 0 || rev >= length) { PyErr_SetString(PyExc_ValueError, "revlog index out of range"); return NULL; } node = index_node_existing(self->nt.index, rev); if (nt_insert(&self->nt, node, (int)rev) == -1) return NULL; Py_RETURN_NONE; } static int nt_delete_node(nodetree *self, const char *node) { /* rev==-2 happens to get encoded as 0, which is interpreted as not set */ return nt_insert(self, node, -2); } static int nt_init(nodetree *self, indexObject *index, unsigned capacity) { /* Initialize before overflow-checking to avoid nt_dealloc() crash. */ self->nodes = NULL; self->index = index; /* The input capacity is in terms of revisions, while the field is in * terms of nodetree nodes. */ self->capacity = (capacity < 4 ? 4 : capacity / 2); self->nodelen = index->nodelen; self->depth = 0; self->splits = 0; if (self->capacity > SIZE_MAX / sizeof(nodetreenode)) { PyErr_SetString(PyExc_ValueError, "overflow in init_nt"); return -1; } self->nodes = calloc(self->capacity, sizeof(nodetreenode)); if (self->nodes == NULL) { PyErr_NoMemory(); return -1; } self->length = 1; return 0; } static int ntobj_init(nodetreeObject *self, PyObject *args) { PyObject *index; unsigned capacity; if (!PyArg_ParseTuple(args, "O!I", &HgRevlogIndex_Type, &index, &capacity)) return -1; Py_INCREF(index); return nt_init(&self->nt, (indexObject *)index, capacity); } static int nt_partialmatch(nodetree *self, const char *node, Py_ssize_t nodelen) { return nt_find(self, node, nodelen, 1); } /* * Find the length of the shortest unique prefix of node. * * Return values: * * -3: error (exception set) * -2: not found (no exception set) * rest: length of shortest prefix */ static int nt_shortest(nodetree *self, const char *node) { int level, off; for (level = off = 0; level < 2 * self->nodelen; level++) { int k, v; nodetreenode *n = &self->nodes[off]; k = nt_level(node, level); v = n->children[k]; if (v < 0) { const char *n; v = -(v + 2); n = index_node_existing(self->index, v); if (n == NULL) return -3; if (memcmp(node, n, self->nodelen) != 0) /* * Found a unique prefix, but it wasn't for the * requested node (i.e the requested node does * not exist). */ return -2; return level + 1; } if (v == 0) return -2; off = v; } /* * The node was still not unique after 40 hex digits, so this won't * happen. Also, if we get here, then there's a programming error in * this file that made us insert a node longer than 40 hex digits. */ PyErr_SetString(PyExc_Exception, "broken node tree"); return -3; } static PyObject *ntobj_shortest(nodetreeObject *self, PyObject *args) { PyObject *val; char *node; int length; if (!PyArg_ParseTuple(args, "O", &val)) return NULL; if (node_check(self->nt.nodelen, val, &node) == -1) return NULL; length = nt_shortest(&self->nt, node); if (length == -3) return NULL; if (length == -2) { raise_revlog_error(); return NULL; } return PyInt_FromLong(length); } static void nt_dealloc(nodetree *self) { free(self->nodes); self->nodes = NULL; } static void ntobj_dealloc(nodetreeObject *self) { Py_XDECREF(self->nt.index); nt_dealloc(&self->nt); PyObject_Del(self); } static PyMethodDef ntobj_methods[] = { {"insert", (PyCFunction)ntobj_insert, METH_VARARGS, "insert an index entry"}, {"shortest", (PyCFunction)ntobj_shortest, METH_VARARGS, "find length of shortest hex nodeid of a binary ID"}, {NULL} /* Sentinel */ }; static PyTypeObject nodetreeType = { PyVarObject_HEAD_INIT(NULL, 0) /* header */ "parsers.nodetree", /* tp_name */ sizeof(nodetreeObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ntobj_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "nodetree", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ntobj_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)ntobj_init, /* tp_init */ 0, /* tp_alloc */ }; static int index_init_nt(indexObject *self) { if (!self->ntinitialized) { if (nt_init(&self->nt, self, (int)self->length) == -1) { nt_dealloc(&self->nt); return -1; } if (nt_insert(&self->nt, nullid, -1) == -1) { nt_dealloc(&self->nt); return -1; } self->ntinitialized = 1; self->ntrev = (int)index_length(self); self->ntlookups = 1; self->ntmisses = 0; } return 0; } /* * Return values: * * -3: error (exception set) * -2: not found (no exception set) * rest: valid rev */ static int index_find_node(indexObject *self, const char *node) { int rev; if (index_init_nt(self) == -1) return -3; self->ntlookups++; rev = nt_find(&self->nt, node, self->nodelen, 0); if (rev >= -1) return rev; /* * For the first handful of lookups, we scan the entire index, * and cache only the matching nodes. This optimizes for cases * like "hg tip", where only a few nodes are accessed. * * After that, we cache every node we visit, using a single * scan amortized over multiple lookups. This gives the best * bulk performance, e.g. for "hg log". */ if (self->ntmisses++ < 4) { for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node_existing(self, rev); if (n == NULL) return -3; if (memcmp(node, n, self->nodelen) == 0) { if (nt_insert(&self->nt, n, rev) == -1) return -3; break; } } } else { for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node_existing(self, rev); if (n == NULL) return -3; if (nt_insert(&self->nt, n, rev) == -1) { self->ntrev = rev + 1; return -3; } if (memcmp(node, n, self->nodelen) == 0) { break; } } self->ntrev = rev; } if (rev >= 0) return rev; return -2; } static PyObject *index_getitem(indexObject *self, PyObject *value) { char *node; int rev; if (PyInt_Check(value)) { long idx; if (!pylong_to_long(value, &idx)) { return NULL; } return index_get(self, idx); } if (node_check(self->nodelen, value, &node) == -1) return NULL; rev = index_find_node(self, node); if (rev >= -1) return PyInt_FromLong(rev); if (rev == -2) raise_revlog_error(); return NULL; } /* * Fully populate the radix tree. */ static int index_populate_nt(indexObject *self) { int rev; if (self->ntrev > 0) { for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node_existing(self, rev); if (n == NULL) return -1; if (nt_insert(&self->nt, n, rev) == -1) return -1; } self->ntrev = -1; } return 0; } static PyObject *index_partialmatch(indexObject *self, PyObject *args) { const char *fullnode; Py_ssize_t nodelen; char *node; int rev, i; if (!PyArg_ParseTuple(args, PY23("s#", "y#"), &node, &nodelen)) return NULL; if (nodelen < 1) { PyErr_SetString(PyExc_ValueError, "key too short"); return NULL; } if (nodelen > 2 * self->nodelen) { PyErr_SetString(PyExc_ValueError, "key too long"); return NULL; } for (i = 0; i < nodelen; i++) hexdigit(node, i); if (PyErr_Occurred()) { /* input contains non-hex characters */ PyErr_Clear(); Py_RETURN_NONE; } if (index_init_nt(self) == -1) return NULL; if (index_populate_nt(self) == -1) return NULL; rev = nt_partialmatch(&self->nt, node, nodelen); switch (rev) { case -4: raise_revlog_error(); return NULL; case -2: Py_RETURN_NONE; case -1: return PyBytes_FromStringAndSize(nullid, self->nodelen); } fullnode = index_node_existing(self, rev); if (fullnode == NULL) { return NULL; } return PyBytes_FromStringAndSize(fullnode, self->nodelen); } static PyObject *index_shortest(indexObject *self, PyObject *args) { PyObject *val; char *node; int length; if (!PyArg_ParseTuple(args, "O", &val)) return NULL; if (node_check(self->nodelen, val, &node) == -1) return NULL; self->ntlookups++; if (index_init_nt(self) == -1) return NULL; if (index_populate_nt(self) == -1) return NULL; length = nt_shortest(&self->nt, node); if (length == -3) return NULL; if (length == -2) { raise_revlog_error(); return NULL; } return PyInt_FromLong(length); } static PyObject *index_m_get(indexObject *self, PyObject *args) { PyObject *val; char *node; int rev; if (!PyArg_ParseTuple(args, "O", &val)) return NULL; if (node_check(self->nodelen, val, &node) == -1) return NULL; rev = index_find_node(self, node); if (rev == -3) return NULL; if (rev == -2) Py_RETURN_NONE; return PyInt_FromLong(rev); } static int index_contains(indexObject *self, PyObject *value) { char *node; if (PyInt_Check(value)) { long rev; if (!pylong_to_long(value, &rev)) { return -1; } return rev >= -1 && rev < index_length(self); } if (node_check(self->nodelen, value, &node) == -1) return -1; switch (index_find_node(self, node)) { case -3: return -1; case -2: return 0; default: return 1; } } static PyObject *index_m_has_node(indexObject *self, PyObject *args) { int ret = index_contains(self, args); if (ret < 0) return NULL; return PyBool_FromLong((long)ret); } static PyObject *index_m_rev(indexObject *self, PyObject *val) { char *node; int rev; if (node_check(self->nodelen, val, &node) == -1) return NULL; rev = index_find_node(self, node); if (rev >= -1) return PyInt_FromLong(rev); if (rev == -2) raise_revlog_error(); return NULL; } typedef uint64_t bitmask; /* * Given a disjoint set of revs, return all candidates for the * greatest common ancestor. In revset notation, this is the set * "heads(::a and ::b and ...)" */ static PyObject *find_gca_candidates(indexObject *self, const int *revs, int revcount) { const bitmask allseen = (1ull << revcount) - 1; const bitmask poison = 1ull << revcount; PyObject *gca = PyList_New(0); int i, v, interesting; int maxrev = -1; bitmask sp; bitmask *seen; if (gca == NULL) return PyErr_NoMemory(); for (i = 0; i < revcount; i++) { if (revs[i] > maxrev) maxrev = revs[i]; } seen = calloc(sizeof(*seen), maxrev + 1); if (seen == NULL) { Py_DECREF(gca); return PyErr_NoMemory(); } for (i = 0; i < revcount; i++) seen[revs[i]] = 1ull << i; interesting = revcount; for (v = maxrev; v >= 0 && interesting; v--) { bitmask sv = seen[v]; int parents[2]; if (!sv) continue; if (sv < poison) { interesting -= 1; if (sv == allseen) { PyObject *obj = PyInt_FromLong(v); if (obj == NULL) goto bail; if (PyList_Append(gca, obj) == -1) { Py_DECREF(obj); goto bail; } sv |= poison; for (i = 0; i < revcount; i++) { if (revs[i] == v) goto done; } } } if (index_get_parents(self, v, parents, maxrev) < 0) goto bail; for (i = 0; i < 2; i++) { int p = parents[i]; if (p == -1) continue; sp = seen[p]; if (sv < poison) { if (sp == 0) { seen[p] = sv; interesting++; } else if (sp != sv) seen[p] |= sv; } else { if (sp && sp < poison) interesting--; seen[p] = sv; } } } done: free(seen); return gca; bail: free(seen); Py_XDECREF(gca); return NULL; } /* * Given a disjoint set of revs, return the subset with the longest * path to the root. */ static PyObject *find_deepest(indexObject *self, PyObject *revs) { const Py_ssize_t revcount = PyList_GET_SIZE(revs); static const Py_ssize_t capacity = 24; int *depth, *interesting = NULL; int i, j, v, ninteresting; PyObject *dict = NULL, *keys = NULL; long *seen = NULL; int maxrev = -1; long final; if (revcount > capacity) { PyErr_Format(PyExc_OverflowError, "bitset size (%ld) > capacity (%ld)", (long)revcount, (long)capacity); return NULL; } for (i = 0; i < revcount; i++) { int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i)); if (n > maxrev) maxrev = n; } depth = calloc(sizeof(*depth), maxrev + 1); if (depth == NULL) return PyErr_NoMemory(); seen = calloc(sizeof(*seen), maxrev + 1); if (seen == NULL) { PyErr_NoMemory(); goto bail; } interesting = calloc(sizeof(*interesting), ((size_t)1) << revcount); if (interesting == NULL) { PyErr_NoMemory(); goto bail; } if (PyList_Sort(revs) == -1) goto bail; for (i = 0; i < revcount; i++) { int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i)); long b = 1l << i; depth[n] = 1; seen[n] = b; interesting[b] = 1; } /* invariant: ninteresting is the number of non-zero entries in * interesting. */ ninteresting = (int)revcount; for (v = maxrev; v >= 0 && ninteresting > 1; v--) { int dv = depth[v]; int parents[2]; long sv; if (dv == 0) continue; sv = seen[v]; if (index_get_parents(self, v, parents, maxrev) < 0) goto bail; for (i = 0; i < 2; i++) { int p = parents[i]; long sp; int dp; if (p == -1) continue; dp = depth[p]; sp = seen[p]; if (dp <= dv) { depth[p] = dv + 1; if (sp != sv) { interesting[sv] += 1; seen[p] = sv; if (sp) { interesting[sp] -= 1; if (interesting[sp] == 0) ninteresting -= 1; } } } else if (dv == dp - 1) { long nsp = sp | sv; if (nsp == sp) continue; seen[p] = nsp; interesting[sp] -= 1; if (interesting[sp] == 0) ninteresting -= 1; if (interesting[nsp] == 0) ninteresting += 1; interesting[nsp] += 1; } } interesting[sv] -= 1; if (interesting[sv] == 0) ninteresting -= 1; } final = 0; j = ninteresting; for (i = 0; i < (int)(2 << revcount) && j > 0; i++) { if (interesting[i] == 0) continue; final |= i; j -= 1; } if (final == 0) { keys = PyList_New(0); goto bail; } dict = PyDict_New(); if (dict == NULL) goto bail; for (i = 0; i < revcount; i++) { PyObject *key; if ((final & (1 << i)) == 0) continue; key = PyList_GET_ITEM(revs, i); Py_INCREF(key); Py_INCREF(Py_None); if (PyDict_SetItem(dict, key, Py_None) == -1) { Py_DECREF(key); Py_DECREF(Py_None); goto bail; } } keys = PyDict_Keys(dict); bail: free(depth); free(seen); free(interesting); Py_XDECREF(dict); return keys; } /* * Given a (possibly overlapping) set of revs, return all the * common ancestors heads: heads(::args[0] and ::a[1] and ...) */ static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args) { PyObject *ret = NULL; Py_ssize_t argcount, i, len; bitmask repeat = 0; int revcount = 0; int *revs; argcount = PySequence_Length(args); revs = PyMem_Malloc(argcount * sizeof(*revs)); if (argcount > 0 && revs == NULL) return PyErr_NoMemory(); len = index_length(self); for (i = 0; i < argcount; i++) { static const int capacity = 24; PyObject *obj = PySequence_GetItem(args, i); bitmask x; long val; if (!PyInt_Check(obj)) { PyErr_SetString(PyExc_TypeError, "arguments must all be ints"); Py_DECREF(obj); goto bail; } val = PyInt_AsLong(obj); Py_DECREF(obj); if (val == -1) { ret = PyList_New(0); goto done; } if (val < 0 || val >= len) { PyErr_SetString(PyExc_IndexError, "index out of range"); goto bail; } /* this cheesy bloom filter lets us avoid some more * expensive duplicate checks in the common set-is-disjoint * case */ x = 1ull << (val & 0x3f); if (repeat & x) { int k; for (k = 0; k < revcount; k++) { if (val == revs[k]) goto duplicate; } } else repeat |= x; if (revcount >= capacity) { PyErr_Format(PyExc_OverflowError, "bitset size (%d) > capacity (%d)", revcount, capacity); goto bail; } revs[revcount++] = (int)val; duplicate:; } if (revcount == 0) { ret = PyList_New(0); goto done; } if (revcount == 1) { PyObject *obj; ret = PyList_New(1); if (ret == NULL) goto bail; obj = PyInt_FromLong(revs[0]); if (obj == NULL) goto bail; PyList_SET_ITEM(ret, 0, obj); goto done; } ret = find_gca_candidates(self, revs, revcount); if (ret == NULL) goto bail; done: PyMem_Free(revs); return ret; bail: PyMem_Free(revs); Py_XDECREF(ret); return NULL; } /* * Given a (possibly overlapping) set of revs, return the greatest * common ancestors: those with the longest path to the root. */ static PyObject *index_ancestors(indexObject *self, PyObject *args) { PyObject *ret; PyObject *gca = index_commonancestorsheads(self, args); if (gca == NULL) return NULL; if (PyList_GET_SIZE(gca) <= 1) { return gca; } ret = find_deepest(self, gca); Py_DECREF(gca); return ret; } /* * Invalidate any trie entries introduced by added revs. */ static void index_invalidate_added(indexObject *self, Py_ssize_t start) { Py_ssize_t i, len; len = self->length + self->new_length; i = start - self->length; if (i < 0) return; for (i = start; i < len; i++) nt_delete_node(&self->nt, index_deref(self, i) + 32); self->new_length = start - self->length; } /* * Delete a numeric range of revs, which must be at the end of the * range. */ static int index_slice_del(indexObject *self, PyObject *item) { Py_ssize_t start, stop, step, slicelength; Py_ssize_t length = index_length(self) + 1; int ret = 0; /* Argument changed from PySliceObject* to PyObject* in Python 3. */ #ifdef IS_PY3K if (PySlice_GetIndicesEx(item, length, &start, &stop, &step, &slicelength) < 0) #else if (PySlice_GetIndicesEx((PySliceObject *)item, length, &start, &stop, &step, &slicelength) < 0) #endif return -1; if (slicelength <= 0) return 0; if ((step < 0 && start < stop) || (step > 0 && start > stop)) stop = start; if (step < 0) { stop = start + 1; start = stop + step * (slicelength - 1) - 1; step = -step; } if (step != 1) { PyErr_SetString(PyExc_ValueError, "revlog index delete requires step size of 1"); return -1; } if (stop != length - 1) { PyErr_SetString(PyExc_IndexError, "revlog index deletion indices are invalid"); return -1; } if (start < self->length) { if (self->ntinitialized) { Py_ssize_t i; for (i = start; i < self->length; i++) { const char *node = index_node_existing(self, i); if (node == NULL) return -1; nt_delete_node(&self->nt, node); } if (self->new_length) index_invalidate_added(self, self->length); if (self->ntrev > start) self->ntrev = (int)start; } else if (self->new_length) { self->new_length = 0; } self->length = start; goto done; } if (self->ntinitialized) { index_invalidate_added(self, start); if (self->ntrev > start) self->ntrev = (int)start; } else { self->new_length = start - self->length; } done: Py_CLEAR(self->headrevs); return ret; } /* * Supported ops: * * slice deletion * string assignment (extend node->rev mapping) * string deletion (shrink node->rev mapping) */ static int index_assign_subscript(indexObject *self, PyObject *item, PyObject *value) { char *node; long rev; if (PySlice_Check(item) && value == NULL) return index_slice_del(self, item); if (node_check(self->nodelen, item, &node) == -1) return -1; if (value == NULL) return self->ntinitialized ? nt_delete_node(&self->nt, node) : 0; rev = PyInt_AsLong(value); if (rev > INT_MAX || rev < 0) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "rev out of range"); return -1; } if (index_init_nt(self) == -1) return -1; return nt_insert(&self->nt, node, (int)rev); } /* * Find all RevlogNG entries in an index that has inline data. Update * the optional "offsets" table with those entries. */ static Py_ssize_t inline_scan(indexObject *self, const char **offsets) { const char *data = (const char *)self->buf.buf; Py_ssize_t pos = 0; Py_ssize_t end = self->buf.len; long incr = self->hdrsize; Py_ssize_t len = 0; while (pos + self->hdrsize <= end && pos >= 0) { uint32_t comp_len, sidedata_comp_len = 0; /* 3rd element of header is length of compressed inline data */ comp_len = getbe32(data + pos + 8); if (self->hdrsize == v2_hdrsize) { sidedata_comp_len = getbe32(data + pos + 72); } incr = self->hdrsize + comp_len + sidedata_comp_len; if (offsets) offsets[len] = data + pos; len++; pos += incr; } if (pos != end) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "corrupt index file"); return -1; } return len; } static int index_init(indexObject *self, PyObject *args, PyObject *kwargs) { PyObject *data_obj, *inlined_obj, *revlogv2; Py_ssize_t size; static char *kwlist[] = {"data", "inlined", "revlogv2", NULL}; /* Initialize before argument-checking to avoid index_dealloc() crash. */ self->added = NULL; self->new_length = 0; self->added_length = 0; self->data = NULL; memset(&self->buf, 0, sizeof(self->buf)); self->headrevs = NULL; self->filteredrevs = Py_None; Py_INCREF(Py_None); self->ntinitialized = 0; self->offsets = NULL; self->nodelen = 20; self->nullentry = NULL; revlogv2 = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|O", kwlist, &data_obj, &inlined_obj, &revlogv2)) return -1; if (!PyObject_CheckBuffer(data_obj)) { PyErr_SetString(PyExc_TypeError, "data does not support buffer interface"); return -1; } if (self->nodelen < 20 || self->nodelen > (Py_ssize_t)sizeof(nullid)) { PyErr_SetString(PyExc_RuntimeError, "unsupported node size"); return -1; } if (revlogv2 && PyObject_IsTrue(revlogv2)) { self->hdrsize = v2_hdrsize; } else { self->hdrsize = v1_hdrsize; } if (self->hdrsize == v1_hdrsize) { self->nullentry = Py_BuildValue(PY23("iiiiiiis#", "iiiiiiiy#"), 0, 0, 0, -1, -1, -1, -1, nullid, self->nodelen); } else { self->nullentry = Py_BuildValue(PY23("iiiiiiis#ii", "iiiiiiiy#ii"), 0, 0, 0, -1, -1, -1, -1, nullid, self->nodelen, 0, 0); } if (!self->nullentry) return -1; PyObject_GC_UnTrack(self->nullentry); if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1) return -1; size = self->buf.len; self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj); self->data = data_obj; self->ntlookups = self->ntmisses = 0; self->ntrev = -1; Py_INCREF(self->data); if (self->inlined) { Py_ssize_t len = inline_scan(self, NULL); if (len == -1) goto bail; self->length = len; } else { if (size % self->hdrsize) { PyErr_SetString(PyExc_ValueError, "corrupt index file"); goto bail; } self->length = size / self->hdrsize; } return 0; bail: return -1; } static PyObject *index_nodemap(indexObject *self) { Py_INCREF(self); return (PyObject *)self; } static void _index_clearcaches(indexObject *self) { if (self->offsets) { PyMem_Free((void *)self->offsets); self->offsets = NULL; } if (self->ntinitialized) { nt_dealloc(&self->nt); } self->ntinitialized = 0; Py_CLEAR(self->headrevs); } static PyObject *index_clearcaches(indexObject *self) { _index_clearcaches(self); self->ntrev = -1; self->ntlookups = self->ntmisses = 0; Py_RETURN_NONE; } static void index_dealloc(indexObject *self) { _index_clearcaches(self); Py_XDECREF(self->filteredrevs); if (self->buf.buf) { PyBuffer_Release(&self->buf); memset(&self->buf, 0, sizeof(self->buf)); } Py_XDECREF(self->data); PyMem_Free(self->added); Py_XDECREF(self->nullentry); PyObject_Del(self); } static PySequenceMethods index_sequence_methods = { (lenfunc)index_length, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (ssizeargfunc)index_get, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)index_contains, /* sq_contains */ }; static PyMappingMethods index_mapping_methods = { (lenfunc)index_length, /* mp_length */ (binaryfunc)index_getitem, /* mp_subscript */ (objobjargproc)index_assign_subscript, /* mp_ass_subscript */ }; static PyMethodDef index_methods[] = { {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS, "return the gca set of the given revs"}, {"commonancestorsheads", (PyCFunction)index_commonancestorsheads, METH_VARARGS, "return the heads of the common ancestors of the given revs"}, {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS, "clear the index caches"}, {"get", (PyCFunction)index_m_get, METH_VARARGS, "get an index entry"}, {"get_rev", (PyCFunction)index_m_get, METH_VARARGS, "return `rev` associated with a node or None"}, {"has_node", (PyCFunction)index_m_has_node, METH_O, "return True if the node exist in the index"}, {"rev", (PyCFunction)index_m_rev, METH_O, "return `rev` associated with a node or raise RevlogError"}, {"computephasesmapsets", (PyCFunction)compute_phases_map_sets, METH_VARARGS, "compute phases"}, {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS, "reachableroots"}, {"replace_sidedata_info", (PyCFunction)index_replace_sidedata_info, METH_VARARGS, "replace an existing index entry with a new value"}, {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS, "get head revisions"}, /* Can do filtering since 3.2 */ {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS, "get filtered head revisions"}, /* Can always do filtering */ {"issnapshot", (PyCFunction)index_issnapshot, METH_O, "True if the object is a snapshot"}, {"findsnapshots", (PyCFunction)index_findsnapshots, METH_VARARGS, "Gather snapshot data in a cache dict"}, {"deltachain", (PyCFunction)index_deltachain, METH_VARARGS, "determine revisions with deltas to reconstruct fulltext"}, {"slicechunktodensity", (PyCFunction)index_slicechunktodensity, METH_VARARGS, "determine revisions with deltas to reconstruct fulltext"}, {"append", (PyCFunction)index_append, METH_O, "append an index entry"}, {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS, "match a potentially ambiguous node ID"}, {"shortest", (PyCFunction)index_shortest, METH_VARARGS, "find length of shortest hex nodeid of a binary ID"}, {"stats", (PyCFunction)index_stats, METH_NOARGS, "stats for the index"}, + {"entry_binary", (PyCFunction)index_entry_binary, METH_VARARGS, + "return an entry in binary form"}, {NULL} /* Sentinel */ }; static PyGetSetDef index_getset[] = { {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL}, {NULL} /* Sentinel */ }; static PyMemberDef index_members[] = { {"entry_size", T_LONG, offsetof(indexObject, hdrsize), 0, "size of an index entry"}, {NULL} /* Sentinel */ }; PyTypeObject HgRevlogIndex_Type = { PyVarObject_HEAD_INIT(NULL, 0) /* header */ "parsers.index", /* tp_name */ sizeof(indexObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)index_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ &index_sequence_methods, /* tp_as_sequence */ &index_mapping_methods, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "revlog index", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ index_methods, /* tp_methods */ index_members, /* tp_members */ index_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)index_init, /* tp_init */ 0, /* tp_alloc */ }; /* * returns a tuple of the form (index, cache) with elements as * follows: * * index: an index object that lazily parses Revlog (v1 or v2) records * cache: if data is inlined, a tuple (0, index_file_content), else None * index_file_content could be a string, or a buffer * * added complications are for backwards compatibility */ PyObject *parse_index2(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *cache = NULL; indexObject *idx; int ret; idx = PyObject_New(indexObject, &HgRevlogIndex_Type); if (idx == NULL) goto bail; ret = index_init(idx, args, kwargs); if (ret == -1) goto bail; if (idx->inlined) { cache = Py_BuildValue("iO", 0, idx->data); if (cache == NULL) goto bail; } else { cache = Py_None; Py_INCREF(cache); } return Py_BuildValue("NN", idx, cache); bail: Py_XDECREF(idx); Py_XDECREF(cache); return NULL; } static Revlog_CAPI CAPI = { /* increment the abi_version field upon each change in the Revlog_CAPI struct or in the ABI of the listed functions */ 2, index_length, index_node, HgRevlogIndex_GetParents, }; void revlog_module_init(PyObject *mod) { PyObject *caps = NULL; HgRevlogIndex_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&HgRevlogIndex_Type) < 0) return; Py_INCREF(&HgRevlogIndex_Type); PyModule_AddObject(mod, "index", (PyObject *)&HgRevlogIndex_Type); nodetreeType.tp_new = PyType_GenericNew; if (PyType_Ready(&nodetreeType) < 0) return; Py_INCREF(&nodetreeType); PyModule_AddObject(mod, "nodetree", (PyObject *)&nodetreeType); caps = PyCapsule_New(&CAPI, "mercurial.cext.parsers.revlog_CAPI", NULL); if (caps != NULL) PyModule_AddObject(mod, "revlog_CAPI", caps); } diff --git a/mercurial/pure/parsers.py b/mercurial/pure/parsers.py --- a/mercurial/pure/parsers.py +++ b/mercurial/pure/parsers.py @@ -1,356 +1,380 @@ # parsers.py - Python implementation of parsers.c # # Copyright 2009 Olivia Mackall and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import import struct import zlib from ..node import ( nullrev, sha1nodeconstants, ) from .. import ( pycompat, util, ) from ..revlogutils import nodemap as nodemaputil from ..revlogutils import constants as revlog_constants stringio = pycompat.bytesio _pack = struct.pack _unpack = struct.unpack _compress = zlib.compress _decompress = zlib.decompress # Some code below makes tuples directly because it's more convenient. However, # code outside this module should always use dirstatetuple. def dirstatetuple(*x): # x is a tuple return x def gettype(q): return int(q & 0xFFFF) def offset_type(offset, type): return int(int(offset) << 16 | type) class BaseIndexObject(object): # Format of an index entry according to Python's `struct` language index_format = revlog_constants.INDEX_ENTRY_V1 # Size of a C unsigned long long int, platform independent big_int_size = struct.calcsize(b'>Q') # Size of a C long int, platform independent int_size = struct.calcsize(b'>i') # An empty index entry, used as a default value to be overridden, or nullrev null_item = (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid) @util.propertycache def entry_size(self): return self.index_format.size @property def nodemap(self): msg = b"index.nodemap is deprecated, use index.[has_node|rev|get_rev]" util.nouideprecwarn(msg, b'5.3', stacklevel=2) return self._nodemap @util.propertycache def _nodemap(self): nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) for r in range(0, len(self)): n = self[r][7] nodemap[n] = r return nodemap def has_node(self, node): """return True if the node exist in the index""" return node in self._nodemap def rev(self, node): """return a revision for a node If the node is unknown, raise a RevlogError""" return self._nodemap[node] def get_rev(self, node): """return a revision for a node If the node is unknown, return None""" return self._nodemap.get(node) def _stripnodes(self, start): if '_nodemap' in vars(self): for r in range(start, len(self)): n = self[r][7] del self._nodemap[n] def clearcaches(self): self.__dict__.pop('_nodemap', None) def __len__(self): return self._lgt + len(self._extra) def append(self, tup): if '_nodemap' in vars(self): self._nodemap[tup[7]] = len(self) data = self.index_format.pack(*tup) self._extra.append(data) def _check_index(self, i): if not isinstance(i, int): raise TypeError(b"expecting int indexes") if i < 0 or i >= len(self): raise IndexError def __getitem__(self, i): if i == -1: return self.null_item self._check_index(i) if i >= self._lgt: data = self._extra[i - self._lgt] else: index = self._calculate_index(i) data = self._data[index : index + self.entry_size] r = self.index_format.unpack(data) if self._lgt and i == 0: r = (offset_type(0, gettype(r[0])),) + r[1:] return r + def entry_binary(self, rev, header): + """return the raw binary string representing a revision""" + entry = self[rev] + p = revlog_constants.INDEX_ENTRY_V1.pack(*entry) + if rev == 0: + v_fmt = revlog_constants.INDEX_HEADER + v_bin = v_fmt.pack(header) + p = v_bin + p[v_fmt.size :] + return p + class IndexObject(BaseIndexObject): def __init__(self, data): - assert len(data) % self.entry_size == 0 + assert len(data) % self.entry_size == 0, ( + len(data), + self.entry_size, + len(data) % self.entry_size, + ) self._data = data self._lgt = len(data) // self.entry_size self._extra = [] def _calculate_index(self, i): return i * self.entry_size def __delitem__(self, i): if not isinstance(i, slice) or not i.stop == -1 or i.step is not None: raise ValueError(b"deleting slices only supports a:-1 with step 1") i = i.start self._check_index(i) self._stripnodes(i) if i < self._lgt: self._data = self._data[: i * self.entry_size] self._lgt = i self._extra = [] else: self._extra = self._extra[: i - self._lgt] class PersistentNodeMapIndexObject(IndexObject): """a Debug oriented class to test persistent nodemap We need a simple python object to test API and higher level behavior. See the Rust implementation for more serious usage. This should be used only through the dedicated `devel.persistent-nodemap` config. """ def nodemap_data_all(self): """Return bytes containing a full serialization of a nodemap The nodemap should be valid for the full set of revisions in the index.""" return nodemaputil.persistent_data(self) def nodemap_data_incremental(self): """Return bytes containing a incremental update to persistent nodemap This containst the data for an append-only update of the data provided in the last call to `update_nodemap_data`. """ if self._nm_root is None: return None docket = self._nm_docket changed, data = nodemaputil.update_persistent_data( self, self._nm_root, self._nm_max_idx, self._nm_docket.tip_rev ) self._nm_root = self._nm_max_idx = self._nm_docket = None return docket, changed, data def update_nodemap_data(self, docket, nm_data): """provide full block of persisted binary data for a nodemap The data are expected to come from disk. See `nodemap_data_all` for a produceur of such data.""" if nm_data is not None: self._nm_root, self._nm_max_idx = nodemaputil.parse_data(nm_data) if self._nm_root: self._nm_docket = docket else: self._nm_root = self._nm_max_idx = self._nm_docket = None class InlinedIndexObject(BaseIndexObject): def __init__(self, data, inline=0): self._data = data self._lgt = self._inline_scan(None) self._inline_scan(self._lgt) self._extra = [] def _inline_scan(self, lgt): off = 0 if lgt is not None: self._offsets = [0] * lgt count = 0 while off <= len(self._data) - self.entry_size: start = off + self.big_int_size (s,) = struct.unpack( b'>i', self._data[start : start + self.int_size], ) if lgt is not None: self._offsets[count] = off count += 1 off += self.entry_size + s if off != len(self._data): raise ValueError(b"corrupted data") return count def __delitem__(self, i): if not isinstance(i, slice) or not i.stop == -1 or i.step is not None: raise ValueError(b"deleting slices only supports a:-1 with step 1") i = i.start self._check_index(i) self._stripnodes(i) if i < self._lgt: self._offsets = self._offsets[:i] self._lgt = i self._extra = [] else: self._extra = self._extra[: i - self._lgt] def _calculate_index(self, i): return self._offsets[i] def parse_index2(data, inline, revlogv2=False): if not inline: cls = IndexObject2 if revlogv2 else IndexObject return cls(data), None cls = InlinedIndexObject2 if revlogv2 else InlinedIndexObject return cls(data, inline), (0, data) class Index2Mixin(object): index_format = revlog_constants.INDEX_ENTRY_V2 null_item = (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid, 0, 0) def replace_sidedata_info(self, i, sidedata_offset, sidedata_length): """ Replace an existing index entry's sidedata offset and length with new ones. This cannot be used outside of the context of sidedata rewriting, inside the transaction that creates the revision `i`. """ if i < 0: raise KeyError self._check_index(i) sidedata_format = b">Qi" packed_size = struct.calcsize(sidedata_format) if i >= self._lgt: packed = _pack(sidedata_format, sidedata_offset, sidedata_length) old = self._extra[i - self._lgt] new = old[:64] + packed + old[64 + packed_size :] self._extra[i - self._lgt] = new else: msg = b"cannot rewrite entries outside of this transaction" raise KeyError(msg) + def entry_binary(self, rev, header): + """return the raw binary string representing a revision""" + entry = self[rev] + p = revlog_constants.INDEX_ENTRY_V2.pack(*entry) + if rev == 0: + v_fmt = revlog_constants.INDEX_HEADER + v_bin = v_fmt.pack(header) + p = v_bin + p[v_fmt.size :] + return p + class IndexObject2(Index2Mixin, IndexObject): pass class InlinedIndexObject2(Index2Mixin, InlinedIndexObject): def _inline_scan(self, lgt): sidedata_length_pos = 72 off = 0 if lgt is not None: self._offsets = [0] * lgt count = 0 while off <= len(self._data) - self.entry_size: start = off + self.big_int_size (data_size,) = struct.unpack( b'>i', self._data[start : start + self.int_size], ) start = off + sidedata_length_pos (side_data_size,) = struct.unpack( b'>i', self._data[start : start + self.int_size] ) if lgt is not None: self._offsets[count] = off count += 1 off += self.entry_size + data_size + side_data_size if off != len(self._data): raise ValueError(b"corrupted data") return count def parse_index_devel_nodemap(data, inline): """like parse_index2, but alway return a PersistentNodeMapIndexObject""" return PersistentNodeMapIndexObject(data), None def parse_dirstate(dmap, copymap, st): parents = [st[:20], st[20:40]] # dereference fields so they will be local in loop format = b">cllll" e_size = struct.calcsize(format) pos1 = 40 l = len(st) # the inner loop while pos1 < l: pos2 = pos1 + e_size e = _unpack(b">cllll", st[pos1:pos2]) # a literal here is faster pos1 = pos2 + e[4] f = st[pos2:pos1] if b'\0' in f: f, c = f.split(b'\0') copymap[f] = c dmap[f] = e[:4] return parents def pack_dirstate(dmap, copymap, pl, now): now = int(now) cs = stringio() write = cs.write write(b"".join(pl)) for f, e in pycompat.iteritems(dmap): if e[0] == b'n' and e[3] == now: # The file was last modified "simultaneously" with the current # write to dirstate (i.e. within the same second for file- # systems with a granularity of 1 sec). This commonly happens # for at least a couple of files on 'update'. # The user could change the file without changing its size # within the same second. Invalidate the file's mtime in # dirstate, forcing future 'status' calls to compare the # contents of the file if the size is the same. This prevents # mistakenly treating such files as clean. e = dirstatetuple(e[0], e[1], e[2], -1) dmap[f] = e if f in copymap: f = b"%s\0%s" % (f, copymap[f]) e = _pack(b">cllll", e[0], e[1], e[2], e[3], len(f)) write(e) write(f) return cs.getvalue() diff --git a/mercurial/revlog.py b/mercurial/revlog.py --- a/mercurial/revlog.py +++ b/mercurial/revlog.py @@ -1,3247 +1,3230 @@ # revlog.py - storage back-end for mercurial # # Copyright 2005-2007 Olivia Mackall # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. """Storage back-end for Mercurial. This provides efficient delta storage with O(1) retrieve and append and O(changes) merge between branches. """ from __future__ import absolute_import import binascii import collections import contextlib import errno import io import os import struct import zlib # import stuff from node for others to import from revlog from .node import ( bin, hex, nullrev, sha1nodeconstants, short, wdirrev, ) from .i18n import _ from .pycompat import getattr from .revlogutils.constants import ( FLAG_GENERALDELTA, FLAG_INLINE_DATA, INDEX_ENTRY_V0, INDEX_ENTRY_V1, INDEX_ENTRY_V2, INDEX_HEADER, REVLOGV0, REVLOGV1, REVLOGV1_FLAGS, REVLOGV2, REVLOGV2_FLAGS, REVLOG_DEFAULT_FLAGS, REVLOG_DEFAULT_FORMAT, REVLOG_DEFAULT_VERSION, ) from .revlogutils.flagutil import ( REVIDX_DEFAULT_FLAGS, REVIDX_ELLIPSIS, REVIDX_EXTSTORED, REVIDX_FLAGS_ORDER, REVIDX_HASCOPIESINFO, REVIDX_ISCENSORED, REVIDX_RAWTEXT_CHANGING_FLAGS, REVIDX_SIDEDATA, ) from .thirdparty import attr from . import ( ancestor, dagop, error, mdiff, policy, pycompat, templatefilters, util, ) from .interfaces import ( repository, util as interfaceutil, ) from .revlogutils import ( deltas as deltautil, flagutil, nodemap as nodemaputil, sidedata as sidedatautil, ) from .utils import ( storageutil, stringutil, ) # blanked usage of all the name to prevent pyflakes constraints # We need these name available in the module for extensions. REVLOGV0 REVLOGV1 REVLOGV2 FLAG_INLINE_DATA FLAG_GENERALDELTA REVLOG_DEFAULT_FLAGS REVLOG_DEFAULT_FORMAT REVLOG_DEFAULT_VERSION REVLOGV1_FLAGS REVLOGV2_FLAGS REVIDX_ISCENSORED REVIDX_ELLIPSIS REVIDX_SIDEDATA REVIDX_HASCOPIESINFO REVIDX_EXTSTORED REVIDX_DEFAULT_FLAGS REVIDX_FLAGS_ORDER REVIDX_RAWTEXT_CHANGING_FLAGS parsers = policy.importmod('parsers') rustancestor = policy.importrust('ancestor') rustdagop = policy.importrust('dagop') rustrevlog = policy.importrust('revlog') # Aliased for performance. _zlibdecompress = zlib.decompress # max size of revlog with inline data _maxinline = 131072 _chunksize = 1048576 # Flag processors for REVIDX_ELLIPSIS. def ellipsisreadprocessor(rl, text): return text, False def ellipsiswriteprocessor(rl, text): return text, False def ellipsisrawprocessor(rl, text): return False ellipsisprocessor = ( ellipsisreadprocessor, ellipsiswriteprocessor, ellipsisrawprocessor, ) def getoffset(q): return int(q >> 16) def gettype(q): return int(q & 0xFFFF) def offset_type(offset, type): if (type & ~flagutil.REVIDX_KNOWN_FLAGS) != 0: raise ValueError(b'unknown revlog index flags') return int(int(offset) << 16 | type) def _verify_revision(rl, skipflags, state, node): """Verify the integrity of the given revlog ``node`` while providing a hook point for extensions to influence the operation.""" if skipflags: state[b'skipread'].add(node) else: # Side-effect: read content and verify hash. rl.revision(node) # True if a fast implementation for persistent-nodemap is available # # We also consider we have a "fast" implementation in "pure" python because # people using pure don't really have performance consideration (and a # wheelbarrow of other slowness source) HAS_FAST_PERSISTENT_NODEMAP = rustrevlog is not None or util.safehasattr( parsers, 'BaseIndexObject' ) @attr.s(slots=True, frozen=True) class _revisioninfo(object): """Information about a revision that allows building its fulltext node: expected hash of the revision p1, p2: parent revs of the revision btext: built text cache consisting of a one-element list cachedelta: (baserev, uncompressed_delta) or None flags: flags associated to the revision storage One of btext[0] or cachedelta must be set. """ node = attr.ib() p1 = attr.ib() p2 = attr.ib() btext = attr.ib() textlen = attr.ib() cachedelta = attr.ib() flags = attr.ib() @interfaceutil.implementer(repository.irevisiondelta) @attr.s(slots=True) class revlogrevisiondelta(object): node = attr.ib() p1node = attr.ib() p2node = attr.ib() basenode = attr.ib() flags = attr.ib() baserevisionsize = attr.ib() revision = attr.ib() delta = attr.ib() sidedata = attr.ib() linknode = attr.ib(default=None) @interfaceutil.implementer(repository.iverifyproblem) @attr.s(frozen=True) class revlogproblem(object): warning = attr.ib(default=None) error = attr.ib(default=None) node = attr.ib(default=None) class revlogoldindex(list): entry_size = INDEX_ENTRY_V0.size @property def nodemap(self): msg = b"index.nodemap is deprecated, use index.[has_node|rev|get_rev]" util.nouideprecwarn(msg, b'5.3', stacklevel=2) return self._nodemap @util.propertycache def _nodemap(self): nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) for r in range(0, len(self)): n = self[r][7] nodemap[n] = r return nodemap def has_node(self, node): """return True if the node exist in the index""" return node in self._nodemap def rev(self, node): """return a revision for a node If the node is unknown, raise a RevlogError""" return self._nodemap[node] def get_rev(self, node): """return a revision for a node If the node is unknown, return None""" return self._nodemap.get(node) def append(self, tup): self._nodemap[tup[7]] = len(self) super(revlogoldindex, self).append(tup) def __delitem__(self, i): if not isinstance(i, slice) or not i.stop == -1 or i.step is not None: raise ValueError(b"deleting slices only supports a:-1 with step 1") for r in pycompat.xrange(i.start, len(self)): del self._nodemap[self[r][7]] super(revlogoldindex, self).__delitem__(i) def clearcaches(self): self.__dict__.pop('_nodemap', None) def __getitem__(self, i): if i == -1: return (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid) return list.__getitem__(self, i) + def entry_binary(self, rev, header): + """return the raw binary string representing a revision""" + entry = self[rev] + if gettype(entry[0]): + raise error.RevlogError( + _(b'index entry flags need revlog version 1') + ) + e2 = ( + getoffset(entry[0]), + entry[1], + entry[3], + entry[4], + self[entry[5]][7], + self[entry[6]][7], + entry[7], + ) + return INDEX_ENTRY_V0.pack(*e2) + class revlogoldio(object): def parseindex(self, data, inline): s = INDEX_ENTRY_V0.size index = [] nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) n = off = 0 l = len(data) while off + s <= l: cur = data[off : off + s] off += s e = INDEX_ENTRY_V0.unpack(cur) # transform to revlogv1 format e2 = ( offset_type(e[0], 0), e[1], -1, e[2], e[3], nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6], ) index.append(e2) nodemap[e[6]] = n n += 1 index = revlogoldindex(index) return index, None - def packentry(self, entry, node, version, rev): - """return the binary representation of an entry - - entry: a tuple containing all the values (see index.__getitem__) - node: a callback to convert a revision to nodeid - version: the changelog version - rev: the revision number - """ - if gettype(entry[0]): - raise error.RevlogError( - _(b'index entry flags need revlog version 1') - ) - e2 = ( - getoffset(entry[0]), - entry[1], - entry[3], - entry[4], - node(entry[5]), - node(entry[6]), - entry[7], - ) - return INDEX_ENTRY_V0.pack(*e2) - # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte # signed integer) _maxentrysize = 0x7FFFFFFF class revlogio(object): def parseindex(self, data, inline): # call the C implementation to parse the index data index, cache = parsers.parse_index2(data, inline) return index, cache - def packentry(self, entry, node, version, rev): - p = INDEX_ENTRY_V1.pack(*entry) - if rev == 0: - p = INDEX_HEADER.pack(version) + p[4:] - return p - class revlogv2io(object): def parseindex(self, data, inline): index, cache = parsers.parse_index2(data, inline, revlogv2=True) return index, cache - def packentry(self, entry, node, version, rev): - p = INDEX_ENTRY_V2.pack(*entry) - if rev == 0: - p = INDEX_HEADER.pack(version) + p[4:] - return p - NodemapRevlogIO = None if util.safehasattr(parsers, 'parse_index_devel_nodemap'): class NodemapRevlogIO(revlogio): """A debug oriented IO class that return a PersistentNodeMapIndexObject The PersistentNodeMapIndexObject object is meant to test the persistent nodemap feature. """ def parseindex(self, data, inline): index, cache = parsers.parse_index_devel_nodemap(data, inline) return index, cache class rustrevlogio(revlogio): def parseindex(self, data, inline): index, cache = super(rustrevlogio, self).parseindex(data, inline) return rustrevlog.MixedIndex(index), cache class revlog(object): """ the underlying revision storage object A revlog consists of two parts, an index and the revision data. The index is a file with a fixed record size containing information on each revision, including its nodeid (hash), the nodeids of its parents, the position and offset of its data within the data file, and the revision it's based on. Finally, each entry contains a linkrev entry that can serve as a pointer to external data. The revision data itself is a linear collection of data chunks. Each chunk represents a revision and is usually represented as a delta against the previous chunk. To bound lookup time, runs of deltas are limited to about 2 times the length of the original version data. This makes retrieval of a version proportional to its size, or O(1) relative to the number of revisions. Both pieces of the revlog are written to in an append-only fashion, which means we never need to rewrite a file to insert or remove data, and can use some simple techniques to avoid the need for locking while reading. If checkambig, indexfile is opened with checkambig=True at writing, to avoid file stat ambiguity. If mmaplargeindex is True, and an mmapindexthreshold is set, the index will be mmapped rather than read if it is larger than the configured threshold. If censorable is True, the revlog can have censored revisions. If `upperboundcomp` is not None, this is the expected maximal gain from compression for the data content. `concurrencychecker` is an optional function that receives 3 arguments: a file handle, a filename, and an expected position. It should check whether the current position in the file handle is valid, and log/warn/fail (by raising). """ _flagserrorclass = error.RevlogError def __init__( self, opener, indexfile, datafile=None, checkambig=False, mmaplargeindex=False, censorable=False, upperboundcomp=None, persistentnodemap=False, concurrencychecker=None, ): """ create a revlog object opener is a function that abstracts the file opening operation and can be used to implement COW semantics or the like. """ self.upperboundcomp = upperboundcomp self.indexfile = indexfile self.datafile = datafile or (indexfile[:-2] + b".d") self.nodemap_file = None if persistentnodemap: self.nodemap_file = nodemaputil.get_nodemap_file( opener, self.indexfile ) self.opener = opener # When True, indexfile is opened with checkambig=True at writing, to # avoid file stat ambiguity. self._checkambig = checkambig self._mmaplargeindex = mmaplargeindex self._censorable = censorable # 3-tuple of (node, rev, text) for a raw revision. self._revisioncache = None # Maps rev to chain base rev. self._chainbasecache = util.lrucachedict(100) # 2-tuple of (offset, data) of raw data from the revlog at an offset. self._chunkcache = (0, b'') # How much data to read and cache into the raw revlog data cache. self._chunkcachesize = 65536 self._maxchainlen = None self._deltabothparents = True self.index = None self._nodemap_docket = None # Mapping of partial identifiers to full nodes. self._pcache = {} # Mapping of revision integer to full node. self._compengine = b'zlib' self._compengineopts = {} self._maxdeltachainspan = -1 self._withsparseread = False self._sparserevlog = False self._srdensitythreshold = 0.50 self._srmingapsize = 262144 # Make copy of flag processors so each revlog instance can support # custom flags. self._flagprocessors = dict(flagutil.flagprocessors) # 2-tuple of file handles being used for active writing. self._writinghandles = None self._loadindex() self._concurrencychecker = concurrencychecker def _loadindex(self): mmapindexthreshold = None opts = self.opener.options if b'revlogv2' in opts: newversionflags = REVLOGV2 | FLAG_INLINE_DATA elif b'revlogv1' in opts: newversionflags = REVLOGV1 | FLAG_INLINE_DATA if b'generaldelta' in opts: newversionflags |= FLAG_GENERALDELTA elif b'revlogv0' in self.opener.options: newversionflags = REVLOGV0 else: newversionflags = REVLOG_DEFAULT_VERSION if b'chunkcachesize' in opts: self._chunkcachesize = opts[b'chunkcachesize'] if b'maxchainlen' in opts: self._maxchainlen = opts[b'maxchainlen'] if b'deltabothparents' in opts: self._deltabothparents = opts[b'deltabothparents'] self._lazydelta = bool(opts.get(b'lazydelta', True)) self._lazydeltabase = False if self._lazydelta: self._lazydeltabase = bool(opts.get(b'lazydeltabase', False)) if b'compengine' in opts: self._compengine = opts[b'compengine'] if b'zlib.level' in opts: self._compengineopts[b'zlib.level'] = opts[b'zlib.level'] if b'zstd.level' in opts: self._compengineopts[b'zstd.level'] = opts[b'zstd.level'] if b'maxdeltachainspan' in opts: self._maxdeltachainspan = opts[b'maxdeltachainspan'] if self._mmaplargeindex and b'mmapindexthreshold' in opts: mmapindexthreshold = opts[b'mmapindexthreshold'] self.hassidedata = bool(opts.get(b'side-data', False)) self._sparserevlog = bool(opts.get(b'sparse-revlog', False)) withsparseread = bool(opts.get(b'with-sparse-read', False)) # sparse-revlog forces sparse-read self._withsparseread = self._sparserevlog or withsparseread if b'sparse-read-density-threshold' in opts: self._srdensitythreshold = opts[b'sparse-read-density-threshold'] if b'sparse-read-min-gap-size' in opts: self._srmingapsize = opts[b'sparse-read-min-gap-size'] if opts.get(b'enableellipsis'): self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor # revlog v0 doesn't have flag processors for flag, processor in pycompat.iteritems( opts.get(b'flagprocessors', {}) ): flagutil.insertflagprocessor(flag, processor, self._flagprocessors) if self._chunkcachesize <= 0: raise error.RevlogError( _(b'revlog chunk cache size %r is not greater than 0') % self._chunkcachesize ) elif self._chunkcachesize & (self._chunkcachesize - 1): raise error.RevlogError( _(b'revlog chunk cache size %r is not a power of 2') % self._chunkcachesize ) indexdata = b'' self._initempty = True try: with self._indexfp() as f: if ( mmapindexthreshold is not None and self.opener.fstat(f).st_size >= mmapindexthreshold ): # TODO: should .close() to release resources without # relying on Python GC indexdata = util.buffer(util.mmapread(f)) else: indexdata = f.read() if len(indexdata) > 0: versionflags = INDEX_HEADER.unpack(indexdata[:4])[0] self._initempty = False else: versionflags = newversionflags except IOError as inst: if inst.errno != errno.ENOENT: raise versionflags = newversionflags self.version = versionflags flags = versionflags & ~0xFFFF fmt = versionflags & 0xFFFF if fmt == REVLOGV0: if flags: raise error.RevlogError( _(b'unknown flags (%#04x) in version %d revlog %s') % (flags >> 16, fmt, self.indexfile) ) self._inline = False self._generaldelta = False elif fmt == REVLOGV1: if flags & ~REVLOGV1_FLAGS: raise error.RevlogError( _(b'unknown flags (%#04x) in version %d revlog %s') % (flags >> 16, fmt, self.indexfile) ) self._inline = versionflags & FLAG_INLINE_DATA self._generaldelta = versionflags & FLAG_GENERALDELTA elif fmt == REVLOGV2: if flags & ~REVLOGV2_FLAGS: raise error.RevlogError( _(b'unknown flags (%#04x) in version %d revlog %s') % (flags >> 16, fmt, self.indexfile) ) # There is a bug in the transaction handling when going from an # inline revlog to a separate index and data file. Turn it off until # it's fixed, since v2 revlogs sometimes get rewritten on exchange. # See issue6485 self._inline = False # generaldelta implied by version 2 revlogs. self._generaldelta = True else: raise error.RevlogError( _(b'unknown version (%d) in revlog %s') % (fmt, self.indexfile) ) self.nodeconstants = sha1nodeconstants self.nullid = self.nodeconstants.nullid # sparse-revlog can't be on without general-delta (issue6056) if not self._generaldelta: self._sparserevlog = False self._storedeltachains = True devel_nodemap = ( self.nodemap_file and opts.get(b'devel-force-nodemap', False) and NodemapRevlogIO is not None ) use_rust_index = False if rustrevlog is not None: if self.nodemap_file is not None: use_rust_index = True else: use_rust_index = self.opener.options.get(b'rust.index') self._io = revlogio() if self.version == REVLOGV0: self._io = revlogoldio() elif fmt == REVLOGV2: self._io = revlogv2io() elif devel_nodemap: self._io = NodemapRevlogIO() elif use_rust_index: self._io = rustrevlogio() try: d = self._io.parseindex(indexdata, self._inline) index, _chunkcache = d use_nodemap = ( not self._inline and self.nodemap_file is not None and util.safehasattr(index, 'update_nodemap_data') ) if use_nodemap: nodemap_data = nodemaputil.persisted_data(self) if nodemap_data is not None: docket = nodemap_data[0] if ( len(d[0]) > docket.tip_rev and d[0][docket.tip_rev][7] == docket.tip_node ): # no changelog tampering self._nodemap_docket = docket index.update_nodemap_data(*nodemap_data) except (ValueError, IndexError): raise error.RevlogError( _(b"index %s is corrupted") % self.indexfile ) self.index, self._chunkcache = d if not self._chunkcache: self._chunkclear() # revnum -> (chain-length, sum-delta-length) self._chaininfocache = util.lrucachedict(500) # revlog header -> revlog compressor self._decompressors = {} @util.propertycache def _compressor(self): engine = util.compengines[self._compengine] return engine.revlogcompressor(self._compengineopts) def _indexfp(self, mode=b'r'): """file object for the revlog's index file""" args = {'mode': mode} if mode != b'r': args['checkambig'] = self._checkambig if mode == b'w': args['atomictemp'] = True return self.opener(self.indexfile, **args) def _datafp(self, mode=b'r'): """file object for the revlog's data file""" return self.opener(self.datafile, mode=mode) @contextlib.contextmanager def _datareadfp(self, existingfp=None): """file object suitable to read data""" # Use explicit file handle, if given. if existingfp is not None: yield existingfp # Use a file handle being actively used for writes, if available. # There is some danger to doing this because reads will seek the # file. However, _writeentry() performs a SEEK_END before all writes, # so we should be safe. elif self._writinghandles: if self._inline: yield self._writinghandles[0] else: yield self._writinghandles[1] # Otherwise open a new file handle. else: if self._inline: func = self._indexfp else: func = self._datafp with func() as fp: yield fp def tiprev(self): return len(self.index) - 1 def tip(self): return self.node(self.tiprev()) def __contains__(self, rev): return 0 <= rev < len(self) def __len__(self): return len(self.index) def __iter__(self): return iter(pycompat.xrange(len(self))) def revs(self, start=0, stop=None): """iterate over all rev in this revlog (from start to stop)""" return storageutil.iterrevs(len(self), start=start, stop=stop) @property def nodemap(self): msg = ( b"revlog.nodemap is deprecated, " b"use revlog.index.[has_node|rev|get_rev]" ) util.nouideprecwarn(msg, b'5.3', stacklevel=2) return self.index.nodemap @property def _nodecache(self): msg = b"revlog._nodecache is deprecated, use revlog.index.nodemap" util.nouideprecwarn(msg, b'5.3', stacklevel=2) return self.index.nodemap def hasnode(self, node): try: self.rev(node) return True except KeyError: return False def candelta(self, baserev, rev): """whether two revisions (baserev, rev) can be delta-ed or not""" # Disable delta if either rev requires a content-changing flag # processor (ex. LFS). This is because such flag processor can alter # the rawtext content that the delta will be based on, and two clients # could have a same revlog node with different flags (i.e. different # rawtext contents) and the delta could be incompatible. if (self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) or ( self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS ): return False return True def update_caches(self, transaction): if self.nodemap_file is not None: if transaction is None: nodemaputil.update_persistent_nodemap(self) else: nodemaputil.setup_persistent_nodemap(transaction, self) def clearcaches(self): self._revisioncache = None self._chainbasecache.clear() self._chunkcache = (0, b'') self._pcache = {} self._nodemap_docket = None self.index.clearcaches() # The python code is the one responsible for validating the docket, we # end up having to refresh it here. use_nodemap = ( not self._inline and self.nodemap_file is not None and util.safehasattr(self.index, 'update_nodemap_data') ) if use_nodemap: nodemap_data = nodemaputil.persisted_data(self) if nodemap_data is not None: self._nodemap_docket = nodemap_data[0] self.index.update_nodemap_data(*nodemap_data) def rev(self, node): try: return self.index.rev(node) except TypeError: raise except error.RevlogError: # parsers.c radix tree lookup failed if ( node == self.nodeconstants.wdirid or node in self.nodeconstants.wdirfilenodeids ): raise error.WdirUnsupported raise error.LookupError(node, self.indexfile, _(b'no node')) # Accessors for index entries. # First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes # are flags. def start(self, rev): return int(self.index[rev][0] >> 16) def flags(self, rev): return self.index[rev][0] & 0xFFFF def length(self, rev): return self.index[rev][1] def sidedata_length(self, rev): if self.version & 0xFFFF != REVLOGV2: return 0 return self.index[rev][9] def rawsize(self, rev): """return the length of the uncompressed text for a given revision""" l = self.index[rev][2] if l >= 0: return l t = self.rawdata(rev) return len(t) def size(self, rev): """length of non-raw text (processed by a "read" flag processor)""" # fast path: if no "read" flag processor could change the content, # size is rawsize. note: ELLIPSIS is known to not change the content. flags = self.flags(rev) if flags & (flagutil.REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0: return self.rawsize(rev) return len(self.revision(rev, raw=False)) def chainbase(self, rev): base = self._chainbasecache.get(rev) if base is not None: return base index = self.index iterrev = rev base = index[iterrev][3] while base != iterrev: iterrev = base base = index[iterrev][3] self._chainbasecache[rev] = base return base def linkrev(self, rev): return self.index[rev][4] def parentrevs(self, rev): try: entry = self.index[rev] except IndexError: if rev == wdirrev: raise error.WdirUnsupported raise if entry[5] == nullrev: return entry[6], entry[5] else: return entry[5], entry[6] # fast parentrevs(rev) where rev isn't filtered _uncheckedparentrevs = parentrevs def node(self, rev): try: return self.index[rev][7] except IndexError: if rev == wdirrev: raise error.WdirUnsupported raise # Derived from index values. def end(self, rev): return self.start(rev) + self.length(rev) def parents(self, node): i = self.index d = i[self.rev(node)] # inline node() to avoid function call overhead if d[5] == self.nullid: return i[d[6]][7], i[d[5]][7] else: return i[d[5]][7], i[d[6]][7] def chainlen(self, rev): return self._chaininfo(rev)[0] def _chaininfo(self, rev): chaininfocache = self._chaininfocache if rev in chaininfocache: return chaininfocache[rev] index = self.index generaldelta = self._generaldelta iterrev = rev e = index[iterrev] clen = 0 compresseddeltalen = 0 while iterrev != e[3]: clen += 1 compresseddeltalen += e[1] if generaldelta: iterrev = e[3] else: iterrev -= 1 if iterrev in chaininfocache: t = chaininfocache[iterrev] clen += t[0] compresseddeltalen += t[1] break e = index[iterrev] else: # Add text length of base since decompressing that also takes # work. For cache hits the length is already included. compresseddeltalen += e[1] r = (clen, compresseddeltalen) chaininfocache[rev] = r return r def _deltachain(self, rev, stoprev=None): """Obtain the delta chain for a revision. ``stoprev`` specifies a revision to stop at. If not specified, we stop at the base of the chain. Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of revs in ascending order and ``stopped`` is a bool indicating whether ``stoprev`` was hit. """ # Try C implementation. try: return self.index.deltachain(rev, stoprev, self._generaldelta) except AttributeError: pass chain = [] # Alias to prevent attribute lookup in tight loop. index = self.index generaldelta = self._generaldelta iterrev = rev e = index[iterrev] while iterrev != e[3] and iterrev != stoprev: chain.append(iterrev) if generaldelta: iterrev = e[3] else: iterrev -= 1 e = index[iterrev] if iterrev == stoprev: stopped = True else: chain.append(iterrev) stopped = False chain.reverse() return chain, stopped def ancestors(self, revs, stoprev=0, inclusive=False): """Generate the ancestors of 'revs' in reverse revision order. Does not generate revs lower than stoprev. See the documentation for ancestor.lazyancestors for more details.""" # first, make sure start revisions aren't filtered revs = list(revs) checkrev = self.node for r in revs: checkrev(r) # and we're sure ancestors aren't filtered as well if rustancestor is not None: lazyancestors = rustancestor.LazyAncestors arg = self.index else: lazyancestors = ancestor.lazyancestors arg = self._uncheckedparentrevs return lazyancestors(arg, revs, stoprev=stoprev, inclusive=inclusive) def descendants(self, revs): return dagop.descendantrevs(revs, self.revs, self.parentrevs) def findcommonmissing(self, common=None, heads=None): """Return a tuple of the ancestors of common and the ancestors of heads that are not ancestors of common. In revset terminology, we return the tuple: ::common, (::heads) - (::common) The list is sorted by revision number, meaning it is topologically sorted. 'heads' and 'common' are both lists of node IDs. If heads is not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: common = [self.nullid] if heads is None: heads = self.heads() common = [self.rev(n) for n in common] heads = [self.rev(n) for n in heads] # we want the ancestors, but inclusive class lazyset(object): def __init__(self, lazyvalues): self.addedvalues = set() self.lazyvalues = lazyvalues def __contains__(self, value): return value in self.addedvalues or value in self.lazyvalues def __iter__(self): added = self.addedvalues for r in added: yield r for r in self.lazyvalues: if not r in added: yield r def add(self, value): self.addedvalues.add(value) def update(self, values): self.addedvalues.update(values) has = lazyset(self.ancestors(common)) has.add(nullrev) has.update(common) # take all ancestors from heads that aren't in has missing = set() visit = collections.deque(r for r in heads if r not in has) while visit: r = visit.popleft() if r in missing: continue else: missing.add(r) for p in self.parentrevs(r): if p not in has: visit.append(p) missing = list(missing) missing.sort() return has, [self.node(miss) for miss in missing] def incrementalmissingrevs(self, common=None): """Return an object that can be used to incrementally compute the revision numbers of the ancestors of arbitrary sets that are not ancestors of common. This is an ancestor.incrementalmissingancestors object. 'common' is a list of revision numbers. If common is not supplied, uses nullrev. """ if common is None: common = [nullrev] if rustancestor is not None: return rustancestor.MissingAncestors(self.index, common) return ancestor.incrementalmissingancestors(self.parentrevs, common) def findmissingrevs(self, common=None, heads=None): """Return the revision numbers of the ancestors of heads that are not ancestors of common. More specifically, return a list of revision numbers corresponding to nodes N such that every N satisfies the following constraints: 1. N is an ancestor of some node in 'heads' 2. N is not an ancestor of any node in 'common' The list is sorted by revision number, meaning it is topologically sorted. 'heads' and 'common' are both lists of revision numbers. If heads is not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: common = [nullrev] if heads is None: heads = self.headrevs() inc = self.incrementalmissingrevs(common=common) return inc.missingancestors(heads) def findmissing(self, common=None, heads=None): """Return the ancestors of heads that are not ancestors of common. More specifically, return a list of nodes N such that every N satisfies the following constraints: 1. N is an ancestor of some node in 'heads' 2. N is not an ancestor of any node in 'common' The list is sorted by revision number, meaning it is topologically sorted. 'heads' and 'common' are both lists of node IDs. If heads is not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: common = [self.nullid] if heads is None: heads = self.heads() common = [self.rev(n) for n in common] heads = [self.rev(n) for n in heads] inc = self.incrementalmissingrevs(common=common) return [self.node(r) for r in inc.missingancestors(heads)] def nodesbetween(self, roots=None, heads=None): """Return a topological path from 'roots' to 'heads'. Return a tuple (nodes, outroots, outheads) where 'nodes' is a topologically sorted list of all nodes N that satisfy both of these constraints: 1. N is a descendant of some node in 'roots' 2. N is an ancestor of some node in 'heads' Every node is considered to be both a descendant and an ancestor of itself, so every reachable node in 'roots' and 'heads' will be included in 'nodes'. 'outroots' is the list of reachable nodes in 'roots', i.e., the subset of 'roots' that is returned in 'nodes'. Likewise, 'outheads' is the subset of 'heads' that is also in 'nodes'. 'roots' and 'heads' are both lists of node IDs. If 'roots' is unspecified, uses nullid as the only root. If 'heads' is unspecified, uses list of all of the revlog's heads.""" nonodes = ([], [], []) if roots is not None: roots = list(roots) if not roots: return nonodes lowestrev = min([self.rev(n) for n in roots]) else: roots = [self.nullid] # Everybody's a descendant of nullid lowestrev = nullrev if (lowestrev == nullrev) and (heads is None): # We want _all_ the nodes! return ( [self.node(r) for r in self], [self.nullid], list(self.heads()), ) if heads is None: # All nodes are ancestors, so the latest ancestor is the last # node. highestrev = len(self) - 1 # Set ancestors to None to signal that every node is an ancestor. ancestors = None # Set heads to an empty dictionary for later discovery of heads heads = {} else: heads = list(heads) if not heads: return nonodes ancestors = set() # Turn heads into a dictionary so we can remove 'fake' heads. # Also, later we will be using it to filter out the heads we can't # find from roots. heads = dict.fromkeys(heads, False) # Start at the top and keep marking parents until we're done. nodestotag = set(heads) # Remember where the top was so we can use it as a limit later. highestrev = max([self.rev(n) for n in nodestotag]) while nodestotag: # grab a node to tag n = nodestotag.pop() # Never tag nullid if n == self.nullid: continue # A node's revision number represents its place in a # topologically sorted list of nodes. r = self.rev(n) if r >= lowestrev: if n not in ancestors: # If we are possibly a descendant of one of the roots # and we haven't already been marked as an ancestor ancestors.add(n) # Mark as ancestor # Add non-nullid parents to list of nodes to tag. nodestotag.update( [p for p in self.parents(n) if p != self.nullid] ) elif n in heads: # We've seen it before, is it a fake head? # So it is, real heads should not be the ancestors of # any other heads. heads.pop(n) if not ancestors: return nonodes # Now that we have our set of ancestors, we want to remove any # roots that are not ancestors. # If one of the roots was nullid, everything is included anyway. if lowestrev > nullrev: # But, since we weren't, let's recompute the lowest rev to not # include roots that aren't ancestors. # Filter out roots that aren't ancestors of heads roots = [root for root in roots if root in ancestors] # Recompute the lowest revision if roots: lowestrev = min([self.rev(root) for root in roots]) else: # No more roots? Return empty list return nonodes else: # We are descending from nullid, and don't need to care about # any other roots. lowestrev = nullrev roots = [self.nullid] # Transform our roots list into a set. descendants = set(roots) # Also, keep the original roots so we can filter out roots that aren't # 'real' roots (i.e. are descended from other roots). roots = descendants.copy() # Our topologically sorted list of output nodes. orderedout = [] # Don't start at nullid since we don't want nullid in our output list, # and if nullid shows up in descendants, empty parents will look like # they're descendants. for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1): n = self.node(r) isdescendant = False if lowestrev == nullrev: # Everybody is a descendant of nullid isdescendant = True elif n in descendants: # n is already a descendant isdescendant = True # This check only needs to be done here because all the roots # will start being marked is descendants before the loop. if n in roots: # If n was a root, check if it's a 'real' root. p = tuple(self.parents(n)) # If any of its parents are descendants, it's not a root. if (p[0] in descendants) or (p[1] in descendants): roots.remove(n) else: p = tuple(self.parents(n)) # A node is a descendant if either of its parents are # descendants. (We seeded the dependents list with the roots # up there, remember?) if (p[0] in descendants) or (p[1] in descendants): descendants.add(n) isdescendant = True if isdescendant and ((ancestors is None) or (n in ancestors)): # Only include nodes that are both descendants and ancestors. orderedout.append(n) if (ancestors is not None) and (n in heads): # We're trying to figure out which heads are reachable # from roots. # Mark this head as having been reached heads[n] = True elif ancestors is None: # Otherwise, we're trying to discover the heads. # Assume this is a head because if it isn't, the next step # will eventually remove it. heads[n] = True # But, obviously its parents aren't. for p in self.parents(n): heads.pop(p, None) heads = [head for head, flag in pycompat.iteritems(heads) if flag] roots = list(roots) assert orderedout assert roots assert heads return (orderedout, roots, heads) def headrevs(self, revs=None): if revs is None: try: return self.index.headrevs() except AttributeError: return self._headrevs() if rustdagop is not None: return rustdagop.headrevs(self.index, revs) return dagop.headrevs(revs, self._uncheckedparentrevs) def computephases(self, roots): return self.index.computephasesmapsets(roots) def _headrevs(self): count = len(self) if not count: return [nullrev] # we won't iter over filtered rev so nobody is a head at start ishead = [0] * (count + 1) index = self.index for r in self: ishead[r] = 1 # I may be an head e = index[r] ishead[e[5]] = ishead[e[6]] = 0 # my parent are not return [r for r, val in enumerate(ishead) if val] def heads(self, start=None, stop=None): """return the list of all nodes that have no children if start is specified, only heads that are descendants of start will be returned if stop is specified, it will consider all the revs from stop as if they had no children """ if start is None and stop is None: if not len(self): return [self.nullid] return [self.node(r) for r in self.headrevs()] if start is None: start = nullrev else: start = self.rev(start) stoprevs = {self.rev(n) for n in stop or []} revs = dagop.headrevssubset( self.revs, self.parentrevs, startrev=start, stoprevs=stoprevs ) return [self.node(rev) for rev in revs] def children(self, node): """find the children of a given node""" c = [] p = self.rev(node) for r in self.revs(start=p + 1): prevs = [pr for pr in self.parentrevs(r) if pr != nullrev] if prevs: for pr in prevs: if pr == p: c.append(self.node(r)) elif p == nullrev: c.append(self.node(r)) return c def commonancestorsheads(self, a, b): """calculate all the heads of the common ancestors of nodes a and b""" a, b = self.rev(a), self.rev(b) ancs = self._commonancestorsheads(a, b) return pycompat.maplist(self.node, ancs) def _commonancestorsheads(self, *revs): """calculate all the heads of the common ancestors of revs""" try: ancs = self.index.commonancestorsheads(*revs) except (AttributeError, OverflowError): # C implementation failed ancs = ancestor.commonancestorsheads(self.parentrevs, *revs) return ancs def isancestor(self, a, b): """return True if node a is an ancestor of node b A revision is considered an ancestor of itself.""" a, b = self.rev(a), self.rev(b) return self.isancestorrev(a, b) def isancestorrev(self, a, b): """return True if revision a is an ancestor of revision b A revision is considered an ancestor of itself. The implementation of this is trivial but the use of reachableroots is not.""" if a == nullrev: return True elif a == b: return True elif a > b: return False return bool(self.reachableroots(a, [b], [a], includepath=False)) def reachableroots(self, minroot, heads, roots, includepath=False): """return (heads(::( and ::))) If includepath is True, return (::).""" try: return self.index.reachableroots2( minroot, heads, roots, includepath ) except AttributeError: return dagop._reachablerootspure( self.parentrevs, minroot, roots, heads, includepath ) def ancestor(self, a, b): """calculate the "best" common ancestor of nodes a and b""" a, b = self.rev(a), self.rev(b) try: ancs = self.index.ancestors(a, b) except (AttributeError, OverflowError): ancs = ancestor.ancestors(self.parentrevs, a, b) if ancs: # choose a consistent winner when there's a tie return min(map(self.node, ancs)) return self.nullid def _match(self, id): if isinstance(id, int): # rev return self.node(id) if len(id) == 20: # possibly a binary node # odds of a binary node being all hex in ASCII are 1 in 10**25 try: node = id self.rev(node) # quick search the index return node except error.LookupError: pass # may be partial hex id try: # str(rev) rev = int(id) if b"%d" % rev != id: raise ValueError if rev < 0: rev = len(self) + rev if rev < 0 or rev >= len(self): raise ValueError return self.node(rev) except (ValueError, OverflowError): pass if len(id) == 40: try: # a full hex nodeid? node = bin(id) self.rev(node) return node except (TypeError, error.LookupError): pass def _partialmatch(self, id): # we don't care wdirfilenodeids as they should be always full hash maybewdir = self.nodeconstants.wdirhex.startswith(id) try: partial = self.index.partialmatch(id) if partial and self.hasnode(partial): if maybewdir: # single 'ff...' match in radix tree, ambiguous with wdir raise error.RevlogError return partial if maybewdir: # no 'ff...' match in radix tree, wdir identified raise error.WdirUnsupported return None except error.RevlogError: # parsers.c radix tree lookup gave multiple matches # fast path: for unfiltered changelog, radix tree is accurate if not getattr(self, 'filteredrevs', None): raise error.AmbiguousPrefixLookupError( id, self.indexfile, _(b'ambiguous identifier') ) # fall through to slow path that filters hidden revisions except (AttributeError, ValueError): # we are pure python, or key was too short to search radix tree pass if id in self._pcache: return self._pcache[id] if len(id) <= 40: try: # hex(node)[:...] l = len(id) // 2 # grab an even number of digits prefix = bin(id[: l * 2]) nl = [e[7] for e in self.index if e[7].startswith(prefix)] nl = [ n for n in nl if hex(n).startswith(id) and self.hasnode(n) ] if self.nodeconstants.nullhex.startswith(id): nl.append(self.nullid) if len(nl) > 0: if len(nl) == 1 and not maybewdir: self._pcache[id] = nl[0] return nl[0] raise error.AmbiguousPrefixLookupError( id, self.indexfile, _(b'ambiguous identifier') ) if maybewdir: raise error.WdirUnsupported return None except TypeError: pass def lookup(self, id): """locate a node based on: - revision number or str(revision number) - nodeid or subset of hex nodeid """ n = self._match(id) if n is not None: return n n = self._partialmatch(id) if n: return n raise error.LookupError(id, self.indexfile, _(b'no match found')) def shortest(self, node, minlength=1): """Find the shortest unambiguous prefix that matches node.""" def isvalid(prefix): try: matchednode = self._partialmatch(prefix) except error.AmbiguousPrefixLookupError: return False except error.WdirUnsupported: # single 'ff...' match return True if matchednode is None: raise error.LookupError(node, self.indexfile, _(b'no node')) return True def maybewdir(prefix): return all(c == b'f' for c in pycompat.iterbytestr(prefix)) hexnode = hex(node) def disambiguate(hexnode, minlength): """Disambiguate against wdirid.""" for length in range(minlength, len(hexnode) + 1): prefix = hexnode[:length] if not maybewdir(prefix): return prefix if not getattr(self, 'filteredrevs', None): try: length = max(self.index.shortest(node), minlength) return disambiguate(hexnode, length) except error.RevlogError: if node != self.nodeconstants.wdirid: raise error.LookupError(node, self.indexfile, _(b'no node')) except AttributeError: # Fall through to pure code pass if node == self.nodeconstants.wdirid: for length in range(minlength, len(hexnode) + 1): prefix = hexnode[:length] if isvalid(prefix): return prefix for length in range(minlength, len(hexnode) + 1): prefix = hexnode[:length] if isvalid(prefix): return disambiguate(hexnode, length) def cmp(self, node, text): """compare text with a given file revision returns True if text is different than what is stored. """ p1, p2 = self.parents(node) return storageutil.hashrevisionsha1(text, p1, p2) != node def _cachesegment(self, offset, data): """Add a segment to the revlog cache. Accepts an absolute offset and the data that is at that location. """ o, d = self._chunkcache # try to add to existing cache if o + len(d) == offset and len(d) + len(data) < _chunksize: self._chunkcache = o, d + data else: self._chunkcache = offset, data def _readsegment(self, offset, length, df=None): """Load a segment of raw data from the revlog. Accepts an absolute offset, length to read, and an optional existing file handle to read from. If an existing file handle is passed, it will be seeked and the original seek position will NOT be restored. Returns a str or buffer of raw byte data. Raises if the requested number of bytes could not be read. """ # Cache data both forward and backward around the requested # data, in a fixed size window. This helps speed up operations # involving reading the revlog backwards. cachesize = self._chunkcachesize realoffset = offset & ~(cachesize - 1) reallength = ( (offset + length + cachesize) & ~(cachesize - 1) ) - realoffset with self._datareadfp(df) as df: df.seek(realoffset) d = df.read(reallength) self._cachesegment(realoffset, d) if offset != realoffset or reallength != length: startoffset = offset - realoffset if len(d) - startoffset < length: raise error.RevlogError( _( b'partial read of revlog %s; expected %d bytes from ' b'offset %d, got %d' ) % ( self.indexfile if self._inline else self.datafile, length, realoffset, len(d) - startoffset, ) ) return util.buffer(d, startoffset, length) if len(d) < length: raise error.RevlogError( _( b'partial read of revlog %s; expected %d bytes from offset ' b'%d, got %d' ) % ( self.indexfile if self._inline else self.datafile, length, offset, len(d), ) ) return d def _getsegment(self, offset, length, df=None): """Obtain a segment of raw data from the revlog. Accepts an absolute offset, length of bytes to obtain, and an optional file handle to the already-opened revlog. If the file handle is used, it's original seek position will not be preserved. Requests for data may be returned from a cache. Returns a str or a buffer instance of raw byte data. """ o, d = self._chunkcache l = len(d) # is it in the cache? cachestart = offset - o cacheend = cachestart + length if cachestart >= 0 and cacheend <= l: if cachestart == 0 and cacheend == l: return d # avoid a copy return util.buffer(d, cachestart, cacheend - cachestart) return self._readsegment(offset, length, df=df) def _getsegmentforrevs(self, startrev, endrev, df=None): """Obtain a segment of raw data corresponding to a range of revisions. Accepts the start and end revisions and an optional already-open file handle to be used for reading. If the file handle is read, its seek position will not be preserved. Requests for data may be satisfied by a cache. Returns a 2-tuple of (offset, data) for the requested range of revisions. Offset is the integer offset from the beginning of the revlog and data is a str or buffer of the raw byte data. Callers will need to call ``self.start(rev)`` and ``self.length(rev)`` to determine where each revision's data begins and ends. """ # Inlined self.start(startrev) & self.end(endrev) for perf reasons # (functions are expensive). index = self.index istart = index[startrev] start = int(istart[0] >> 16) if startrev == endrev: end = start + istart[1] else: iend = index[endrev] end = int(iend[0] >> 16) + iend[1] if self._inline: start += (startrev + 1) * self.index.entry_size end += (endrev + 1) * self.index.entry_size length = end - start return start, self._getsegment(start, length, df=df) def _chunk(self, rev, df=None): """Obtain a single decompressed chunk for a revision. Accepts an integer revision and an optional already-open file handle to be used for reading. If used, the seek position of the file will not be preserved. Returns a str holding uncompressed data for the requested revision. """ return self.decompress(self._getsegmentforrevs(rev, rev, df=df)[1]) def _chunks(self, revs, df=None, targetsize=None): """Obtain decompressed chunks for the specified revisions. Accepts an iterable of numeric revisions that are assumed to be in ascending order. Also accepts an optional already-open file handle to be used for reading. If used, the seek position of the file will not be preserved. This function is similar to calling ``self._chunk()`` multiple times, but is faster. Returns a list with decompressed data for each requested revision. """ if not revs: return [] start = self.start length = self.length inline = self._inline iosize = self.index.entry_size buffer = util.buffer l = [] ladd = l.append if not self._withsparseread: slicedchunks = (revs,) else: slicedchunks = deltautil.slicechunk( self, revs, targetsize=targetsize ) for revschunk in slicedchunks: firstrev = revschunk[0] # Skip trailing revisions with empty diff for lastrev in revschunk[::-1]: if length(lastrev) != 0: break try: offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df) except OverflowError: # issue4215 - we can't cache a run of chunks greater than # 2G on Windows return [self._chunk(rev, df=df) for rev in revschunk] decomp = self.decompress for rev in revschunk: chunkstart = start(rev) if inline: chunkstart += (rev + 1) * iosize chunklength = length(rev) ladd(decomp(buffer(data, chunkstart - offset, chunklength))) return l def _chunkclear(self): """Clear the raw chunk cache.""" self._chunkcache = (0, b'') def deltaparent(self, rev): """return deltaparent of the given revision""" base = self.index[rev][3] if base == rev: return nullrev elif self._generaldelta: return base else: return rev - 1 def issnapshot(self, rev): """tells whether rev is a snapshot""" if not self._sparserevlog: return self.deltaparent(rev) == nullrev elif util.safehasattr(self.index, b'issnapshot'): # directly assign the method to cache the testing and access self.issnapshot = self.index.issnapshot return self.issnapshot(rev) if rev == nullrev: return True entry = self.index[rev] base = entry[3] if base == rev: return True if base == nullrev: return True p1 = entry[5] p2 = entry[6] if base == p1 or base == p2: return False return self.issnapshot(base) def snapshotdepth(self, rev): """number of snapshot in the chain before this one""" if not self.issnapshot(rev): raise error.ProgrammingError(b'revision %d not a snapshot') return len(self._deltachain(rev)[0]) - 1 def revdiff(self, rev1, rev2): """return or calculate a delta between two revisions The delta calculated is in binary form and is intended to be written to revlog data directly. So this function needs raw revision data. """ if rev1 != nullrev and self.deltaparent(rev2) == rev1: return bytes(self._chunk(rev2)) return mdiff.textdiff(self.rawdata(rev1), self.rawdata(rev2)) def _processflags(self, text, flags, operation, raw=False): """deprecated entry point to access flag processors""" msg = b'_processflag(...) use the specialized variant' util.nouideprecwarn(msg, b'5.2', stacklevel=2) if raw: return text, flagutil.processflagsraw(self, text, flags) elif operation == b'read': return flagutil.processflagsread(self, text, flags) else: # write operation return flagutil.processflagswrite(self, text, flags) def revision(self, nodeorrev, _df=None, raw=False): """return an uncompressed revision of a given node or revision number. _df - an existing file handle to read from. (internal-only) raw - an optional argument specifying if the revision data is to be treated as raw data when applying flag transforms. 'raw' should be set to True when generating changegroups or in debug commands. """ if raw: msg = ( b'revlog.revision(..., raw=True) is deprecated, ' b'use revlog.rawdata(...)' ) util.nouideprecwarn(msg, b'5.2', stacklevel=2) return self._revisiondata(nodeorrev, _df, raw=raw)[0] def sidedata(self, nodeorrev, _df=None): """a map of extra data related to the changeset but not part of the hash This function currently return a dictionary. However, more advanced mapping object will likely be used in the future for a more efficient/lazy code. """ return self._revisiondata(nodeorrev, _df)[1] def _revisiondata(self, nodeorrev, _df=None, raw=False): # deal with argument type if isinstance(nodeorrev, int): rev = nodeorrev node = self.node(rev) else: node = nodeorrev rev = None # fast path the special `nullid` rev if node == self.nullid: return b"", {} # ``rawtext`` is the text as stored inside the revlog. Might be the # revision or might need to be processed to retrieve the revision. rev, rawtext, validated = self._rawtext(node, rev, _df=_df) if self.version & 0xFFFF == REVLOGV2: if rev is None: rev = self.rev(node) sidedata = self._sidedata(rev) else: sidedata = {} if raw and validated: # if we don't want to process the raw text and that raw # text is cached, we can exit early. return rawtext, sidedata if rev is None: rev = self.rev(node) # the revlog's flag for this revision # (usually alter its state or content) flags = self.flags(rev) if validated and flags == REVIDX_DEFAULT_FLAGS: # no extra flags set, no flag processor runs, text = rawtext return rawtext, sidedata if raw: validatehash = flagutil.processflagsraw(self, rawtext, flags) text = rawtext else: r = flagutil.processflagsread(self, rawtext, flags) text, validatehash = r if validatehash: self.checkhash(text, node, rev=rev) if not validated: self._revisioncache = (node, rev, rawtext) return text, sidedata def _rawtext(self, node, rev, _df=None): """return the possibly unvalidated rawtext for a revision returns (rev, rawtext, validated) """ # revision in the cache (could be useful to apply delta) cachedrev = None # An intermediate text to apply deltas to basetext = None # Check if we have the entry in cache # The cache entry looks like (node, rev, rawtext) if self._revisioncache: if self._revisioncache[0] == node: return (rev, self._revisioncache[2], True) cachedrev = self._revisioncache[1] if rev is None: rev = self.rev(node) chain, stopped = self._deltachain(rev, stoprev=cachedrev) if stopped: basetext = self._revisioncache[2] # drop cache to save memory, the caller is expected to # update self._revisioncache after validating the text self._revisioncache = None targetsize = None rawsize = self.index[rev][2] if 0 <= rawsize: targetsize = 4 * rawsize bins = self._chunks(chain, df=_df, targetsize=targetsize) if basetext is None: basetext = bytes(bins[0]) bins = bins[1:] rawtext = mdiff.patches(basetext, bins) del basetext # let us have a chance to free memory early return (rev, rawtext, False) def _sidedata(self, rev): """Return the sidedata for a given revision number.""" index_entry = self.index[rev] sidedata_offset = index_entry[8] sidedata_size = index_entry[9] if self._inline: sidedata_offset += self.index.entry_size * (1 + rev) if sidedata_size == 0: return {} segment = self._getsegment(sidedata_offset, sidedata_size) sidedata = sidedatautil.deserialize_sidedata(segment) return sidedata def rawdata(self, nodeorrev, _df=None): """return an uncompressed raw data of a given node or revision number. _df - an existing file handle to read from. (internal-only) """ return self._revisiondata(nodeorrev, _df, raw=True)[0] def hash(self, text, p1, p2): """Compute a node hash. Available as a function so that subclasses can replace the hash as needed. """ return storageutil.hashrevisionsha1(text, p1, p2) def checkhash(self, text, node, p1=None, p2=None, rev=None): """Check node hash integrity. Available as a function so that subclasses can extend hash mismatch behaviors as needed. """ try: if p1 is None and p2 is None: p1, p2 = self.parents(node) if node != self.hash(text, p1, p2): # Clear the revision cache on hash failure. The revision cache # only stores the raw revision and clearing the cache does have # the side-effect that we won't have a cache hit when the raw # revision data is accessed. But this case should be rare and # it is extra work to teach the cache about the hash # verification state. if self._revisioncache and self._revisioncache[0] == node: self._revisioncache = None revornode = rev if revornode is None: revornode = templatefilters.short(hex(node)) raise error.RevlogError( _(b"integrity check failed on %s:%s") % (self.indexfile, pycompat.bytestr(revornode)) ) except error.RevlogError: if self._censorable and storageutil.iscensoredtext(text): raise error.CensoredNodeError(self.indexfile, node, text) raise def _enforceinlinesize(self, tr, fp=None): """Check if the revlog is too big for inline and convert if so. This should be called after revisions are added to the revlog. If the revlog has grown too large to be an inline revlog, it will convert it to use multiple index and data files. """ tiprev = len(self) - 1 if ( not self._inline or (self.start(tiprev) + self.length(tiprev)) < _maxinline ): return troffset = tr.findoffset(self.indexfile) if troffset is None: raise error.RevlogError( _(b"%s not found in the transaction") % self.indexfile ) trindex = 0 tr.add(self.datafile, 0) if fp: fp.flush() fp.close() # We can't use the cached file handle after close(). So prevent # its usage. self._writinghandles = None with self._indexfp(b'r') as ifh, self._datafp(b'w') as dfh: for r in self: dfh.write(self._getsegmentforrevs(r, r, df=ifh)[1]) if troffset <= self.start(r): trindex = r with self._indexfp(b'w') as fp: self.version &= ~FLAG_INLINE_DATA self._inline = False io = self._io for i in self: - e = io.packentry(self.index[i], self.node, self.version, i) + e = self.index.entry_binary(i, self.version) fp.write(e) # the temp file replace the real index when we exit the context # manager tr.replace(self.indexfile, trindex * self.index.entry_size) nodemaputil.setup_persistent_nodemap(tr, self) self._chunkclear() def _nodeduplicatecallback(self, transaction, node): """called when trying to add a node already stored.""" def addrevision( self, text, transaction, link, p1, p2, cachedelta=None, node=None, flags=REVIDX_DEFAULT_FLAGS, deltacomputer=None, sidedata=None, ): """add a revision to the log text - the revision data to add transaction - the transaction object used for rollback link - the linkrev data to add p1, p2 - the parent nodeids of the revision cachedelta - an optional precomputed delta node - nodeid of revision; typically node is not specified, and it is computed by default as hash(text, p1, p2), however subclasses might use different hashing method (and override checkhash() in such case) flags - the known flags to set on the revision deltacomputer - an optional deltacomputer instance shared between multiple calls """ if link == nullrev: raise error.RevlogError( _(b"attempted to add linkrev -1 to %s") % self.indexfile ) if sidedata is None: sidedata = {} elif not self.hassidedata: raise error.ProgrammingError( _(b"trying to add sidedata to a revlog who don't support them") ) if flags: node = node or self.hash(text, p1, p2) rawtext, validatehash = flagutil.processflagswrite(self, text, flags) # If the flag processor modifies the revision data, ignore any provided # cachedelta. if rawtext != text: cachedelta = None if len(rawtext) > _maxentrysize: raise error.RevlogError( _( b"%s: size of %d bytes exceeds maximum revlog storage of 2GiB" ) % (self.indexfile, len(rawtext)) ) node = node or self.hash(rawtext, p1, p2) rev = self.index.get_rev(node) if rev is not None: return rev if validatehash: self.checkhash(rawtext, node, p1=p1, p2=p2) return self.addrawrevision( rawtext, transaction, link, p1, p2, node, flags, cachedelta=cachedelta, deltacomputer=deltacomputer, sidedata=sidedata, ) def addrawrevision( self, rawtext, transaction, link, p1, p2, node, flags, cachedelta=None, deltacomputer=None, sidedata=None, ): """add a raw revision with known flags, node and parents useful when reusing a revision not stored in this revlog (ex: received over wire, or read from an external bundle). """ dfh = None if not self._inline: dfh = self._datafp(b"a+") ifh = self._indexfp(b"a+") try: return self._addrevision( node, rawtext, transaction, link, p1, p2, flags, cachedelta, ifh, dfh, deltacomputer=deltacomputer, sidedata=sidedata, ) finally: if dfh: dfh.close() ifh.close() def compress(self, data): """Generate a possibly-compressed representation of data.""" if not data: return b'', data compressed = self._compressor.compress(data) if compressed: # The revlog compressor added the header in the returned data. return b'', compressed if data[0:1] == b'\0': return b'', data return b'u', data def decompress(self, data): """Decompress a revlog chunk. The chunk is expected to begin with a header identifying the format type so it can be routed to an appropriate decompressor. """ if not data: return data # Revlogs are read much more frequently than they are written and many # chunks only take microseconds to decompress, so performance is # important here. # # We can make a few assumptions about revlogs: # # 1) the majority of chunks will be compressed (as opposed to inline # raw data). # 2) decompressing *any* data will likely by at least 10x slower than # returning raw inline data. # 3) we want to prioritize common and officially supported compression # engines # # It follows that we want to optimize for "decompress compressed data # when encoded with common and officially supported compression engines" # case over "raw data" and "data encoded by less common or non-official # compression engines." That is why we have the inline lookup first # followed by the compengines lookup. # # According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib # compressed chunks. And this matters for changelog and manifest reads. t = data[0:1] if t == b'x': try: return _zlibdecompress(data) except zlib.error as e: raise error.RevlogError( _(b'revlog decompress error: %s') % stringutil.forcebytestr(e) ) # '\0' is more common than 'u' so it goes first. elif t == b'\0': return data elif t == b'u': return util.buffer(data, 1) try: compressor = self._decompressors[t] except KeyError: try: engine = util.compengines.forrevlogheader(t) compressor = engine.revlogcompressor(self._compengineopts) self._decompressors[t] = compressor except KeyError: raise error.RevlogError( _(b'unknown compression type %s') % binascii.hexlify(t) ) return compressor.decompress(data) def _addrevision( self, node, rawtext, transaction, link, p1, p2, flags, cachedelta, ifh, dfh, alwayscache=False, deltacomputer=None, sidedata=None, ): """internal function to add revisions to the log see addrevision for argument descriptions. note: "addrevision" takes non-raw text, "_addrevision" takes raw text. if "deltacomputer" is not provided or None, a defaultdeltacomputer will be used. invariants: - rawtext is optional (can be None); if not set, cachedelta must be set. if both are set, they must correspond to each other. """ if node == self.nullid: raise error.RevlogError( _(b"%s: attempt to add null revision") % self.indexfile ) if ( node == self.nodeconstants.wdirid or node in self.nodeconstants.wdirfilenodeids ): raise error.RevlogError( _(b"%s: attempt to add wdir revision") % self.indexfile ) if self._inline: fh = ifh else: fh = dfh btext = [rawtext] curr = len(self) prev = curr - 1 offset = self._get_data_offset(prev) if self._concurrencychecker: if self._inline: # offset is "as if" it were in the .d file, so we need to add on # the size of the entry metadata. self._concurrencychecker( ifh, self.indexfile, offset + curr * self.index.entry_size ) else: # Entries in the .i are a consistent size. self._concurrencychecker( ifh, self.indexfile, curr * self.index.entry_size ) self._concurrencychecker(dfh, self.datafile, offset) p1r, p2r = self.rev(p1), self.rev(p2) # full versions are inserted when the needed deltas # become comparable to the uncompressed text if rawtext is None: # need rawtext size, before changed by flag processors, which is # the non-raw size. use revlog explicitly to avoid filelog's extra # logic that might remove metadata size. textlen = mdiff.patchedsize( revlog.size(self, cachedelta[0]), cachedelta[1] ) else: textlen = len(rawtext) if deltacomputer is None: deltacomputer = deltautil.deltacomputer(self) revinfo = _revisioninfo(node, p1, p2, btext, textlen, cachedelta, flags) deltainfo = deltacomputer.finddeltainfo(revinfo, fh) if sidedata: serialized_sidedata = sidedatautil.serialize_sidedata(sidedata) sidedata_offset = offset + deltainfo.deltalen else: serialized_sidedata = b"" # Don't store the offset if the sidedata is empty, that way # we can easily detect empty sidedata and they will be no different # than ones we manually add. sidedata_offset = 0 e = ( offset_type(offset, flags), deltainfo.deltalen, textlen, deltainfo.base, link, p1r, p2r, node, sidedata_offset, len(serialized_sidedata), ) if self.version & 0xFFFF != REVLOGV2: e = e[:8] self.index.append(e) - entry = self._io.packentry(e, self.node, self.version, curr) + entry = self.index.entry_binary(curr, self.version) self._writeentry( transaction, ifh, dfh, entry, deltainfo.data, link, offset, serialized_sidedata, ) rawtext = btext[0] if alwayscache and rawtext is None: rawtext = deltacomputer.buildtext(revinfo, fh) if type(rawtext) == bytes: # only accept immutable objects self._revisioncache = (node, curr, rawtext) self._chainbasecache[curr] = deltainfo.chainbase return curr def _get_data_offset(self, prev): """Returns the current offset in the (in-transaction) data file. Versions < 2 of the revlog can get this 0(1), revlog v2 needs a docket file to store that information: since sidedata can be rewritten to the end of the data file within a transaction, you can have cases where, for example, rev `n` does not have sidedata while rev `n - 1` does, leading to `n - 1`'s sidedata being written after `n`'s data. TODO cache this in a docket file before getting out of experimental.""" if self.version & 0xFFFF != REVLOGV2: return self.end(prev) offset = 0 for rev, entry in enumerate(self.index): sidedata_end = entry[8] + entry[9] # Sidedata for a previous rev has potentially been written after # this rev's end, so take the max. offset = max(self.end(rev), offset, sidedata_end) return offset def _writeentry( self, transaction, ifh, dfh, entry, data, link, offset, sidedata ): # Files opened in a+ mode have inconsistent behavior on various # platforms. Windows requires that a file positioning call be made # when the file handle transitions between reads and writes. See # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other # platforms, Python or the platform itself can be buggy. Some versions # of Solaris have been observed to not append at the end of the file # if the file was seeked to before the end. See issue4943 for more. # # We work around this issue by inserting a seek() before writing. # Note: This is likely not necessary on Python 3. However, because # the file handle is reused for reads and may be seeked there, we need # to be careful before changing this. ifh.seek(0, os.SEEK_END) if dfh: dfh.seek(0, os.SEEK_END) curr = len(self) - 1 if not self._inline: transaction.add(self.datafile, offset) transaction.add(self.indexfile, curr * len(entry)) if data[0]: dfh.write(data[0]) dfh.write(data[1]) if sidedata: dfh.write(sidedata) ifh.write(entry) else: offset += curr * self.index.entry_size transaction.add(self.indexfile, offset) ifh.write(entry) ifh.write(data[0]) ifh.write(data[1]) if sidedata: ifh.write(sidedata) self._enforceinlinesize(transaction, ifh) nodemaputil.setup_persistent_nodemap(transaction, self) def addgroup( self, deltas, linkmapper, transaction, alwayscache=False, addrevisioncb=None, duplicaterevisioncb=None, ): """ add a delta group given a set of deltas, add them to the revision log. the first delta is against its parent, which should be in our log, the rest are against the previous delta. If ``addrevisioncb`` is defined, it will be called with arguments of this revlog and the node that was added. """ if self._writinghandles: raise error.ProgrammingError(b'cannot nest addgroup() calls') r = len(self) end = 0 if r: end = self.end(r - 1) ifh = self._indexfp(b"a+") isize = r * self.index.entry_size if self._inline: transaction.add(self.indexfile, end + isize) dfh = None else: transaction.add(self.indexfile, isize) transaction.add(self.datafile, end) dfh = self._datafp(b"a+") def flush(): if dfh: dfh.flush() ifh.flush() self._writinghandles = (ifh, dfh) empty = True try: deltacomputer = deltautil.deltacomputer(self) # loop through our set of deltas for data in deltas: node, p1, p2, linknode, deltabase, delta, flags, sidedata = data link = linkmapper(linknode) flags = flags or REVIDX_DEFAULT_FLAGS rev = self.index.get_rev(node) if rev is not None: # this can happen if two branches make the same change self._nodeduplicatecallback(transaction, rev) if duplicaterevisioncb: duplicaterevisioncb(self, rev) empty = False continue for p in (p1, p2): if not self.index.has_node(p): raise error.LookupError( p, self.indexfile, _(b'unknown parent') ) if not self.index.has_node(deltabase): raise error.LookupError( deltabase, self.indexfile, _(b'unknown delta base') ) baserev = self.rev(deltabase) if baserev != nullrev and self.iscensored(baserev): # if base is censored, delta must be full replacement in a # single patch operation hlen = struct.calcsize(b">lll") oldlen = self.rawsize(baserev) newlen = len(delta) - hlen if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen): raise error.CensoredBaseError( self.indexfile, self.node(baserev) ) if not flags and self._peek_iscensored(baserev, delta, flush): flags |= REVIDX_ISCENSORED # We assume consumers of addrevisioncb will want to retrieve # the added revision, which will require a call to # revision(). revision() will fast path if there is a cache # hit. So, we tell _addrevision() to always cache in this case. # We're only using addgroup() in the context of changegroup # generation so the revision data can always be handled as raw # by the flagprocessor. rev = self._addrevision( node, None, transaction, link, p1, p2, flags, (baserev, delta), ifh, dfh, alwayscache=alwayscache, deltacomputer=deltacomputer, sidedata=sidedata, ) if addrevisioncb: addrevisioncb(self, rev) empty = False if not dfh and not self._inline: # addrevision switched from inline to conventional # reopen the index ifh.close() dfh = self._datafp(b"a+") ifh = self._indexfp(b"a+") self._writinghandles = (ifh, dfh) finally: self._writinghandles = None if dfh: dfh.close() ifh.close() return not empty def iscensored(self, rev): """Check if a file revision is censored.""" if not self._censorable: return False return self.flags(rev) & REVIDX_ISCENSORED def _peek_iscensored(self, baserev, delta, flush): """Quickly check if a delta produces a censored revision.""" if not self._censorable: return False return storageutil.deltaiscensored(delta, baserev, self.rawsize) def getstrippoint(self, minlink): """find the minimum rev that must be stripped to strip the linkrev Returns a tuple containing the minimum rev and a set of all revs that have linkrevs that will be broken by this strip. """ return storageutil.resolvestripinfo( minlink, len(self) - 1, self.headrevs(), self.linkrev, self.parentrevs, ) def strip(self, minlink, transaction): """truncate the revlog on the first revision with a linkrev >= minlink This function is called when we're stripping revision minlink and its descendants from the repository. We have to remove all revisions with linkrev >= minlink, because the equivalent changelog revisions will be renumbered after the strip. So we truncate the revlog on the first of these revisions, and trust that the caller has saved the revisions that shouldn't be removed and that it'll re-add them after this truncation. """ if len(self) == 0: return rev, _ = self.getstrippoint(minlink) if rev == len(self): return # first truncate the files on disk end = self.start(rev) if not self._inline: transaction.add(self.datafile, end) end = rev * self.index.entry_size else: end += rev * self.index.entry_size transaction.add(self.indexfile, end) # then reset internal state in memory to forget those revisions self._revisioncache = None self._chaininfocache = util.lrucachedict(500) self._chunkclear() del self.index[rev:-1] def checksize(self): """Check size of index and data files return a (dd, di) tuple. - dd: extra bytes for the "data" file - di: extra bytes for the "index" file A healthy revlog will return (0, 0). """ expected = 0 if len(self): expected = max(0, self.end(len(self) - 1)) try: with self._datafp() as f: f.seek(0, io.SEEK_END) actual = f.tell() dd = actual - expected except IOError as inst: if inst.errno != errno.ENOENT: raise dd = 0 try: f = self.opener(self.indexfile) f.seek(0, io.SEEK_END) actual = f.tell() f.close() s = self.index.entry_size i = max(0, actual // s) di = actual - (i * s) if self._inline: databytes = 0 for r in self: databytes += max(0, self.length(r)) dd = 0 di = actual - len(self) * s - databytes except IOError as inst: if inst.errno != errno.ENOENT: raise di = 0 return (dd, di) def files(self): res = [self.indexfile] if not self._inline: res.append(self.datafile) return res def emitrevisions( self, nodes, nodesorder=None, revisiondata=False, assumehaveparentrevisions=False, deltamode=repository.CG_DELTAMODE_STD, sidedata_helpers=None, ): if nodesorder not in (b'nodes', b'storage', b'linear', None): raise error.ProgrammingError( b'unhandled value for nodesorder: %s' % nodesorder ) if nodesorder is None and not self._generaldelta: nodesorder = b'storage' if ( not self._storedeltachains and deltamode != repository.CG_DELTAMODE_PREV ): deltamode = repository.CG_DELTAMODE_FULL return storageutil.emitrevisions( self, nodes, nodesorder, revlogrevisiondelta, deltaparentfn=self.deltaparent, candeltafn=self.candelta, rawsizefn=self.rawsize, revdifffn=self.revdiff, flagsfn=self.flags, deltamode=deltamode, revisiondata=revisiondata, assumehaveparentrevisions=assumehaveparentrevisions, sidedata_helpers=sidedata_helpers, ) DELTAREUSEALWAYS = b'always' DELTAREUSESAMEREVS = b'samerevs' DELTAREUSENEVER = b'never' DELTAREUSEFULLADD = b'fulladd' DELTAREUSEALL = {b'always', b'samerevs', b'never', b'fulladd'} def clone( self, tr, destrevlog, addrevisioncb=None, deltareuse=DELTAREUSESAMEREVS, forcedeltabothparents=None, sidedatacompanion=None, ): """Copy this revlog to another, possibly with format changes. The destination revlog will contain the same revisions and nodes. However, it may not be bit-for-bit identical due to e.g. delta encoding differences. The ``deltareuse`` argument control how deltas from the existing revlog are preserved in the destination revlog. The argument can have the following values: DELTAREUSEALWAYS Deltas will always be reused (if possible), even if the destination revlog would not select the same revisions for the delta. This is the fastest mode of operation. DELTAREUSESAMEREVS Deltas will be reused if the destination revlog would pick the same revisions for the delta. This mode strikes a balance between speed and optimization. DELTAREUSENEVER Deltas will never be reused. This is the slowest mode of execution. This mode can be used to recompute deltas (e.g. if the diff/delta algorithm changes). DELTAREUSEFULLADD Revision will be re-added as if their were new content. This is slower than DELTAREUSEALWAYS but allow more mechanism to kicks in. eg: large file detection and handling. Delta computation can be slow, so the choice of delta reuse policy can significantly affect run time. The default policy (``DELTAREUSESAMEREVS``) strikes a balance between two extremes. Deltas will be reused if they are appropriate. But if the delta could choose a better revision, it will do so. This means if you are converting a non-generaldelta revlog to a generaldelta revlog, deltas will be recomputed if the delta's parent isn't a parent of the revision. In addition to the delta policy, the ``forcedeltabothparents`` argument controls whether to force compute deltas against both parents for merges. By default, the current default is used. If not None, the `sidedatacompanion` is callable that accept two arguments: (srcrevlog, rev) and return a quintet that control changes to sidedata content from the old revision to the new clone result: (dropall, filterout, update, new_flags, dropped_flags) * if `dropall` is True, all sidedata should be dropped * `filterout` is a set of sidedata keys that should be dropped * `update` is a mapping of additionnal/new key -> value * new_flags is a bitfields of new flags that the revision should get * dropped_flags is a bitfields of new flags that the revision shoudl not longer have """ if deltareuse not in self.DELTAREUSEALL: raise ValueError( _(b'value for deltareuse invalid: %s') % deltareuse ) if len(destrevlog): raise ValueError(_(b'destination revlog is not empty')) if getattr(self, 'filteredrevs', None): raise ValueError(_(b'source revlog has filtered revisions')) if getattr(destrevlog, 'filteredrevs', None): raise ValueError(_(b'destination revlog has filtered revisions')) # lazydelta and lazydeltabase controls whether to reuse a cached delta, # if possible. oldlazydelta = destrevlog._lazydelta oldlazydeltabase = destrevlog._lazydeltabase oldamd = destrevlog._deltabothparents try: if deltareuse == self.DELTAREUSEALWAYS: destrevlog._lazydeltabase = True destrevlog._lazydelta = True elif deltareuse == self.DELTAREUSESAMEREVS: destrevlog._lazydeltabase = False destrevlog._lazydelta = True elif deltareuse == self.DELTAREUSENEVER: destrevlog._lazydeltabase = False destrevlog._lazydelta = False destrevlog._deltabothparents = forcedeltabothparents or oldamd self._clone( tr, destrevlog, addrevisioncb, deltareuse, forcedeltabothparents, sidedatacompanion, ) finally: destrevlog._lazydelta = oldlazydelta destrevlog._lazydeltabase = oldlazydeltabase destrevlog._deltabothparents = oldamd def _clone( self, tr, destrevlog, addrevisioncb, deltareuse, forcedeltabothparents, sidedatacompanion, ): """perform the core duty of `revlog.clone` after parameter processing""" deltacomputer = deltautil.deltacomputer(destrevlog) index = self.index for rev in self: entry = index[rev] # Some classes override linkrev to take filtered revs into # account. Use raw entry from index. flags = entry[0] & 0xFFFF linkrev = entry[4] p1 = index[entry[5]][7] p2 = index[entry[6]][7] node = entry[7] sidedataactions = (False, [], {}, 0, 0) if sidedatacompanion is not None: sidedataactions = sidedatacompanion(self, rev) # (Possibly) reuse the delta from the revlog if allowed and # the revlog chunk is a delta. cachedelta = None rawtext = None if any(sidedataactions) or deltareuse == self.DELTAREUSEFULLADD: dropall = sidedataactions[0] filterout = sidedataactions[1] update = sidedataactions[2] new_flags = sidedataactions[3] dropped_flags = sidedataactions[4] text, sidedata = self._revisiondata(rev) if dropall: sidedata = {} for key in filterout: sidedata.pop(key, None) sidedata.update(update) if not sidedata: sidedata = None flags |= new_flags flags &= ~dropped_flags destrevlog.addrevision( text, tr, linkrev, p1, p2, cachedelta=cachedelta, node=node, flags=flags, deltacomputer=deltacomputer, sidedata=sidedata, ) else: if destrevlog._lazydelta: dp = self.deltaparent(rev) if dp != nullrev: cachedelta = (dp, bytes(self._chunk(rev))) if not cachedelta: rawtext = self.rawdata(rev) ifh = destrevlog.opener( destrevlog.indexfile, b'a+', checkambig=False ) dfh = None if not destrevlog._inline: dfh = destrevlog.opener(destrevlog.datafile, b'a+') try: destrevlog._addrevision( node, rawtext, tr, linkrev, p1, p2, flags, cachedelta, ifh, dfh, deltacomputer=deltacomputer, ) finally: if dfh: dfh.close() ifh.close() if addrevisioncb: addrevisioncb(self, rev, node) def censorrevision(self, tr, censornode, tombstone=b''): if (self.version & 0xFFFF) == REVLOGV0: raise error.RevlogError( _(b'cannot censor with version %d revlogs') % self.version ) censorrev = self.rev(censornode) tombstone = storageutil.packmeta({b'censored': tombstone}, b'') if len(tombstone) > self.rawsize(censorrev): raise error.Abort( _(b'censor tombstone must be no longer than censored data') ) # Rewriting the revlog in place is hard. Our strategy for censoring is # to create a new revlog, copy all revisions to it, then replace the # revlogs on transaction close. newindexfile = self.indexfile + b'.tmpcensored' newdatafile = self.datafile + b'.tmpcensored' # This is a bit dangerous. We could easily have a mismatch of state. newrl = revlog(self.opener, newindexfile, newdatafile, censorable=True) newrl.version = self.version newrl._generaldelta = self._generaldelta newrl._io = self._io for rev in self.revs(): node = self.node(rev) p1, p2 = self.parents(node) if rev == censorrev: newrl.addrawrevision( tombstone, tr, self.linkrev(censorrev), p1, p2, censornode, REVIDX_ISCENSORED, ) if newrl.deltaparent(rev) != nullrev: raise error.Abort( _( b'censored revision stored as delta; ' b'cannot censor' ), hint=_( b'censoring of revlogs is not ' b'fully implemented; please report ' b'this bug' ), ) continue if self.iscensored(rev): if self.deltaparent(rev) != nullrev: raise error.Abort( _( b'cannot censor due to censored ' b'revision having delta stored' ) ) rawtext = self._chunk(rev) else: rawtext = self.rawdata(rev) newrl.addrawrevision( rawtext, tr, self.linkrev(rev), p1, p2, node, self.flags(rev) ) tr.addbackup(self.indexfile, location=b'store') if not self._inline: tr.addbackup(self.datafile, location=b'store') self.opener.rename(newrl.indexfile, self.indexfile) if not self._inline: self.opener.rename(newrl.datafile, self.datafile) self.clearcaches() self._loadindex() def verifyintegrity(self, state): """Verifies the integrity of the revlog. Yields ``revlogproblem`` instances describing problems that are found. """ dd, di = self.checksize() if dd: yield revlogproblem(error=_(b'data length off by %d bytes') % dd) if di: yield revlogproblem(error=_(b'index contains %d extra bytes') % di) version = self.version & 0xFFFF # The verifier tells us what version revlog we should be. if version != state[b'expectedversion']: yield revlogproblem( warning=_(b"warning: '%s' uses revlog format %d; expected %d") % (self.indexfile, version, state[b'expectedversion']) ) state[b'skipread'] = set() state[b'safe_renamed'] = set() for rev in self: node = self.node(rev) # Verify contents. 4 cases to care about: # # common: the most common case # rename: with a rename # meta: file content starts with b'\1\n', the metadata # header defined in filelog.py, but without a rename # ext: content stored externally # # More formally, their differences are shown below: # # | common | rename | meta | ext # ------------------------------------------------------- # flags() | 0 | 0 | 0 | not 0 # renamed() | False | True | False | ? # rawtext[0:2]=='\1\n'| False | True | True | ? # # "rawtext" means the raw text stored in revlog data, which # could be retrieved by "rawdata(rev)". "text" # mentioned below is "revision(rev)". # # There are 3 different lengths stored physically: # 1. L1: rawsize, stored in revlog index # 2. L2: len(rawtext), stored in revlog data # 3. L3: len(text), stored in revlog data if flags==0, or # possibly somewhere else if flags!=0 # # L1 should be equal to L2. L3 could be different from them. # "text" may or may not affect commit hash depending on flag # processors (see flagutil.addflagprocessor). # # | common | rename | meta | ext # ------------------------------------------------- # rawsize() | L1 | L1 | L1 | L1 # size() | L1 | L2-LM | L1(*) | L1 (?) # len(rawtext) | L2 | L2 | L2 | L2 # len(text) | L2 | L2 | L2 | L3 # len(read()) | L2 | L2-LM | L2-LM | L3 (?) # # LM: length of metadata, depending on rawtext # (*): not ideal, see comment in filelog.size # (?): could be "- len(meta)" if the resolved content has # rename metadata # # Checks needed to be done: # 1. length check: L1 == L2, in all cases. # 2. hash check: depending on flag processor, we may need to # use either "text" (external), or "rawtext" (in revlog). try: skipflags = state.get(b'skipflags', 0) if skipflags: skipflags &= self.flags(rev) _verify_revision(self, skipflags, state, node) l1 = self.rawsize(rev) l2 = len(self.rawdata(node)) if l1 != l2: yield revlogproblem( error=_(b'unpacked size is %d, %d expected') % (l2, l1), node=node, ) except error.CensoredNodeError: if state[b'erroroncensored']: yield revlogproblem( error=_(b'censored file data'), node=node ) state[b'skipread'].add(node) except Exception as e: yield revlogproblem( error=_(b'unpacking %s: %s') % (short(node), stringutil.forcebytestr(e)), node=node, ) state[b'skipread'].add(node) def storageinfo( self, exclusivefiles=False, sharedfiles=False, revisionscount=False, trackedsize=False, storedsize=False, ): d = {} if exclusivefiles: d[b'exclusivefiles'] = [(self.opener, self.indexfile)] if not self._inline: d[b'exclusivefiles'].append((self.opener, self.datafile)) if sharedfiles: d[b'sharedfiles'] = [] if revisionscount: d[b'revisionscount'] = len(self) if trackedsize: d[b'trackedsize'] = sum(map(self.rawsize, iter(self))) if storedsize: d[b'storedsize'] = sum( self.opener.stat(path).st_size for path in self.files() ) return d def rewrite_sidedata(self, helpers, startrev, endrev): if self.version & 0xFFFF != REVLOGV2: return # inline are not yet supported because they suffer from an issue when # rewriting them (since it's not an append-only operation). # See issue6485. assert not self._inline if not helpers[1] and not helpers[2]: # Nothing to generate or remove return new_entries = [] # append the new sidedata with self._datafp(b'a+') as fp: # Maybe this bug still exists, see revlog._writeentry fp.seek(0, os.SEEK_END) current_offset = fp.tell() for rev in range(startrev, endrev + 1): entry = self.index[rev] new_sidedata = storageutil.run_sidedata_helpers( store=self, sidedata_helpers=helpers, sidedata={}, rev=rev, ) serialized_sidedata = sidedatautil.serialize_sidedata( new_sidedata ) if entry[8] != 0 or entry[9] != 0: # rewriting entries that already have sidedata is not # supported yet, because it introduces garbage data in the # revlog. msg = b"Rewriting existing sidedata is not supported yet" raise error.Abort(msg) entry = entry[:8] entry += (current_offset, len(serialized_sidedata)) fp.write(serialized_sidedata) new_entries.append(entry) current_offset += len(serialized_sidedata) # rewrite the new index entries with self._indexfp(b'w+') as fp: fp.seek(startrev * self.index.entry_size) for i, entry in enumerate(new_entries): rev = startrev + i self.index.replace_sidedata_info(rev, entry[8], entry[9]) - packed = self._io.packentry(entry, self.node, self.version, rev) + packed = self.index.entry_binary(rev, self.version) fp.write(packed) diff --git a/rust/hg-cpython/src/revlog.rs b/rust/hg-cpython/src/revlog.rs --- a/rust/hg-cpython/src/revlog.rs +++ b/rust/hg-cpython/src/revlog.rs @@ -1,494 +1,499 @@ // revlog.rs // // Copyright 2019-2020 Georges Racinet // // This software may be used and distributed according to the terms of the // GNU General Public License version 2 or any later version. use crate::{ cindex, utils::{node_from_py_bytes, node_from_py_object}, }; use cpython::{ buffer::{Element, PyBuffer}, exc::{IndexError, ValueError}, ObjectProtocol, PyBytes, PyClone, PyDict, PyErr, PyInt, PyModule, PyObject, PyResult, PyString, PyTuple, Python, PythonObject, ToPyObject, }; use hg::{ nodemap::{Block, NodeMapError, NodeTree}, revlog::{nodemap::NodeMap, NodePrefix, RevlogIndex}, Revision, }; use std::cell::RefCell; /// Return a Struct implementing the Graph trait pub(crate) fn pyindex_to_graph( py: Python, index: PyObject, ) -> PyResult { match index.extract::(py) { Ok(midx) => Ok(midx.clone_cindex(py)), Err(_) => cindex::Index::new(py, index), } } py_class!(pub class MixedIndex |py| { data cindex: RefCell; data nt: RefCell>; data docket: RefCell>; // Holds a reference to the mmap'ed persistent nodemap data data mmap: RefCell>; def __new__(_cls, cindex: PyObject) -> PyResult { Self::new(py, cindex) } /// Compatibility layer used for Python consumers needing access to the C index /// /// Only use case so far is `scmutil.shortesthexnodeidprefix`, /// that may need to build a custom `nodetree`, based on a specified revset. /// With a Rust implementation of the nodemap, we will be able to get rid of /// this, by exposing our own standalone nodemap class, /// ready to accept `MixedIndex`. def get_cindex(&self) -> PyResult { Ok(self.cindex(py).borrow().inner().clone_ref(py)) } // Index API involving nodemap, as defined in mercurial/pure/parsers.py /// Return Revision if found, raises a bare `error.RevlogError` /// in case of ambiguity, same as C version does def get_rev(&self, node: PyBytes) -> PyResult> { let opt = self.get_nodetree(py)?.borrow(); let nt = opt.as_ref().unwrap(); let idx = &*self.cindex(py).borrow(); let node = node_from_py_bytes(py, &node)?; nt.find_bin(idx, node.into()).map_err(|e| nodemap_error(py, e)) } /// same as `get_rev()` but raises a bare `error.RevlogError` if node /// is not found. /// /// No need to repeat `node` in the exception, `mercurial/revlog.py` /// will catch and rewrap with it def rev(&self, node: PyBytes) -> PyResult { self.get_rev(py, node)?.ok_or_else(|| revlog_error(py)) } /// return True if the node exist in the index def has_node(&self, node: PyBytes) -> PyResult { self.get_rev(py, node).map(|opt| opt.is_some()) } /// find length of shortest hex nodeid of a binary ID def shortest(&self, node: PyBytes) -> PyResult { let opt = self.get_nodetree(py)?.borrow(); let nt = opt.as_ref().unwrap(); let idx = &*self.cindex(py).borrow(); match nt.unique_prefix_len_node(idx, &node_from_py_bytes(py, &node)?) { Ok(Some(l)) => Ok(l), Ok(None) => Err(revlog_error(py)), Err(e) => Err(nodemap_error(py, e)), } } def partialmatch(&self, node: PyObject) -> PyResult> { let opt = self.get_nodetree(py)?.borrow(); let nt = opt.as_ref().unwrap(); let idx = &*self.cindex(py).borrow(); let node_as_string = if cfg!(feature = "python3-sys") { node.cast_as::(py)?.to_string(py)?.to_string() } else { let node = node.extract::(py)?; String::from_utf8_lossy(node.data(py)).to_string() }; let prefix = NodePrefix::from_hex(&node_as_string).map_err(|_| PyErr::new::(py, "Invalid node or prefix"))?; nt.find_bin(idx, prefix) // TODO make an inner API returning the node directly .map(|opt| opt.map( |rev| PyBytes::new(py, idx.node(rev).unwrap().as_bytes()))) .map_err(|e| nodemap_error(py, e)) } /// append an index entry def append(&self, tup: PyTuple) -> PyResult { if tup.len(py) < 8 { // this is better than the panic promised by tup.get_item() return Err( PyErr::new::(py, "tuple index out of range")) } let node_bytes = tup.get_item(py, 7).extract(py)?; let node = node_from_py_object(py, &node_bytes)?; let mut idx = self.cindex(py).borrow_mut(); let rev = idx.len() as Revision; idx.append(py, tup)?; self.get_nodetree(py)?.borrow_mut().as_mut().unwrap() .insert(&*idx, &node, rev) .map_err(|e| nodemap_error(py, e))?; Ok(py.None()) } def __delitem__(&self, key: PyObject) -> PyResult<()> { // __delitem__ is both for `del idx[r]` and `del idx[r1:r2]` self.cindex(py).borrow().inner().del_item(py, key)?; let mut opt = self.get_nodetree(py)?.borrow_mut(); let mut nt = opt.as_mut().unwrap(); nt.invalidate_all(); self.fill_nodemap(py, &mut nt)?; Ok(()) } // // Reforwarded C index API // // index_methods (tp_methods). Same ordering as in revlog.c /// return the gca set of the given revs def ancestors(&self, *args, **kw) -> PyResult { self.call_cindex(py, "ancestors", args, kw) } /// return the heads of the common ancestors of the given revs def commonancestorsheads(&self, *args, **kw) -> PyResult { self.call_cindex(py, "commonancestorsheads", args, kw) } /// Clear the index caches and inner py_class data. /// It is Python's responsibility to call `update_nodemap_data` again. def clearcaches(&self, *args, **kw) -> PyResult { self.nt(py).borrow_mut().take(); self.docket(py).borrow_mut().take(); self.mmap(py).borrow_mut().take(); self.call_cindex(py, "clearcaches", args, kw) } + /// return the raw binary string representing a revision + def entry_binary(&self, *args, **kw) -> PyResult { + self.call_cindex(py, "entry_binary", args, kw) + } + /// get an index entry def get(&self, *args, **kw) -> PyResult { self.call_cindex(py, "get", args, kw) } /// compute phases def computephasesmapsets(&self, *args, **kw) -> PyResult { self.call_cindex(py, "computephasesmapsets", args, kw) } /// reachableroots def reachableroots2(&self, *args, **kw) -> PyResult { self.call_cindex(py, "reachableroots2", args, kw) } /// get head revisions def headrevs(&self, *args, **kw) -> PyResult { self.call_cindex(py, "headrevs", args, kw) } /// get filtered head revisions def headrevsfiltered(&self, *args, **kw) -> PyResult { self.call_cindex(py, "headrevsfiltered", args, kw) } /// True if the object is a snapshot def issnapshot(&self, *args, **kw) -> PyResult { self.call_cindex(py, "issnapshot", args, kw) } /// Gather snapshot data in a cache dict def findsnapshots(&self, *args, **kw) -> PyResult { self.call_cindex(py, "findsnapshots", args, kw) } /// determine revisions with deltas to reconstruct fulltext def deltachain(&self, *args, **kw) -> PyResult { self.call_cindex(py, "deltachain", args, kw) } /// slice planned chunk read to reach a density threshold def slicechunktodensity(&self, *args, **kw) -> PyResult { self.call_cindex(py, "slicechunktodensity", args, kw) } /// stats for the index def stats(&self, *args, **kw) -> PyResult { self.call_cindex(py, "stats", args, kw) } // index_sequence_methods and index_mapping_methods. // // Since we call back through the high level Python API, // there's no point making a distinction between index_get // and index_getitem. def __len__(&self) -> PyResult { self.cindex(py).borrow().inner().len(py) } def __getitem__(&self, key: PyObject) -> PyResult { // this conversion seems needless, but that's actually because // `index_getitem` does not handle conversion from PyLong, // which expressions such as [e for e in index] internally use. // Note that we don't seem to have a direct way to call // PySequence_GetItem (does the job), which would possibly be better // for performance let key = match key.extract::(py) { Ok(rev) => rev.to_py_object(py).into_object(), Err(_) => key, }; self.cindex(py).borrow().inner().get_item(py, key) } def __setitem__(&self, key: PyObject, value: PyObject) -> PyResult<()> { self.cindex(py).borrow().inner().set_item(py, key, value) } def __contains__(&self, item: PyObject) -> PyResult { // ObjectProtocol does not seem to provide contains(), so // this is an equivalent implementation of the index_contains() // defined in revlog.c let cindex = self.cindex(py).borrow(); match item.extract::(py) { Ok(rev) => { Ok(rev >= -1 && rev < cindex.inner().len(py)? as Revision) } Err(_) => { cindex.inner().call_method( py, "has_node", PyTuple::new(py, &[item]), None)? .extract(py) } } } def nodemap_data_all(&self) -> PyResult { self.inner_nodemap_data_all(py) } def nodemap_data_incremental(&self) -> PyResult { self.inner_nodemap_data_incremental(py) } def update_nodemap_data( &self, docket: PyObject, nm_data: PyObject ) -> PyResult { self.inner_update_nodemap_data(py, docket, nm_data) } @property def entry_size(&self) -> PyResult { self.cindex(py).borrow().inner().getattr(py, "entry_size")?.extract::(py) } }); impl MixedIndex { fn new(py: Python, cindex: PyObject) -> PyResult { Self::create_instance( py, RefCell::new(cindex::Index::new(py, cindex)?), RefCell::new(None), RefCell::new(None), RefCell::new(None), ) } /// This is scaffolding at this point, but it could also become /// a way to start a persistent nodemap or perform a /// vacuum / repack operation fn fill_nodemap( &self, py: Python, nt: &mut NodeTree, ) -> PyResult { let index = self.cindex(py).borrow(); for r in 0..index.len() { let rev = r as Revision; // in this case node() won't ever return None nt.insert(&*index, index.node(rev).unwrap(), rev) .map_err(|e| nodemap_error(py, e))? } Ok(py.None()) } fn get_nodetree<'a>( &'a self, py: Python<'a>, ) -> PyResult<&'a RefCell>> { if self.nt(py).borrow().is_none() { let readonly = Box::new(Vec::new()); let mut nt = NodeTree::load_bytes(readonly, 0); self.fill_nodemap(py, &mut nt)?; self.nt(py).borrow_mut().replace(nt); } Ok(self.nt(py)) } /// forward a method call to the underlying C index fn call_cindex( &self, py: Python, name: &str, args: &PyTuple, kwargs: Option<&PyDict>, ) -> PyResult { self.cindex(py) .borrow() .inner() .call_method(py, name, args, kwargs) } pub fn clone_cindex(&self, py: Python) -> cindex::Index { self.cindex(py).borrow().clone_ref(py) } /// Returns the full nodemap bytes to be written as-is to disk fn inner_nodemap_data_all(&self, py: Python) -> PyResult { let nodemap = self.get_nodetree(py)?.borrow_mut().take().unwrap(); let (readonly, bytes) = nodemap.into_readonly_and_added_bytes(); // If there's anything readonly, we need to build the data again from // scratch let bytes = if readonly.len() > 0 { let mut nt = NodeTree::load_bytes(Box::new(vec![]), 0); self.fill_nodemap(py, &mut nt)?; let (readonly, bytes) = nt.into_readonly_and_added_bytes(); assert_eq!(readonly.len(), 0); bytes } else { bytes }; let bytes = PyBytes::new(py, &bytes); Ok(bytes) } /// Returns the last saved docket along with the size of any changed data /// (in number of blocks), and said data as bytes. fn inner_nodemap_data_incremental( &self, py: Python, ) -> PyResult { let docket = self.docket(py).borrow(); let docket = match docket.as_ref() { Some(d) => d, None => return Ok(py.None()), }; let node_tree = self.get_nodetree(py)?.borrow_mut().take().unwrap(); let masked_blocks = node_tree.masked_readonly_blocks(); let (_, data) = node_tree.into_readonly_and_added_bytes(); let changed = masked_blocks * std::mem::size_of::(); Ok((docket, changed, PyBytes::new(py, &data)) .to_py_object(py) .into_object()) } /// Update the nodemap from the new (mmaped) data. /// The docket is kept as a reference for later incremental calls. fn inner_update_nodemap_data( &self, py: Python, docket: PyObject, nm_data: PyObject, ) -> PyResult { let buf = PyBuffer::get(py, &nm_data)?; let len = buf.item_count(); // Build a slice from the mmap'ed buffer data let cbuf = buf.buf_ptr(); let bytes = if std::mem::size_of::() == buf.item_size() && buf.is_c_contiguous() && u8::is_compatible_format(buf.format()) { unsafe { std::slice::from_raw_parts(cbuf as *const u8, len) } } else { return Err(PyErr::new::( py, "Nodemap data buffer has an invalid memory representation" .to_string(), )); }; // Keep a reference to the mmap'ed buffer, otherwise we get a dangling // pointer. self.mmap(py).borrow_mut().replace(buf); let mut nt = NodeTree::load_bytes(Box::new(bytes), len); let data_tip = docket.getattr(py, "tip_rev")?.extract::(py)?; self.docket(py).borrow_mut().replace(docket.clone_ref(py)); let idx = self.cindex(py).borrow(); let current_tip = idx.len(); for r in (data_tip + 1)..current_tip as Revision { let rev = r as Revision; // in this case node() won't ever return None nt.insert(&*idx, idx.node(rev).unwrap(), rev) .map_err(|e| nodemap_error(py, e))? } *self.nt(py).borrow_mut() = Some(nt); Ok(py.None()) } } fn revlog_error(py: Python) -> PyErr { match py .import("mercurial.error") .and_then(|m| m.get(py, "RevlogError")) { Err(e) => e, Ok(cls) => PyErr::from_instance(py, cls), } } fn rev_not_in_index(py: Python, rev: Revision) -> PyErr { PyErr::new::( py, format!( "Inconsistency: Revision {} found in nodemap \ is not in revlog index", rev ), ) } /// Standard treatment of NodeMapError fn nodemap_error(py: Python, err: NodeMapError) -> PyErr { match err { NodeMapError::MultipleResults => revlog_error(py), NodeMapError::RevisionNotInIndex(r) => rev_not_in_index(py, r), } } /// Create the module, with __package__ given from parent pub fn init_module(py: Python, package: &str) -> PyResult { let dotted_name = &format!("{}.revlog", package); let m = PyModule::new(py, dotted_name)?; m.add(py, "__package__", package)?; m.add(py, "__doc__", "RevLog - Rust implementations")?; m.add_class::(py)?; let sys = PyModule::import(py, "sys")?; let sys_modules: PyDict = sys.get(py, "modules")?.extract(py)?; sys_modules.set_item(py, dotted_name, &m)?; Ok(m) }