##// END OF EJS Templates
parsers: avoid leak of nonnset and otherpset...
Augie Fackler -
r31291:fffd1abb default
parent child Browse files
Show More
@@ -1,2966 +1,2968
1 /*
1 /*
2 parsers.c - efficient content parsing
2 parsers.c - efficient content parsing
3
3
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
5
5
6 This software may be used and distributed according to the terms of
6 This software may be used and distributed according to the terms of
7 the GNU General Public License, incorporated herein by reference.
7 the GNU General Public License, incorporated herein by reference.
8 */
8 */
9
9
10 #include <Python.h>
10 #include <Python.h>
11 #include <ctype.h>
11 #include <ctype.h>
12 #include <stddef.h>
12 #include <stddef.h>
13 #include <string.h>
13 #include <string.h>
14
14
15 #include "util.h"
15 #include "util.h"
16 #include "bitmanipulation.h"
16 #include "bitmanipulation.h"
17
17
18 #ifdef IS_PY3K
18 #ifdef IS_PY3K
19 /* The mapping of Python types is meant to be temporary to get Python
19 /* The mapping of Python types is meant to be temporary to get Python
20 * 3 to compile. We should remove this once Python 3 support is fully
20 * 3 to compile. We should remove this once Python 3 support is fully
21 * supported and proper types are used in the extensions themselves. */
21 * supported and proper types are used in the extensions themselves. */
22 #define PyInt_Type PyLong_Type
22 #define PyInt_Type PyLong_Type
23 #define PyInt_Check PyLong_Check
23 #define PyInt_Check PyLong_Check
24 #define PyInt_FromLong PyLong_FromLong
24 #define PyInt_FromLong PyLong_FromLong
25 #define PyInt_FromSsize_t PyLong_FromSsize_t
25 #define PyInt_FromSsize_t PyLong_FromSsize_t
26 #define PyInt_AS_LONG PyLong_AS_LONG
26 #define PyInt_AS_LONG PyLong_AS_LONG
27 #define PyInt_AsLong PyLong_AsLong
27 #define PyInt_AsLong PyLong_AsLong
28 #endif
28 #endif
29
29
30 static char *versionerrortext = "Python minor version mismatch";
30 static char *versionerrortext = "Python minor version mismatch";
31
31
32 static int8_t hextable[256] = {
32 static int8_t hextable[256] = {
33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0-9 */
36 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0-9 */
37 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A-F */
37 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A-F */
38 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
39 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a-f */
39 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a-f */
40 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
40 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
41 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
41 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
42 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
42 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
43 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
43 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
44 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
44 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
45 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
45 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
46 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
46 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
48 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
48 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
49 };
49 };
50
50
51 static char lowertable[128] = {
51 static char lowertable[128] = {
52 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
52 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
53 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
53 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
54 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
54 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
55 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
55 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
56 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
56 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
57 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
57 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
58 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
58 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
59 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
59 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
60 '\x40',
60 '\x40',
61 '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', /* A-G */
61 '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', /* A-G */
62 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', /* H-O */
62 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', /* H-O */
63 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', /* P-W */
63 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', /* P-W */
64 '\x78', '\x79', '\x7a', /* X-Z */
64 '\x78', '\x79', '\x7a', /* X-Z */
65 '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
65 '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
66 '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
66 '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
67 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
67 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
68 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
68 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
69 '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
69 '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
70 };
70 };
71
71
72 static char uppertable[128] = {
72 static char uppertable[128] = {
73 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
73 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
74 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
74 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
75 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
75 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
76 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
76 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
77 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
77 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
78 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
78 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
79 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
79 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
80 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
80 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
81 '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
81 '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
82 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
82 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
83 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
83 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
84 '\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
84 '\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
85 '\x60',
85 '\x60',
86 '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', /* a-g */
86 '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', /* a-g */
87 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', /* h-o */
87 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', /* h-o */
88 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', /* p-w */
88 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', /* p-w */
89 '\x58', '\x59', '\x5a', /* x-z */
89 '\x58', '\x59', '\x5a', /* x-z */
90 '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
90 '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
91 };
91 };
92
92
93 static inline int hexdigit(const char *p, Py_ssize_t off)
93 static inline int hexdigit(const char *p, Py_ssize_t off)
94 {
94 {
95 int8_t val = hextable[(unsigned char)p[off]];
95 int8_t val = hextable[(unsigned char)p[off]];
96
96
97 if (val >= 0) {
97 if (val >= 0) {
98 return val;
98 return val;
99 }
99 }
100
100
101 PyErr_SetString(PyExc_ValueError, "input contains non-hex character");
101 PyErr_SetString(PyExc_ValueError, "input contains non-hex character");
102 return 0;
102 return 0;
103 }
103 }
104
104
105 /*
105 /*
106 * Turn a hex-encoded string into binary.
106 * Turn a hex-encoded string into binary.
107 */
107 */
108 PyObject *unhexlify(const char *str, int len)
108 PyObject *unhexlify(const char *str, int len)
109 {
109 {
110 PyObject *ret;
110 PyObject *ret;
111 char *d;
111 char *d;
112 int i;
112 int i;
113
113
114 ret = PyBytes_FromStringAndSize(NULL, len / 2);
114 ret = PyBytes_FromStringAndSize(NULL, len / 2);
115
115
116 if (!ret)
116 if (!ret)
117 return NULL;
117 return NULL;
118
118
119 d = PyBytes_AsString(ret);
119 d = PyBytes_AsString(ret);
120
120
121 for (i = 0; i < len;) {
121 for (i = 0; i < len;) {
122 int hi = hexdigit(str, i++);
122 int hi = hexdigit(str, i++);
123 int lo = hexdigit(str, i++);
123 int lo = hexdigit(str, i++);
124 *d++ = (hi << 4) | lo;
124 *d++ = (hi << 4) | lo;
125 }
125 }
126
126
127 return ret;
127 return ret;
128 }
128 }
129
129
130 static inline PyObject *_asciitransform(PyObject *str_obj,
130 static inline PyObject *_asciitransform(PyObject *str_obj,
131 const char table[128],
131 const char table[128],
132 PyObject *fallback_fn)
132 PyObject *fallback_fn)
133 {
133 {
134 char *str, *newstr;
134 char *str, *newstr;
135 Py_ssize_t i, len;
135 Py_ssize_t i, len;
136 PyObject *newobj = NULL;
136 PyObject *newobj = NULL;
137 PyObject *ret = NULL;
137 PyObject *ret = NULL;
138
138
139 str = PyBytes_AS_STRING(str_obj);
139 str = PyBytes_AS_STRING(str_obj);
140 len = PyBytes_GET_SIZE(str_obj);
140 len = PyBytes_GET_SIZE(str_obj);
141
141
142 newobj = PyBytes_FromStringAndSize(NULL, len);
142 newobj = PyBytes_FromStringAndSize(NULL, len);
143 if (!newobj)
143 if (!newobj)
144 goto quit;
144 goto quit;
145
145
146 newstr = PyBytes_AS_STRING(newobj);
146 newstr = PyBytes_AS_STRING(newobj);
147
147
148 for (i = 0; i < len; i++) {
148 for (i = 0; i < len; i++) {
149 char c = str[i];
149 char c = str[i];
150 if (c & 0x80) {
150 if (c & 0x80) {
151 if (fallback_fn != NULL) {
151 if (fallback_fn != NULL) {
152 ret = PyObject_CallFunctionObjArgs(fallback_fn,
152 ret = PyObject_CallFunctionObjArgs(fallback_fn,
153 str_obj, NULL);
153 str_obj, NULL);
154 } else {
154 } else {
155 PyObject *err = PyUnicodeDecodeError_Create(
155 PyObject *err = PyUnicodeDecodeError_Create(
156 "ascii", str, len, i, (i + 1),
156 "ascii", str, len, i, (i + 1),
157 "unexpected code byte");
157 "unexpected code byte");
158 PyErr_SetObject(PyExc_UnicodeDecodeError, err);
158 PyErr_SetObject(PyExc_UnicodeDecodeError, err);
159 Py_XDECREF(err);
159 Py_XDECREF(err);
160 }
160 }
161 goto quit;
161 goto quit;
162 }
162 }
163 newstr[i] = table[(unsigned char)c];
163 newstr[i] = table[(unsigned char)c];
164 }
164 }
165
165
166 ret = newobj;
166 ret = newobj;
167 Py_INCREF(ret);
167 Py_INCREF(ret);
168 quit:
168 quit:
169 Py_XDECREF(newobj);
169 Py_XDECREF(newobj);
170 return ret;
170 return ret;
171 }
171 }
172
172
173 static PyObject *asciilower(PyObject *self, PyObject *args)
173 static PyObject *asciilower(PyObject *self, PyObject *args)
174 {
174 {
175 PyObject *str_obj;
175 PyObject *str_obj;
176 if (!PyArg_ParseTuple(args, "O!:asciilower", &PyBytes_Type, &str_obj))
176 if (!PyArg_ParseTuple(args, "O!:asciilower", &PyBytes_Type, &str_obj))
177 return NULL;
177 return NULL;
178 return _asciitransform(str_obj, lowertable, NULL);
178 return _asciitransform(str_obj, lowertable, NULL);
179 }
179 }
180
180
181 static PyObject *asciiupper(PyObject *self, PyObject *args)
181 static PyObject *asciiupper(PyObject *self, PyObject *args)
182 {
182 {
183 PyObject *str_obj;
183 PyObject *str_obj;
184 if (!PyArg_ParseTuple(args, "O!:asciiupper", &PyBytes_Type, &str_obj))
184 if (!PyArg_ParseTuple(args, "O!:asciiupper", &PyBytes_Type, &str_obj))
185 return NULL;
185 return NULL;
186 return _asciitransform(str_obj, uppertable, NULL);
186 return _asciitransform(str_obj, uppertable, NULL);
187 }
187 }
188
188
189 static inline PyObject *_dict_new_presized(Py_ssize_t expected_size)
189 static inline PyObject *_dict_new_presized(Py_ssize_t expected_size)
190 {
190 {
191 /* _PyDict_NewPresized expects a minused parameter, but it actually
191 /* _PyDict_NewPresized expects a minused parameter, but it actually
192 creates a dictionary that's the nearest power of two bigger than the
192 creates a dictionary that's the nearest power of two bigger than the
193 parameter. For example, with the initial minused = 1000, the
193 parameter. For example, with the initial minused = 1000, the
194 dictionary created has size 1024. Of course in a lot of cases that
194 dictionary created has size 1024. Of course in a lot of cases that
195 can be greater than the maximum load factor Python's dict object
195 can be greater than the maximum load factor Python's dict object
196 expects (= 2/3), so as soon as we cross the threshold we'll resize
196 expects (= 2/3), so as soon as we cross the threshold we'll resize
197 anyway. So create a dictionary that's at least 3/2 the size. */
197 anyway. So create a dictionary that's at least 3/2 the size. */
198 return _PyDict_NewPresized(((1 + expected_size) / 2) * 3);
198 return _PyDict_NewPresized(((1 + expected_size) / 2) * 3);
199 }
199 }
200
200
201 static PyObject *dict_new_presized(PyObject *self, PyObject *args)
201 static PyObject *dict_new_presized(PyObject *self, PyObject *args)
202 {
202 {
203 Py_ssize_t expected_size;
203 Py_ssize_t expected_size;
204
204
205 if (!PyArg_ParseTuple(args, "n:make_presized_dict", &expected_size))
205 if (!PyArg_ParseTuple(args, "n:make_presized_dict", &expected_size))
206 return NULL;
206 return NULL;
207
207
208 return _dict_new_presized(expected_size);
208 return _dict_new_presized(expected_size);
209 }
209 }
210
210
211 static PyObject *make_file_foldmap(PyObject *self, PyObject *args)
211 static PyObject *make_file_foldmap(PyObject *self, PyObject *args)
212 {
212 {
213 PyObject *dmap, *spec_obj, *normcase_fallback;
213 PyObject *dmap, *spec_obj, *normcase_fallback;
214 PyObject *file_foldmap = NULL;
214 PyObject *file_foldmap = NULL;
215 enum normcase_spec spec;
215 enum normcase_spec spec;
216 PyObject *k, *v;
216 PyObject *k, *v;
217 dirstateTupleObject *tuple;
217 dirstateTupleObject *tuple;
218 Py_ssize_t pos = 0;
218 Py_ssize_t pos = 0;
219 const char *table;
219 const char *table;
220
220
221 if (!PyArg_ParseTuple(args, "O!O!O!:make_file_foldmap",
221 if (!PyArg_ParseTuple(args, "O!O!O!:make_file_foldmap",
222 &PyDict_Type, &dmap,
222 &PyDict_Type, &dmap,
223 &PyInt_Type, &spec_obj,
223 &PyInt_Type, &spec_obj,
224 &PyFunction_Type, &normcase_fallback))
224 &PyFunction_Type, &normcase_fallback))
225 goto quit;
225 goto quit;
226
226
227 spec = (int)PyInt_AS_LONG(spec_obj);
227 spec = (int)PyInt_AS_LONG(spec_obj);
228 switch (spec) {
228 switch (spec) {
229 case NORMCASE_LOWER:
229 case NORMCASE_LOWER:
230 table = lowertable;
230 table = lowertable;
231 break;
231 break;
232 case NORMCASE_UPPER:
232 case NORMCASE_UPPER:
233 table = uppertable;
233 table = uppertable;
234 break;
234 break;
235 case NORMCASE_OTHER:
235 case NORMCASE_OTHER:
236 table = NULL;
236 table = NULL;
237 break;
237 break;
238 default:
238 default:
239 PyErr_SetString(PyExc_TypeError, "invalid normcasespec");
239 PyErr_SetString(PyExc_TypeError, "invalid normcasespec");
240 goto quit;
240 goto quit;
241 }
241 }
242
242
243 /* Add some more entries to deal with additions outside this
243 /* Add some more entries to deal with additions outside this
244 function. */
244 function. */
245 file_foldmap = _dict_new_presized((PyDict_Size(dmap) / 10) * 11);
245 file_foldmap = _dict_new_presized((PyDict_Size(dmap) / 10) * 11);
246 if (file_foldmap == NULL)
246 if (file_foldmap == NULL)
247 goto quit;
247 goto quit;
248
248
249 while (PyDict_Next(dmap, &pos, &k, &v)) {
249 while (PyDict_Next(dmap, &pos, &k, &v)) {
250 if (!dirstate_tuple_check(v)) {
250 if (!dirstate_tuple_check(v)) {
251 PyErr_SetString(PyExc_TypeError,
251 PyErr_SetString(PyExc_TypeError,
252 "expected a dirstate tuple");
252 "expected a dirstate tuple");
253 goto quit;
253 goto quit;
254 }
254 }
255
255
256 tuple = (dirstateTupleObject *)v;
256 tuple = (dirstateTupleObject *)v;
257 if (tuple->state != 'r') {
257 if (tuple->state != 'r') {
258 PyObject *normed;
258 PyObject *normed;
259 if (table != NULL) {
259 if (table != NULL) {
260 normed = _asciitransform(k, table,
260 normed = _asciitransform(k, table,
261 normcase_fallback);
261 normcase_fallback);
262 } else {
262 } else {
263 normed = PyObject_CallFunctionObjArgs(
263 normed = PyObject_CallFunctionObjArgs(
264 normcase_fallback, k, NULL);
264 normcase_fallback, k, NULL);
265 }
265 }
266
266
267 if (normed == NULL)
267 if (normed == NULL)
268 goto quit;
268 goto quit;
269 if (PyDict_SetItem(file_foldmap, normed, k) == -1) {
269 if (PyDict_SetItem(file_foldmap, normed, k) == -1) {
270 Py_DECREF(normed);
270 Py_DECREF(normed);
271 goto quit;
271 goto quit;
272 }
272 }
273 Py_DECREF(normed);
273 Py_DECREF(normed);
274 }
274 }
275 }
275 }
276 return file_foldmap;
276 return file_foldmap;
277 quit:
277 quit:
278 Py_XDECREF(file_foldmap);
278 Py_XDECREF(file_foldmap);
279 return NULL;
279 return NULL;
280 }
280 }
281
281
282 /*
282 /*
283 * This code assumes that a manifest is stitched together with newline
283 * This code assumes that a manifest is stitched together with newline
284 * ('\n') characters.
284 * ('\n') characters.
285 */
285 */
286 static PyObject *parse_manifest(PyObject *self, PyObject *args)
286 static PyObject *parse_manifest(PyObject *self, PyObject *args)
287 {
287 {
288 PyObject *mfdict, *fdict;
288 PyObject *mfdict, *fdict;
289 char *str, *start, *end;
289 char *str, *start, *end;
290 int len;
290 int len;
291
291
292 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest",
292 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest",
293 &PyDict_Type, &mfdict,
293 &PyDict_Type, &mfdict,
294 &PyDict_Type, &fdict,
294 &PyDict_Type, &fdict,
295 &str, &len))
295 &str, &len))
296 goto quit;
296 goto quit;
297
297
298 start = str;
298 start = str;
299 end = str + len;
299 end = str + len;
300 while (start < end) {
300 while (start < end) {
301 PyObject *file = NULL, *node = NULL;
301 PyObject *file = NULL, *node = NULL;
302 PyObject *flags = NULL;
302 PyObject *flags = NULL;
303 char *zero = NULL, *newline = NULL;
303 char *zero = NULL, *newline = NULL;
304 ptrdiff_t nlen;
304 ptrdiff_t nlen;
305
305
306 zero = memchr(start, '\0', end - start);
306 zero = memchr(start, '\0', end - start);
307 if (!zero) {
307 if (!zero) {
308 PyErr_SetString(PyExc_ValueError,
308 PyErr_SetString(PyExc_ValueError,
309 "manifest entry has no separator");
309 "manifest entry has no separator");
310 goto quit;
310 goto quit;
311 }
311 }
312
312
313 newline = memchr(zero + 1, '\n', end - (zero + 1));
313 newline = memchr(zero + 1, '\n', end - (zero + 1));
314 if (!newline) {
314 if (!newline) {
315 PyErr_SetString(PyExc_ValueError,
315 PyErr_SetString(PyExc_ValueError,
316 "manifest contains trailing garbage");
316 "manifest contains trailing garbage");
317 goto quit;
317 goto quit;
318 }
318 }
319
319
320 file = PyBytes_FromStringAndSize(start, zero - start);
320 file = PyBytes_FromStringAndSize(start, zero - start);
321
321
322 if (!file)
322 if (!file)
323 goto bail;
323 goto bail;
324
324
325 nlen = newline - zero - 1;
325 nlen = newline - zero - 1;
326
326
327 node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen);
327 node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen);
328 if (!node)
328 if (!node)
329 goto bail;
329 goto bail;
330
330
331 if (nlen > 40) {
331 if (nlen > 40) {
332 flags = PyBytes_FromStringAndSize(zero + 41,
332 flags = PyBytes_FromStringAndSize(zero + 41,
333 nlen - 40);
333 nlen - 40);
334 if (!flags)
334 if (!flags)
335 goto bail;
335 goto bail;
336
336
337 if (PyDict_SetItem(fdict, file, flags) == -1)
337 if (PyDict_SetItem(fdict, file, flags) == -1)
338 goto bail;
338 goto bail;
339 }
339 }
340
340
341 if (PyDict_SetItem(mfdict, file, node) == -1)
341 if (PyDict_SetItem(mfdict, file, node) == -1)
342 goto bail;
342 goto bail;
343
343
344 start = newline + 1;
344 start = newline + 1;
345
345
346 Py_XDECREF(flags);
346 Py_XDECREF(flags);
347 Py_XDECREF(node);
347 Py_XDECREF(node);
348 Py_XDECREF(file);
348 Py_XDECREF(file);
349 continue;
349 continue;
350 bail:
350 bail:
351 Py_XDECREF(flags);
351 Py_XDECREF(flags);
352 Py_XDECREF(node);
352 Py_XDECREF(node);
353 Py_XDECREF(file);
353 Py_XDECREF(file);
354 goto quit;
354 goto quit;
355 }
355 }
356
356
357 Py_INCREF(Py_None);
357 Py_INCREF(Py_None);
358 return Py_None;
358 return Py_None;
359 quit:
359 quit:
360 return NULL;
360 return NULL;
361 }
361 }
362
362
363 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
363 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
364 int size, int mtime)
364 int size, int mtime)
365 {
365 {
366 dirstateTupleObject *t = PyObject_New(dirstateTupleObject,
366 dirstateTupleObject *t = PyObject_New(dirstateTupleObject,
367 &dirstateTupleType);
367 &dirstateTupleType);
368 if (!t)
368 if (!t)
369 return NULL;
369 return NULL;
370 t->state = state;
370 t->state = state;
371 t->mode = mode;
371 t->mode = mode;
372 t->size = size;
372 t->size = size;
373 t->mtime = mtime;
373 t->mtime = mtime;
374 return t;
374 return t;
375 }
375 }
376
376
377 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
377 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
378 PyObject *kwds)
378 PyObject *kwds)
379 {
379 {
380 /* We do all the initialization here and not a tp_init function because
380 /* We do all the initialization here and not a tp_init function because
381 * dirstate_tuple is immutable. */
381 * dirstate_tuple is immutable. */
382 dirstateTupleObject *t;
382 dirstateTupleObject *t;
383 char state;
383 char state;
384 int size, mode, mtime;
384 int size, mode, mtime;
385 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
385 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
386 return NULL;
386 return NULL;
387
387
388 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
388 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
389 if (!t)
389 if (!t)
390 return NULL;
390 return NULL;
391 t->state = state;
391 t->state = state;
392 t->mode = mode;
392 t->mode = mode;
393 t->size = size;
393 t->size = size;
394 t->mtime = mtime;
394 t->mtime = mtime;
395
395
396 return (PyObject *)t;
396 return (PyObject *)t;
397 }
397 }
398
398
399 static void dirstate_tuple_dealloc(PyObject *o)
399 static void dirstate_tuple_dealloc(PyObject *o)
400 {
400 {
401 PyObject_Del(o);
401 PyObject_Del(o);
402 }
402 }
403
403
404 static Py_ssize_t dirstate_tuple_length(PyObject *o)
404 static Py_ssize_t dirstate_tuple_length(PyObject *o)
405 {
405 {
406 return 4;
406 return 4;
407 }
407 }
408
408
409 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
409 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
410 {
410 {
411 dirstateTupleObject *t = (dirstateTupleObject *)o;
411 dirstateTupleObject *t = (dirstateTupleObject *)o;
412 switch (i) {
412 switch (i) {
413 case 0:
413 case 0:
414 return PyBytes_FromStringAndSize(&t->state, 1);
414 return PyBytes_FromStringAndSize(&t->state, 1);
415 case 1:
415 case 1:
416 return PyInt_FromLong(t->mode);
416 return PyInt_FromLong(t->mode);
417 case 2:
417 case 2:
418 return PyInt_FromLong(t->size);
418 return PyInt_FromLong(t->size);
419 case 3:
419 case 3:
420 return PyInt_FromLong(t->mtime);
420 return PyInt_FromLong(t->mtime);
421 default:
421 default:
422 PyErr_SetString(PyExc_IndexError, "index out of range");
422 PyErr_SetString(PyExc_IndexError, "index out of range");
423 return NULL;
423 return NULL;
424 }
424 }
425 }
425 }
426
426
427 static PySequenceMethods dirstate_tuple_sq = {
427 static PySequenceMethods dirstate_tuple_sq = {
428 dirstate_tuple_length, /* sq_length */
428 dirstate_tuple_length, /* sq_length */
429 0, /* sq_concat */
429 0, /* sq_concat */
430 0, /* sq_repeat */
430 0, /* sq_repeat */
431 dirstate_tuple_item, /* sq_item */
431 dirstate_tuple_item, /* sq_item */
432 0, /* sq_ass_item */
432 0, /* sq_ass_item */
433 0, /* sq_contains */
433 0, /* sq_contains */
434 0, /* sq_inplace_concat */
434 0, /* sq_inplace_concat */
435 0 /* sq_inplace_repeat */
435 0 /* sq_inplace_repeat */
436 };
436 };
437
437
438 PyTypeObject dirstateTupleType = {
438 PyTypeObject dirstateTupleType = {
439 PyVarObject_HEAD_INIT(NULL, 0)
439 PyVarObject_HEAD_INIT(NULL, 0)
440 "dirstate_tuple", /* tp_name */
440 "dirstate_tuple", /* tp_name */
441 sizeof(dirstateTupleObject),/* tp_basicsize */
441 sizeof(dirstateTupleObject),/* tp_basicsize */
442 0, /* tp_itemsize */
442 0, /* tp_itemsize */
443 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
443 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
444 0, /* tp_print */
444 0, /* tp_print */
445 0, /* tp_getattr */
445 0, /* tp_getattr */
446 0, /* tp_setattr */
446 0, /* tp_setattr */
447 0, /* tp_compare */
447 0, /* tp_compare */
448 0, /* tp_repr */
448 0, /* tp_repr */
449 0, /* tp_as_number */
449 0, /* tp_as_number */
450 &dirstate_tuple_sq, /* tp_as_sequence */
450 &dirstate_tuple_sq, /* tp_as_sequence */
451 0, /* tp_as_mapping */
451 0, /* tp_as_mapping */
452 0, /* tp_hash */
452 0, /* tp_hash */
453 0, /* tp_call */
453 0, /* tp_call */
454 0, /* tp_str */
454 0, /* tp_str */
455 0, /* tp_getattro */
455 0, /* tp_getattro */
456 0, /* tp_setattro */
456 0, /* tp_setattro */
457 0, /* tp_as_buffer */
457 0, /* tp_as_buffer */
458 Py_TPFLAGS_DEFAULT, /* tp_flags */
458 Py_TPFLAGS_DEFAULT, /* tp_flags */
459 "dirstate tuple", /* tp_doc */
459 "dirstate tuple", /* tp_doc */
460 0, /* tp_traverse */
460 0, /* tp_traverse */
461 0, /* tp_clear */
461 0, /* tp_clear */
462 0, /* tp_richcompare */
462 0, /* tp_richcompare */
463 0, /* tp_weaklistoffset */
463 0, /* tp_weaklistoffset */
464 0, /* tp_iter */
464 0, /* tp_iter */
465 0, /* tp_iternext */
465 0, /* tp_iternext */
466 0, /* tp_methods */
466 0, /* tp_methods */
467 0, /* tp_members */
467 0, /* tp_members */
468 0, /* tp_getset */
468 0, /* tp_getset */
469 0, /* tp_base */
469 0, /* tp_base */
470 0, /* tp_dict */
470 0, /* tp_dict */
471 0, /* tp_descr_get */
471 0, /* tp_descr_get */
472 0, /* tp_descr_set */
472 0, /* tp_descr_set */
473 0, /* tp_dictoffset */
473 0, /* tp_dictoffset */
474 0, /* tp_init */
474 0, /* tp_init */
475 0, /* tp_alloc */
475 0, /* tp_alloc */
476 dirstate_tuple_new, /* tp_new */
476 dirstate_tuple_new, /* tp_new */
477 };
477 };
478
478
479 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
479 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
480 {
480 {
481 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
481 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
482 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
482 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
483 char state, *cur, *str, *cpos;
483 char state, *cur, *str, *cpos;
484 int mode, size, mtime;
484 int mode, size, mtime;
485 unsigned int flen, len, pos = 40;
485 unsigned int flen, len, pos = 40;
486 int readlen;
486 int readlen;
487
487
488 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate",
488 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate",
489 &PyDict_Type, &dmap,
489 &PyDict_Type, &dmap,
490 &PyDict_Type, &cmap,
490 &PyDict_Type, &cmap,
491 &str, &readlen))
491 &str, &readlen))
492 goto quit;
492 goto quit;
493
493
494 len = readlen;
494 len = readlen;
495
495
496 /* read parents */
496 /* read parents */
497 if (len < 40) {
497 if (len < 40) {
498 PyErr_SetString(
498 PyErr_SetString(
499 PyExc_ValueError, "too little data for parents");
499 PyExc_ValueError, "too little data for parents");
500 goto quit;
500 goto quit;
501 }
501 }
502
502
503 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
503 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
504 if (!parents)
504 if (!parents)
505 goto quit;
505 goto quit;
506
506
507 /* read filenames */
507 /* read filenames */
508 while (pos >= 40 && pos < len) {
508 while (pos >= 40 && pos < len) {
509 if (pos + 17 > len) {
509 if (pos + 17 > len) {
510 PyErr_SetString(PyExc_ValueError,
510 PyErr_SetString(PyExc_ValueError,
511 "overflow in dirstate");
511 "overflow in dirstate");
512 goto quit;
512 goto quit;
513 }
513 }
514 cur = str + pos;
514 cur = str + pos;
515 /* unpack header */
515 /* unpack header */
516 state = *cur;
516 state = *cur;
517 mode = getbe32(cur + 1);
517 mode = getbe32(cur + 1);
518 size = getbe32(cur + 5);
518 size = getbe32(cur + 5);
519 mtime = getbe32(cur + 9);
519 mtime = getbe32(cur + 9);
520 flen = getbe32(cur + 13);
520 flen = getbe32(cur + 13);
521 pos += 17;
521 pos += 17;
522 cur += 17;
522 cur += 17;
523 if (flen > len - pos) {
523 if (flen > len - pos) {
524 PyErr_SetString(PyExc_ValueError, "overflow in dirstate");
524 PyErr_SetString(PyExc_ValueError, "overflow in dirstate");
525 goto quit;
525 goto quit;
526 }
526 }
527
527
528 entry = (PyObject *)make_dirstate_tuple(state, mode, size,
528 entry = (PyObject *)make_dirstate_tuple(state, mode, size,
529 mtime);
529 mtime);
530 cpos = memchr(cur, 0, flen);
530 cpos = memchr(cur, 0, flen);
531 if (cpos) {
531 if (cpos) {
532 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
532 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
533 cname = PyBytes_FromStringAndSize(cpos + 1,
533 cname = PyBytes_FromStringAndSize(cpos + 1,
534 flen - (cpos - cur) - 1);
534 flen - (cpos - cur) - 1);
535 if (!fname || !cname ||
535 if (!fname || !cname ||
536 PyDict_SetItem(cmap, fname, cname) == -1 ||
536 PyDict_SetItem(cmap, fname, cname) == -1 ||
537 PyDict_SetItem(dmap, fname, entry) == -1)
537 PyDict_SetItem(dmap, fname, entry) == -1)
538 goto quit;
538 goto quit;
539 Py_DECREF(cname);
539 Py_DECREF(cname);
540 } else {
540 } else {
541 fname = PyBytes_FromStringAndSize(cur, flen);
541 fname = PyBytes_FromStringAndSize(cur, flen);
542 if (!fname ||
542 if (!fname ||
543 PyDict_SetItem(dmap, fname, entry) == -1)
543 PyDict_SetItem(dmap, fname, entry) == -1)
544 goto quit;
544 goto quit;
545 }
545 }
546 Py_DECREF(fname);
546 Py_DECREF(fname);
547 Py_DECREF(entry);
547 Py_DECREF(entry);
548 fname = cname = entry = NULL;
548 fname = cname = entry = NULL;
549 pos += flen;
549 pos += flen;
550 }
550 }
551
551
552 ret = parents;
552 ret = parents;
553 Py_INCREF(ret);
553 Py_INCREF(ret);
554 quit:
554 quit:
555 Py_XDECREF(fname);
555 Py_XDECREF(fname);
556 Py_XDECREF(cname);
556 Py_XDECREF(cname);
557 Py_XDECREF(entry);
557 Py_XDECREF(entry);
558 Py_XDECREF(parents);
558 Py_XDECREF(parents);
559 return ret;
559 return ret;
560 }
560 }
561
561
562 /*
562 /*
563 * Build a set of non-normal and other parent entries from the dirstate dmap
563 * Build a set of non-normal and other parent entries from the dirstate dmap
564 */
564 */
565 static PyObject *nonnormalotherparententries(PyObject *self, PyObject *args) {
565 static PyObject *nonnormalotherparententries(PyObject *self, PyObject *args) {
566 PyObject *dmap, *fname, *v;
566 PyObject *dmap, *fname, *v;
567 PyObject *nonnset = NULL, *otherpset = NULL, *result = NULL;
567 PyObject *nonnset = NULL, *otherpset = NULL, *result = NULL;
568 Py_ssize_t pos;
568 Py_ssize_t pos;
569
569
570 if (!PyArg_ParseTuple(args, "O!:nonnormalentries",
570 if (!PyArg_ParseTuple(args, "O!:nonnormalentries",
571 &PyDict_Type, &dmap))
571 &PyDict_Type, &dmap))
572 goto bail;
572 goto bail;
573
573
574 nonnset = PySet_New(NULL);
574 nonnset = PySet_New(NULL);
575 if (nonnset == NULL)
575 if (nonnset == NULL)
576 goto bail;
576 goto bail;
577
577
578 otherpset = PySet_New(NULL);
578 otherpset = PySet_New(NULL);
579 if (otherpset == NULL)
579 if (otherpset == NULL)
580 goto bail;
580 goto bail;
581
581
582 pos = 0;
582 pos = 0;
583 while (PyDict_Next(dmap, &pos, &fname, &v)) {
583 while (PyDict_Next(dmap, &pos, &fname, &v)) {
584 dirstateTupleObject *t;
584 dirstateTupleObject *t;
585 if (!dirstate_tuple_check(v)) {
585 if (!dirstate_tuple_check(v)) {
586 PyErr_SetString(PyExc_TypeError,
586 PyErr_SetString(PyExc_TypeError,
587 "expected a dirstate tuple");
587 "expected a dirstate tuple");
588 goto bail;
588 goto bail;
589 }
589 }
590 t = (dirstateTupleObject *)v;
590 t = (dirstateTupleObject *)v;
591
591
592 if (t->state == 'n' && t->size == -2) {
592 if (t->state == 'n' && t->size == -2) {
593 if (PySet_Add(otherpset, fname) == -1) {
593 if (PySet_Add(otherpset, fname) == -1) {
594 goto bail;
594 goto bail;
595 }
595 }
596 }
596 }
597
597
598 if (t->state == 'n' && t->mtime != -1)
598 if (t->state == 'n' && t->mtime != -1)
599 continue;
599 continue;
600 if (PySet_Add(nonnset, fname) == -1)
600 if (PySet_Add(nonnset, fname) == -1)
601 goto bail;
601 goto bail;
602 }
602 }
603
603
604 result = Py_BuildValue("(OO)", nonnset, otherpset);
604 result = Py_BuildValue("(OO)", nonnset, otherpset);
605 if (result == NULL)
605 if (result == NULL)
606 goto bail;
606 goto bail;
607 Py_DECREF(nonnset);
608 Py_DECREF(otherpset);
607 return result;
609 return result;
608 bail:
610 bail:
609 Py_XDECREF(nonnset);
611 Py_XDECREF(nonnset);
610 Py_XDECREF(otherpset);
612 Py_XDECREF(otherpset);
611 Py_XDECREF(result);
613 Py_XDECREF(result);
612 return NULL;
614 return NULL;
613 }
615 }
614
616
615 /*
617 /*
616 * Build a set of non-normal entries from the dirstate dmap
618 * Build a set of non-normal entries from the dirstate dmap
617 */
619 */
618 static PyObject *nonnormalentries(PyObject *self, PyObject *args)
620 static PyObject *nonnormalentries(PyObject *self, PyObject *args)
619 {
621 {
620 PyObject *nonnset = NULL, *combined = NULL;
622 PyObject *nonnset = NULL, *combined = NULL;
621
623
622 combined = nonnormalotherparententries(self, args);
624 combined = nonnormalotherparententries(self, args);
623 if (!combined) {
625 if (!combined) {
624 return NULL;
626 return NULL;
625 }
627 }
626
628
627 nonnset = PyTuple_GetItem(combined, 0);
629 nonnset = PyTuple_GetItem(combined, 0);
628 if (!nonnset) {
630 if (!nonnset) {
629 Py_DECREF(combined);
631 Py_DECREF(combined);
630 return NULL;
632 return NULL;
631 }
633 }
632
634
633 Py_INCREF(nonnset);
635 Py_INCREF(nonnset);
634 Py_DECREF(combined);
636 Py_DECREF(combined);
635 return nonnset;
637 return nonnset;
636 }
638 }
637
639
638 /*
640 /*
639 * Efficiently pack a dirstate object into its on-disk format.
641 * Efficiently pack a dirstate object into its on-disk format.
640 */
642 */
641 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
643 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
642 {
644 {
643 PyObject *packobj = NULL;
645 PyObject *packobj = NULL;
644 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
646 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
645 Py_ssize_t nbytes, pos, l;
647 Py_ssize_t nbytes, pos, l;
646 PyObject *k, *v = NULL, *pn;
648 PyObject *k, *v = NULL, *pn;
647 char *p, *s;
649 char *p, *s;
648 int now;
650 int now;
649
651
650 if (!PyArg_ParseTuple(args, "O!O!Oi:pack_dirstate",
652 if (!PyArg_ParseTuple(args, "O!O!Oi:pack_dirstate",
651 &PyDict_Type, &map, &PyDict_Type, &copymap,
653 &PyDict_Type, &map, &PyDict_Type, &copymap,
652 &pl, &now))
654 &pl, &now))
653 return NULL;
655 return NULL;
654
656
655 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
657 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
656 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
658 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
657 return NULL;
659 return NULL;
658 }
660 }
659
661
660 /* Figure out how much we need to allocate. */
662 /* Figure out how much we need to allocate. */
661 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
663 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
662 PyObject *c;
664 PyObject *c;
663 if (!PyBytes_Check(k)) {
665 if (!PyBytes_Check(k)) {
664 PyErr_SetString(PyExc_TypeError, "expected string key");
666 PyErr_SetString(PyExc_TypeError, "expected string key");
665 goto bail;
667 goto bail;
666 }
668 }
667 nbytes += PyBytes_GET_SIZE(k) + 17;
669 nbytes += PyBytes_GET_SIZE(k) + 17;
668 c = PyDict_GetItem(copymap, k);
670 c = PyDict_GetItem(copymap, k);
669 if (c) {
671 if (c) {
670 if (!PyBytes_Check(c)) {
672 if (!PyBytes_Check(c)) {
671 PyErr_SetString(PyExc_TypeError,
673 PyErr_SetString(PyExc_TypeError,
672 "expected string key");
674 "expected string key");
673 goto bail;
675 goto bail;
674 }
676 }
675 nbytes += PyBytes_GET_SIZE(c) + 1;
677 nbytes += PyBytes_GET_SIZE(c) + 1;
676 }
678 }
677 }
679 }
678
680
679 packobj = PyBytes_FromStringAndSize(NULL, nbytes);
681 packobj = PyBytes_FromStringAndSize(NULL, nbytes);
680 if (packobj == NULL)
682 if (packobj == NULL)
681 goto bail;
683 goto bail;
682
684
683 p = PyBytes_AS_STRING(packobj);
685 p = PyBytes_AS_STRING(packobj);
684
686
685 pn = PySequence_ITEM(pl, 0);
687 pn = PySequence_ITEM(pl, 0);
686 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
688 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
687 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
689 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
688 goto bail;
690 goto bail;
689 }
691 }
690 memcpy(p, s, l);
692 memcpy(p, s, l);
691 p += 20;
693 p += 20;
692 pn = PySequence_ITEM(pl, 1);
694 pn = PySequence_ITEM(pl, 1);
693 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
695 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
694 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
696 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
695 goto bail;
697 goto bail;
696 }
698 }
697 memcpy(p, s, l);
699 memcpy(p, s, l);
698 p += 20;
700 p += 20;
699
701
700 for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) {
702 for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) {
701 dirstateTupleObject *tuple;
703 dirstateTupleObject *tuple;
702 char state;
704 char state;
703 int mode, size, mtime;
705 int mode, size, mtime;
704 Py_ssize_t len, l;
706 Py_ssize_t len, l;
705 PyObject *o;
707 PyObject *o;
706 char *t;
708 char *t;
707
709
708 if (!dirstate_tuple_check(v)) {
710 if (!dirstate_tuple_check(v)) {
709 PyErr_SetString(PyExc_TypeError,
711 PyErr_SetString(PyExc_TypeError,
710 "expected a dirstate tuple");
712 "expected a dirstate tuple");
711 goto bail;
713 goto bail;
712 }
714 }
713 tuple = (dirstateTupleObject *)v;
715 tuple = (dirstateTupleObject *)v;
714
716
715 state = tuple->state;
717 state = tuple->state;
716 mode = tuple->mode;
718 mode = tuple->mode;
717 size = tuple->size;
719 size = tuple->size;
718 mtime = tuple->mtime;
720 mtime = tuple->mtime;
719 if (state == 'n' && mtime == now) {
721 if (state == 'n' && mtime == now) {
720 /* See pure/parsers.py:pack_dirstate for why we do
722 /* See pure/parsers.py:pack_dirstate for why we do
721 * this. */
723 * this. */
722 mtime = -1;
724 mtime = -1;
723 mtime_unset = (PyObject *)make_dirstate_tuple(
725 mtime_unset = (PyObject *)make_dirstate_tuple(
724 state, mode, size, mtime);
726 state, mode, size, mtime);
725 if (!mtime_unset)
727 if (!mtime_unset)
726 goto bail;
728 goto bail;
727 if (PyDict_SetItem(map, k, mtime_unset) == -1)
729 if (PyDict_SetItem(map, k, mtime_unset) == -1)
728 goto bail;
730 goto bail;
729 Py_DECREF(mtime_unset);
731 Py_DECREF(mtime_unset);
730 mtime_unset = NULL;
732 mtime_unset = NULL;
731 }
733 }
732 *p++ = state;
734 *p++ = state;
733 putbe32((uint32_t)mode, p);
735 putbe32((uint32_t)mode, p);
734 putbe32((uint32_t)size, p + 4);
736 putbe32((uint32_t)size, p + 4);
735 putbe32((uint32_t)mtime, p + 8);
737 putbe32((uint32_t)mtime, p + 8);
736 t = p + 12;
738 t = p + 12;
737 p += 16;
739 p += 16;
738 len = PyBytes_GET_SIZE(k);
740 len = PyBytes_GET_SIZE(k);
739 memcpy(p, PyBytes_AS_STRING(k), len);
741 memcpy(p, PyBytes_AS_STRING(k), len);
740 p += len;
742 p += len;
741 o = PyDict_GetItem(copymap, k);
743 o = PyDict_GetItem(copymap, k);
742 if (o) {
744 if (o) {
743 *p++ = '\0';
745 *p++ = '\0';
744 l = PyBytes_GET_SIZE(o);
746 l = PyBytes_GET_SIZE(o);
745 memcpy(p, PyBytes_AS_STRING(o), l);
747 memcpy(p, PyBytes_AS_STRING(o), l);
746 p += l;
748 p += l;
747 len += l + 1;
749 len += l + 1;
748 }
750 }
749 putbe32((uint32_t)len, t);
751 putbe32((uint32_t)len, t);
750 }
752 }
751
753
752 pos = p - PyBytes_AS_STRING(packobj);
754 pos = p - PyBytes_AS_STRING(packobj);
753 if (pos != nbytes) {
755 if (pos != nbytes) {
754 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
756 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
755 (long)pos, (long)nbytes);
757 (long)pos, (long)nbytes);
756 goto bail;
758 goto bail;
757 }
759 }
758
760
759 return packobj;
761 return packobj;
760 bail:
762 bail:
761 Py_XDECREF(mtime_unset);
763 Py_XDECREF(mtime_unset);
762 Py_XDECREF(packobj);
764 Py_XDECREF(packobj);
763 Py_XDECREF(v);
765 Py_XDECREF(v);
764 return NULL;
766 return NULL;
765 }
767 }
766
768
767 /*
769 /*
768 * A base-16 trie for fast node->rev mapping.
770 * A base-16 trie for fast node->rev mapping.
769 *
771 *
770 * Positive value is index of the next node in the trie
772 * Positive value is index of the next node in the trie
771 * Negative value is a leaf: -(rev + 1)
773 * Negative value is a leaf: -(rev + 1)
772 * Zero is empty
774 * Zero is empty
773 */
775 */
774 typedef struct {
776 typedef struct {
775 int children[16];
777 int children[16];
776 } nodetree;
778 } nodetree;
777
779
778 /*
780 /*
779 * This class has two behaviors.
781 * This class has two behaviors.
780 *
782 *
781 * When used in a list-like way (with integer keys), we decode an
783 * When used in a list-like way (with integer keys), we decode an
782 * entry in a RevlogNG index file on demand. Our last entry is a
784 * entry in a RevlogNG index file on demand. Our last entry is a
783 * sentinel, always a nullid. We have limited support for
785 * sentinel, always a nullid. We have limited support for
784 * integer-keyed insert and delete, only at elements right before the
786 * integer-keyed insert and delete, only at elements right before the
785 * sentinel.
787 * sentinel.
786 *
788 *
787 * With string keys, we lazily perform a reverse mapping from node to
789 * With string keys, we lazily perform a reverse mapping from node to
788 * rev, using a base-16 trie.
790 * rev, using a base-16 trie.
789 */
791 */
790 typedef struct {
792 typedef struct {
791 PyObject_HEAD
793 PyObject_HEAD
792 /* Type-specific fields go here. */
794 /* Type-specific fields go here. */
793 PyObject *data; /* raw bytes of index */
795 PyObject *data; /* raw bytes of index */
794 Py_buffer buf; /* buffer of data */
796 Py_buffer buf; /* buffer of data */
795 PyObject **cache; /* cached tuples */
797 PyObject **cache; /* cached tuples */
796 const char **offsets; /* populated on demand */
798 const char **offsets; /* populated on demand */
797 Py_ssize_t raw_length; /* original number of elements */
799 Py_ssize_t raw_length; /* original number of elements */
798 Py_ssize_t length; /* current number of elements */
800 Py_ssize_t length; /* current number of elements */
799 PyObject *added; /* populated on demand */
801 PyObject *added; /* populated on demand */
800 PyObject *headrevs; /* cache, invalidated on changes */
802 PyObject *headrevs; /* cache, invalidated on changes */
801 PyObject *filteredrevs;/* filtered revs set */
803 PyObject *filteredrevs;/* filtered revs set */
802 nodetree *nt; /* base-16 trie */
804 nodetree *nt; /* base-16 trie */
803 unsigned ntlength; /* # nodes in use */
805 unsigned ntlength; /* # nodes in use */
804 unsigned ntcapacity; /* # nodes allocated */
806 unsigned ntcapacity; /* # nodes allocated */
805 int ntdepth; /* maximum depth of tree */
807 int ntdepth; /* maximum depth of tree */
806 int ntsplits; /* # splits performed */
808 int ntsplits; /* # splits performed */
807 int ntrev; /* last rev scanned */
809 int ntrev; /* last rev scanned */
808 int ntlookups; /* # lookups */
810 int ntlookups; /* # lookups */
809 int ntmisses; /* # lookups that miss the cache */
811 int ntmisses; /* # lookups that miss the cache */
810 int inlined;
812 int inlined;
811 } indexObject;
813 } indexObject;
812
814
813 static Py_ssize_t index_length(const indexObject *self)
815 static Py_ssize_t index_length(const indexObject *self)
814 {
816 {
815 if (self->added == NULL)
817 if (self->added == NULL)
816 return self->length;
818 return self->length;
817 return self->length + PyList_GET_SIZE(self->added);
819 return self->length + PyList_GET_SIZE(self->added);
818 }
820 }
819
821
820 static PyObject *nullentry;
822 static PyObject *nullentry;
821 static const char nullid[20];
823 static const char nullid[20];
822
824
823 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
825 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
824
826
825 #if LONG_MAX == 0x7fffffffL
827 #if LONG_MAX == 0x7fffffffL
826 static char *tuple_format = "Kiiiiiis#";
828 static char *tuple_format = "Kiiiiiis#";
827 #else
829 #else
828 static char *tuple_format = "kiiiiiis#";
830 static char *tuple_format = "kiiiiiis#";
829 #endif
831 #endif
830
832
831 /* A RevlogNG v1 index entry is 64 bytes long. */
833 /* A RevlogNG v1 index entry is 64 bytes long. */
832 static const long v1_hdrsize = 64;
834 static const long v1_hdrsize = 64;
833
835
834 /*
836 /*
835 * Return a pointer to the beginning of a RevlogNG record.
837 * Return a pointer to the beginning of a RevlogNG record.
836 */
838 */
837 static const char *index_deref(indexObject *self, Py_ssize_t pos)
839 static const char *index_deref(indexObject *self, Py_ssize_t pos)
838 {
840 {
839 if (self->inlined && pos > 0) {
841 if (self->inlined && pos > 0) {
840 if (self->offsets == NULL) {
842 if (self->offsets == NULL) {
841 self->offsets = malloc(self->raw_length *
843 self->offsets = malloc(self->raw_length *
842 sizeof(*self->offsets));
844 sizeof(*self->offsets));
843 if (self->offsets == NULL)
845 if (self->offsets == NULL)
844 return (const char *)PyErr_NoMemory();
846 return (const char *)PyErr_NoMemory();
845 inline_scan(self, self->offsets);
847 inline_scan(self, self->offsets);
846 }
848 }
847 return self->offsets[pos];
849 return self->offsets[pos];
848 }
850 }
849
851
850 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
852 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
851 }
853 }
852
854
853 static inline int index_get_parents(indexObject *self, Py_ssize_t rev,
855 static inline int index_get_parents(indexObject *self, Py_ssize_t rev,
854 int *ps, int maxrev)
856 int *ps, int maxrev)
855 {
857 {
856 if (rev >= self->length - 1) {
858 if (rev >= self->length - 1) {
857 PyObject *tuple = PyList_GET_ITEM(self->added,
859 PyObject *tuple = PyList_GET_ITEM(self->added,
858 rev - self->length + 1);
860 rev - self->length + 1);
859 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
861 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
860 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
862 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
861 } else {
863 } else {
862 const char *data = index_deref(self, rev);
864 const char *data = index_deref(self, rev);
863 ps[0] = getbe32(data + 24);
865 ps[0] = getbe32(data + 24);
864 ps[1] = getbe32(data + 28);
866 ps[1] = getbe32(data + 28);
865 }
867 }
866 /* If index file is corrupted, ps[] may point to invalid revisions. So
868 /* If index file is corrupted, ps[] may point to invalid revisions. So
867 * there is a risk of buffer overflow to trust them unconditionally. */
869 * there is a risk of buffer overflow to trust them unconditionally. */
868 if (ps[0] > maxrev || ps[1] > maxrev) {
870 if (ps[0] > maxrev || ps[1] > maxrev) {
869 PyErr_SetString(PyExc_ValueError, "parent out of range");
871 PyErr_SetString(PyExc_ValueError, "parent out of range");
870 return -1;
872 return -1;
871 }
873 }
872 return 0;
874 return 0;
873 }
875 }
874
876
875
877
876 /*
878 /*
877 * RevlogNG format (all in big endian, data may be inlined):
879 * RevlogNG format (all in big endian, data may be inlined):
878 * 6 bytes: offset
880 * 6 bytes: offset
879 * 2 bytes: flags
881 * 2 bytes: flags
880 * 4 bytes: compressed length
882 * 4 bytes: compressed length
881 * 4 bytes: uncompressed length
883 * 4 bytes: uncompressed length
882 * 4 bytes: base revision
884 * 4 bytes: base revision
883 * 4 bytes: link revision
885 * 4 bytes: link revision
884 * 4 bytes: parent 1 revision
886 * 4 bytes: parent 1 revision
885 * 4 bytes: parent 2 revision
887 * 4 bytes: parent 2 revision
886 * 32 bytes: nodeid (only 20 bytes used)
888 * 32 bytes: nodeid (only 20 bytes used)
887 */
889 */
888 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
890 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
889 {
891 {
890 uint64_t offset_flags;
892 uint64_t offset_flags;
891 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
893 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
892 const char *c_node_id;
894 const char *c_node_id;
893 const char *data;
895 const char *data;
894 Py_ssize_t length = index_length(self);
896 Py_ssize_t length = index_length(self);
895 PyObject *entry;
897 PyObject *entry;
896
898
897 if (pos < 0)
899 if (pos < 0)
898 pos += length;
900 pos += length;
899
901
900 if (pos < 0 || pos >= length) {
902 if (pos < 0 || pos >= length) {
901 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
903 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
902 return NULL;
904 return NULL;
903 }
905 }
904
906
905 if (pos == length - 1) {
907 if (pos == length - 1) {
906 Py_INCREF(nullentry);
908 Py_INCREF(nullentry);
907 return nullentry;
909 return nullentry;
908 }
910 }
909
911
910 if (pos >= self->length - 1) {
912 if (pos >= self->length - 1) {
911 PyObject *obj;
913 PyObject *obj;
912 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
914 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
913 Py_INCREF(obj);
915 Py_INCREF(obj);
914 return obj;
916 return obj;
915 }
917 }
916
918
917 if (self->cache) {
919 if (self->cache) {
918 if (self->cache[pos]) {
920 if (self->cache[pos]) {
919 Py_INCREF(self->cache[pos]);
921 Py_INCREF(self->cache[pos]);
920 return self->cache[pos];
922 return self->cache[pos];
921 }
923 }
922 } else {
924 } else {
923 self->cache = calloc(self->raw_length, sizeof(PyObject *));
925 self->cache = calloc(self->raw_length, sizeof(PyObject *));
924 if (self->cache == NULL)
926 if (self->cache == NULL)
925 return PyErr_NoMemory();
927 return PyErr_NoMemory();
926 }
928 }
927
929
928 data = index_deref(self, pos);
930 data = index_deref(self, pos);
929 if (data == NULL)
931 if (data == NULL)
930 return NULL;
932 return NULL;
931
933
932 offset_flags = getbe32(data + 4);
934 offset_flags = getbe32(data + 4);
933 if (pos == 0) /* mask out version number for the first entry */
935 if (pos == 0) /* mask out version number for the first entry */
934 offset_flags &= 0xFFFF;
936 offset_flags &= 0xFFFF;
935 else {
937 else {
936 uint32_t offset_high = getbe32(data);
938 uint32_t offset_high = getbe32(data);
937 offset_flags |= ((uint64_t)offset_high) << 32;
939 offset_flags |= ((uint64_t)offset_high) << 32;
938 }
940 }
939
941
940 comp_len = getbe32(data + 8);
942 comp_len = getbe32(data + 8);
941 uncomp_len = getbe32(data + 12);
943 uncomp_len = getbe32(data + 12);
942 base_rev = getbe32(data + 16);
944 base_rev = getbe32(data + 16);
943 link_rev = getbe32(data + 20);
945 link_rev = getbe32(data + 20);
944 parent_1 = getbe32(data + 24);
946 parent_1 = getbe32(data + 24);
945 parent_2 = getbe32(data + 28);
947 parent_2 = getbe32(data + 28);
946 c_node_id = data + 32;
948 c_node_id = data + 32;
947
949
948 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
950 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
949 uncomp_len, base_rev, link_rev,
951 uncomp_len, base_rev, link_rev,
950 parent_1, parent_2, c_node_id, 20);
952 parent_1, parent_2, c_node_id, 20);
951
953
952 if (entry) {
954 if (entry) {
953 PyObject_GC_UnTrack(entry);
955 PyObject_GC_UnTrack(entry);
954 Py_INCREF(entry);
956 Py_INCREF(entry);
955 }
957 }
956
958
957 self->cache[pos] = entry;
959 self->cache[pos] = entry;
958
960
959 return entry;
961 return entry;
960 }
962 }
961
963
962 /*
964 /*
963 * Return the 20-byte SHA of the node corresponding to the given rev.
965 * Return the 20-byte SHA of the node corresponding to the given rev.
964 */
966 */
965 static const char *index_node(indexObject *self, Py_ssize_t pos)
967 static const char *index_node(indexObject *self, Py_ssize_t pos)
966 {
968 {
967 Py_ssize_t length = index_length(self);
969 Py_ssize_t length = index_length(self);
968 const char *data;
970 const char *data;
969
971
970 if (pos == length - 1 || pos == INT_MAX)
972 if (pos == length - 1 || pos == INT_MAX)
971 return nullid;
973 return nullid;
972
974
973 if (pos >= length)
975 if (pos >= length)
974 return NULL;
976 return NULL;
975
977
976 if (pos >= self->length - 1) {
978 if (pos >= self->length - 1) {
977 PyObject *tuple, *str;
979 PyObject *tuple, *str;
978 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
980 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
979 str = PyTuple_GetItem(tuple, 7);
981 str = PyTuple_GetItem(tuple, 7);
980 return str ? PyBytes_AS_STRING(str) : NULL;
982 return str ? PyBytes_AS_STRING(str) : NULL;
981 }
983 }
982
984
983 data = index_deref(self, pos);
985 data = index_deref(self, pos);
984 return data ? data + 32 : NULL;
986 return data ? data + 32 : NULL;
985 }
987 }
986
988
987 static int nt_insert(indexObject *self, const char *node, int rev);
989 static int nt_insert(indexObject *self, const char *node, int rev);
988
990
989 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
991 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
990 {
992 {
991 if (PyBytes_AsStringAndSize(obj, node, nodelen) == -1)
993 if (PyBytes_AsStringAndSize(obj, node, nodelen) == -1)
992 return -1;
994 return -1;
993 if (*nodelen == 20)
995 if (*nodelen == 20)
994 return 0;
996 return 0;
995 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
997 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
996 return -1;
998 return -1;
997 }
999 }
998
1000
999 static PyObject *index_insert(indexObject *self, PyObject *args)
1001 static PyObject *index_insert(indexObject *self, PyObject *args)
1000 {
1002 {
1001 PyObject *obj;
1003 PyObject *obj;
1002 char *node;
1004 char *node;
1003 int index;
1005 int index;
1004 Py_ssize_t len, nodelen;
1006 Py_ssize_t len, nodelen;
1005
1007
1006 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
1008 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
1007 return NULL;
1009 return NULL;
1008
1010
1009 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
1011 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
1010 PyErr_SetString(PyExc_TypeError, "8-tuple required");
1012 PyErr_SetString(PyExc_TypeError, "8-tuple required");
1011 return NULL;
1013 return NULL;
1012 }
1014 }
1013
1015
1014 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
1016 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
1015 return NULL;
1017 return NULL;
1016
1018
1017 len = index_length(self);
1019 len = index_length(self);
1018
1020
1019 if (index < 0)
1021 if (index < 0)
1020 index += len;
1022 index += len;
1021
1023
1022 if (index != len - 1) {
1024 if (index != len - 1) {
1023 PyErr_SetString(PyExc_IndexError,
1025 PyErr_SetString(PyExc_IndexError,
1024 "insert only supported at index -1");
1026 "insert only supported at index -1");
1025 return NULL;
1027 return NULL;
1026 }
1028 }
1027
1029
1028 if (self->added == NULL) {
1030 if (self->added == NULL) {
1029 self->added = PyList_New(0);
1031 self->added = PyList_New(0);
1030 if (self->added == NULL)
1032 if (self->added == NULL)
1031 return NULL;
1033 return NULL;
1032 }
1034 }
1033
1035
1034 if (PyList_Append(self->added, obj) == -1)
1036 if (PyList_Append(self->added, obj) == -1)
1035 return NULL;
1037 return NULL;
1036
1038
1037 if (self->nt)
1039 if (self->nt)
1038 nt_insert(self, node, index);
1040 nt_insert(self, node, index);
1039
1041
1040 Py_CLEAR(self->headrevs);
1042 Py_CLEAR(self->headrevs);
1041 Py_RETURN_NONE;
1043 Py_RETURN_NONE;
1042 }
1044 }
1043
1045
1044 static void _index_clearcaches(indexObject *self)
1046 static void _index_clearcaches(indexObject *self)
1045 {
1047 {
1046 if (self->cache) {
1048 if (self->cache) {
1047 Py_ssize_t i;
1049 Py_ssize_t i;
1048
1050
1049 for (i = 0; i < self->raw_length; i++)
1051 for (i = 0; i < self->raw_length; i++)
1050 Py_CLEAR(self->cache[i]);
1052 Py_CLEAR(self->cache[i]);
1051 free(self->cache);
1053 free(self->cache);
1052 self->cache = NULL;
1054 self->cache = NULL;
1053 }
1055 }
1054 if (self->offsets) {
1056 if (self->offsets) {
1055 free(self->offsets);
1057 free(self->offsets);
1056 self->offsets = NULL;
1058 self->offsets = NULL;
1057 }
1059 }
1058 if (self->nt) {
1060 if (self->nt) {
1059 free(self->nt);
1061 free(self->nt);
1060 self->nt = NULL;
1062 self->nt = NULL;
1061 }
1063 }
1062 Py_CLEAR(self->headrevs);
1064 Py_CLEAR(self->headrevs);
1063 }
1065 }
1064
1066
1065 static PyObject *index_clearcaches(indexObject *self)
1067 static PyObject *index_clearcaches(indexObject *self)
1066 {
1068 {
1067 _index_clearcaches(self);
1069 _index_clearcaches(self);
1068 self->ntlength = self->ntcapacity = 0;
1070 self->ntlength = self->ntcapacity = 0;
1069 self->ntdepth = self->ntsplits = 0;
1071 self->ntdepth = self->ntsplits = 0;
1070 self->ntrev = -1;
1072 self->ntrev = -1;
1071 self->ntlookups = self->ntmisses = 0;
1073 self->ntlookups = self->ntmisses = 0;
1072 Py_RETURN_NONE;
1074 Py_RETURN_NONE;
1073 }
1075 }
1074
1076
1075 static PyObject *index_stats(indexObject *self)
1077 static PyObject *index_stats(indexObject *self)
1076 {
1078 {
1077 PyObject *obj = PyDict_New();
1079 PyObject *obj = PyDict_New();
1078 PyObject *t = NULL;
1080 PyObject *t = NULL;
1079
1081
1080 if (obj == NULL)
1082 if (obj == NULL)
1081 return NULL;
1083 return NULL;
1082
1084
1083 #define istat(__n, __d) \
1085 #define istat(__n, __d) \
1084 do { \
1086 do { \
1085 t = PyInt_FromSsize_t(self->__n); \
1087 t = PyInt_FromSsize_t(self->__n); \
1086 if (!t) \
1088 if (!t) \
1087 goto bail; \
1089 goto bail; \
1088 if (PyDict_SetItemString(obj, __d, t) == -1) \
1090 if (PyDict_SetItemString(obj, __d, t) == -1) \
1089 goto bail; \
1091 goto bail; \
1090 Py_DECREF(t); \
1092 Py_DECREF(t); \
1091 } while (0)
1093 } while (0)
1092
1094
1093 if (self->added) {
1095 if (self->added) {
1094 Py_ssize_t len = PyList_GET_SIZE(self->added);
1096 Py_ssize_t len = PyList_GET_SIZE(self->added);
1095 t = PyInt_FromSsize_t(len);
1097 t = PyInt_FromSsize_t(len);
1096 if (!t)
1098 if (!t)
1097 goto bail;
1099 goto bail;
1098 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
1100 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
1099 goto bail;
1101 goto bail;
1100 Py_DECREF(t);
1102 Py_DECREF(t);
1101 }
1103 }
1102
1104
1103 if (self->raw_length != self->length - 1)
1105 if (self->raw_length != self->length - 1)
1104 istat(raw_length, "revs on disk");
1106 istat(raw_length, "revs on disk");
1105 istat(length, "revs in memory");
1107 istat(length, "revs in memory");
1106 istat(ntcapacity, "node trie capacity");
1108 istat(ntcapacity, "node trie capacity");
1107 istat(ntdepth, "node trie depth");
1109 istat(ntdepth, "node trie depth");
1108 istat(ntlength, "node trie count");
1110 istat(ntlength, "node trie count");
1109 istat(ntlookups, "node trie lookups");
1111 istat(ntlookups, "node trie lookups");
1110 istat(ntmisses, "node trie misses");
1112 istat(ntmisses, "node trie misses");
1111 istat(ntrev, "node trie last rev scanned");
1113 istat(ntrev, "node trie last rev scanned");
1112 istat(ntsplits, "node trie splits");
1114 istat(ntsplits, "node trie splits");
1113
1115
1114 #undef istat
1116 #undef istat
1115
1117
1116 return obj;
1118 return obj;
1117
1119
1118 bail:
1120 bail:
1119 Py_XDECREF(obj);
1121 Py_XDECREF(obj);
1120 Py_XDECREF(t);
1122 Py_XDECREF(t);
1121 return NULL;
1123 return NULL;
1122 }
1124 }
1123
1125
1124 /*
1126 /*
1125 * When we cache a list, we want to be sure the caller can't mutate
1127 * When we cache a list, we want to be sure the caller can't mutate
1126 * the cached copy.
1128 * the cached copy.
1127 */
1129 */
1128 static PyObject *list_copy(PyObject *list)
1130 static PyObject *list_copy(PyObject *list)
1129 {
1131 {
1130 Py_ssize_t len = PyList_GET_SIZE(list);
1132 Py_ssize_t len = PyList_GET_SIZE(list);
1131 PyObject *newlist = PyList_New(len);
1133 PyObject *newlist = PyList_New(len);
1132 Py_ssize_t i;
1134 Py_ssize_t i;
1133
1135
1134 if (newlist == NULL)
1136 if (newlist == NULL)
1135 return NULL;
1137 return NULL;
1136
1138
1137 for (i = 0; i < len; i++) {
1139 for (i = 0; i < len; i++) {
1138 PyObject *obj = PyList_GET_ITEM(list, i);
1140 PyObject *obj = PyList_GET_ITEM(list, i);
1139 Py_INCREF(obj);
1141 Py_INCREF(obj);
1140 PyList_SET_ITEM(newlist, i, obj);
1142 PyList_SET_ITEM(newlist, i, obj);
1141 }
1143 }
1142
1144
1143 return newlist;
1145 return newlist;
1144 }
1146 }
1145
1147
1146 static int check_filter(PyObject *filter, Py_ssize_t arg) {
1148 static int check_filter(PyObject *filter, Py_ssize_t arg) {
1147 if (filter) {
1149 if (filter) {
1148 PyObject *arglist, *result;
1150 PyObject *arglist, *result;
1149 int isfiltered;
1151 int isfiltered;
1150
1152
1151 arglist = Py_BuildValue("(n)", arg);
1153 arglist = Py_BuildValue("(n)", arg);
1152 if (!arglist) {
1154 if (!arglist) {
1153 return -1;
1155 return -1;
1154 }
1156 }
1155
1157
1156 result = PyEval_CallObject(filter, arglist);
1158 result = PyEval_CallObject(filter, arglist);
1157 Py_DECREF(arglist);
1159 Py_DECREF(arglist);
1158 if (!result) {
1160 if (!result) {
1159 return -1;
1161 return -1;
1160 }
1162 }
1161
1163
1162 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
1164 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
1163 * same as this function, so we can just return it directly.*/
1165 * same as this function, so we can just return it directly.*/
1164 isfiltered = PyObject_IsTrue(result);
1166 isfiltered = PyObject_IsTrue(result);
1165 Py_DECREF(result);
1167 Py_DECREF(result);
1166 return isfiltered;
1168 return isfiltered;
1167 } else {
1169 } else {
1168 return 0;
1170 return 0;
1169 }
1171 }
1170 }
1172 }
1171
1173
1172 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
1174 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
1173 Py_ssize_t marker, char *phases)
1175 Py_ssize_t marker, char *phases)
1174 {
1176 {
1175 PyObject *iter = NULL;
1177 PyObject *iter = NULL;
1176 PyObject *iter_item = NULL;
1178 PyObject *iter_item = NULL;
1177 Py_ssize_t min_idx = index_length(self) + 1;
1179 Py_ssize_t min_idx = index_length(self) + 1;
1178 long iter_item_long;
1180 long iter_item_long;
1179
1181
1180 if (PyList_GET_SIZE(list) != 0) {
1182 if (PyList_GET_SIZE(list) != 0) {
1181 iter = PyObject_GetIter(list);
1183 iter = PyObject_GetIter(list);
1182 if (iter == NULL)
1184 if (iter == NULL)
1183 return -2;
1185 return -2;
1184 while ((iter_item = PyIter_Next(iter)))
1186 while ((iter_item = PyIter_Next(iter)))
1185 {
1187 {
1186 iter_item_long = PyInt_AS_LONG(iter_item);
1188 iter_item_long = PyInt_AS_LONG(iter_item);
1187 Py_DECREF(iter_item);
1189 Py_DECREF(iter_item);
1188 if (iter_item_long < min_idx)
1190 if (iter_item_long < min_idx)
1189 min_idx = iter_item_long;
1191 min_idx = iter_item_long;
1190 phases[iter_item_long] = marker;
1192 phases[iter_item_long] = marker;
1191 }
1193 }
1192 Py_DECREF(iter);
1194 Py_DECREF(iter);
1193 }
1195 }
1194
1196
1195 return min_idx;
1197 return min_idx;
1196 }
1198 }
1197
1199
1198 static inline void set_phase_from_parents(char *phases, int parent_1,
1200 static inline void set_phase_from_parents(char *phases, int parent_1,
1199 int parent_2, Py_ssize_t i)
1201 int parent_2, Py_ssize_t i)
1200 {
1202 {
1201 if (parent_1 >= 0 && phases[parent_1] > phases[i])
1203 if (parent_1 >= 0 && phases[parent_1] > phases[i])
1202 phases[i] = phases[parent_1];
1204 phases[i] = phases[parent_1];
1203 if (parent_2 >= 0 && phases[parent_2] > phases[i])
1205 if (parent_2 >= 0 && phases[parent_2] > phases[i])
1204 phases[i] = phases[parent_2];
1206 phases[i] = phases[parent_2];
1205 }
1207 }
1206
1208
1207 static PyObject *reachableroots2(indexObject *self, PyObject *args)
1209 static PyObject *reachableroots2(indexObject *self, PyObject *args)
1208 {
1210 {
1209
1211
1210 /* Input */
1212 /* Input */
1211 long minroot;
1213 long minroot;
1212 PyObject *includepatharg = NULL;
1214 PyObject *includepatharg = NULL;
1213 int includepath = 0;
1215 int includepath = 0;
1214 /* heads and roots are lists */
1216 /* heads and roots are lists */
1215 PyObject *heads = NULL;
1217 PyObject *heads = NULL;
1216 PyObject *roots = NULL;
1218 PyObject *roots = NULL;
1217 PyObject *reachable = NULL;
1219 PyObject *reachable = NULL;
1218
1220
1219 PyObject *val;
1221 PyObject *val;
1220 Py_ssize_t len = index_length(self) - 1;
1222 Py_ssize_t len = index_length(self) - 1;
1221 long revnum;
1223 long revnum;
1222 Py_ssize_t k;
1224 Py_ssize_t k;
1223 Py_ssize_t i;
1225 Py_ssize_t i;
1224 Py_ssize_t l;
1226 Py_ssize_t l;
1225 int r;
1227 int r;
1226 int parents[2];
1228 int parents[2];
1227
1229
1228 /* Internal data structure:
1230 /* Internal data structure:
1229 * tovisit: array of length len+1 (all revs + nullrev), filled upto lentovisit
1231 * tovisit: array of length len+1 (all revs + nullrev), filled upto lentovisit
1230 * revstates: array of length len+1 (all revs + nullrev) */
1232 * revstates: array of length len+1 (all revs + nullrev) */
1231 int *tovisit = NULL;
1233 int *tovisit = NULL;
1232 long lentovisit = 0;
1234 long lentovisit = 0;
1233 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
1235 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
1234 char *revstates = NULL;
1236 char *revstates = NULL;
1235
1237
1236 /* Get arguments */
1238 /* Get arguments */
1237 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
1239 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
1238 &PyList_Type, &roots,
1240 &PyList_Type, &roots,
1239 &PyBool_Type, &includepatharg))
1241 &PyBool_Type, &includepatharg))
1240 goto bail;
1242 goto bail;
1241
1243
1242 if (includepatharg == Py_True)
1244 if (includepatharg == Py_True)
1243 includepath = 1;
1245 includepath = 1;
1244
1246
1245 /* Initialize return set */
1247 /* Initialize return set */
1246 reachable = PyList_New(0);
1248 reachable = PyList_New(0);
1247 if (reachable == NULL)
1249 if (reachable == NULL)
1248 goto bail;
1250 goto bail;
1249
1251
1250 /* Initialize internal datastructures */
1252 /* Initialize internal datastructures */
1251 tovisit = (int *)malloc((len + 1) * sizeof(int));
1253 tovisit = (int *)malloc((len + 1) * sizeof(int));
1252 if (tovisit == NULL) {
1254 if (tovisit == NULL) {
1253 PyErr_NoMemory();
1255 PyErr_NoMemory();
1254 goto bail;
1256 goto bail;
1255 }
1257 }
1256
1258
1257 revstates = (char *)calloc(len + 1, 1);
1259 revstates = (char *)calloc(len + 1, 1);
1258 if (revstates == NULL) {
1260 if (revstates == NULL) {
1259 PyErr_NoMemory();
1261 PyErr_NoMemory();
1260 goto bail;
1262 goto bail;
1261 }
1263 }
1262
1264
1263 l = PyList_GET_SIZE(roots);
1265 l = PyList_GET_SIZE(roots);
1264 for (i = 0; i < l; i++) {
1266 for (i = 0; i < l; i++) {
1265 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
1267 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
1266 if (revnum == -1 && PyErr_Occurred())
1268 if (revnum == -1 && PyErr_Occurred())
1267 goto bail;
1269 goto bail;
1268 /* If root is out of range, e.g. wdir(), it must be unreachable
1270 /* If root is out of range, e.g. wdir(), it must be unreachable
1269 * from heads. So we can just ignore it. */
1271 * from heads. So we can just ignore it. */
1270 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
1272 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
1271 continue;
1273 continue;
1272 revstates[revnum + 1] |= RS_ROOT;
1274 revstates[revnum + 1] |= RS_ROOT;
1273 }
1275 }
1274
1276
1275 /* Populate tovisit with all the heads */
1277 /* Populate tovisit with all the heads */
1276 l = PyList_GET_SIZE(heads);
1278 l = PyList_GET_SIZE(heads);
1277 for (i = 0; i < l; i++) {
1279 for (i = 0; i < l; i++) {
1278 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
1280 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
1279 if (revnum == -1 && PyErr_Occurred())
1281 if (revnum == -1 && PyErr_Occurred())
1280 goto bail;
1282 goto bail;
1281 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
1283 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
1282 PyErr_SetString(PyExc_IndexError, "head out of range");
1284 PyErr_SetString(PyExc_IndexError, "head out of range");
1283 goto bail;
1285 goto bail;
1284 }
1286 }
1285 if (!(revstates[revnum + 1] & RS_SEEN)) {
1287 if (!(revstates[revnum + 1] & RS_SEEN)) {
1286 tovisit[lentovisit++] = (int)revnum;
1288 tovisit[lentovisit++] = (int)revnum;
1287 revstates[revnum + 1] |= RS_SEEN;
1289 revstates[revnum + 1] |= RS_SEEN;
1288 }
1290 }
1289 }
1291 }
1290
1292
1291 /* Visit the tovisit list and find the reachable roots */
1293 /* Visit the tovisit list and find the reachable roots */
1292 k = 0;
1294 k = 0;
1293 while (k < lentovisit) {
1295 while (k < lentovisit) {
1294 /* Add the node to reachable if it is a root*/
1296 /* Add the node to reachable if it is a root*/
1295 revnum = tovisit[k++];
1297 revnum = tovisit[k++];
1296 if (revstates[revnum + 1] & RS_ROOT) {
1298 if (revstates[revnum + 1] & RS_ROOT) {
1297 revstates[revnum + 1] |= RS_REACHABLE;
1299 revstates[revnum + 1] |= RS_REACHABLE;
1298 val = PyInt_FromLong(revnum);
1300 val = PyInt_FromLong(revnum);
1299 if (val == NULL)
1301 if (val == NULL)
1300 goto bail;
1302 goto bail;
1301 r = PyList_Append(reachable, val);
1303 r = PyList_Append(reachable, val);
1302 Py_DECREF(val);
1304 Py_DECREF(val);
1303 if (r < 0)
1305 if (r < 0)
1304 goto bail;
1306 goto bail;
1305 if (includepath == 0)
1307 if (includepath == 0)
1306 continue;
1308 continue;
1307 }
1309 }
1308
1310
1309 /* Add its parents to the list of nodes to visit */
1311 /* Add its parents to the list of nodes to visit */
1310 if (revnum == -1)
1312 if (revnum == -1)
1311 continue;
1313 continue;
1312 r = index_get_parents(self, revnum, parents, (int)len - 1);
1314 r = index_get_parents(self, revnum, parents, (int)len - 1);
1313 if (r < 0)
1315 if (r < 0)
1314 goto bail;
1316 goto bail;
1315 for (i = 0; i < 2; i++) {
1317 for (i = 0; i < 2; i++) {
1316 if (!(revstates[parents[i] + 1] & RS_SEEN)
1318 if (!(revstates[parents[i] + 1] & RS_SEEN)
1317 && parents[i] >= minroot) {
1319 && parents[i] >= minroot) {
1318 tovisit[lentovisit++] = parents[i];
1320 tovisit[lentovisit++] = parents[i];
1319 revstates[parents[i] + 1] |= RS_SEEN;
1321 revstates[parents[i] + 1] |= RS_SEEN;
1320 }
1322 }
1321 }
1323 }
1322 }
1324 }
1323
1325
1324 /* Find all the nodes in between the roots we found and the heads
1326 /* Find all the nodes in between the roots we found and the heads
1325 * and add them to the reachable set */
1327 * and add them to the reachable set */
1326 if (includepath == 1) {
1328 if (includepath == 1) {
1327 long minidx = minroot;
1329 long minidx = minroot;
1328 if (minidx < 0)
1330 if (minidx < 0)
1329 minidx = 0;
1331 minidx = 0;
1330 for (i = minidx; i < len; i++) {
1332 for (i = minidx; i < len; i++) {
1331 if (!(revstates[i + 1] & RS_SEEN))
1333 if (!(revstates[i + 1] & RS_SEEN))
1332 continue;
1334 continue;
1333 r = index_get_parents(self, i, parents, (int)len - 1);
1335 r = index_get_parents(self, i, parents, (int)len - 1);
1334 /* Corrupted index file, error is set from
1336 /* Corrupted index file, error is set from
1335 * index_get_parents */
1337 * index_get_parents */
1336 if (r < 0)
1338 if (r < 0)
1337 goto bail;
1339 goto bail;
1338 if (((revstates[parents[0] + 1] |
1340 if (((revstates[parents[0] + 1] |
1339 revstates[parents[1] + 1]) & RS_REACHABLE)
1341 revstates[parents[1] + 1]) & RS_REACHABLE)
1340 && !(revstates[i + 1] & RS_REACHABLE)) {
1342 && !(revstates[i + 1] & RS_REACHABLE)) {
1341 revstates[i + 1] |= RS_REACHABLE;
1343 revstates[i + 1] |= RS_REACHABLE;
1342 val = PyInt_FromLong(i);
1344 val = PyInt_FromLong(i);
1343 if (val == NULL)
1345 if (val == NULL)
1344 goto bail;
1346 goto bail;
1345 r = PyList_Append(reachable, val);
1347 r = PyList_Append(reachable, val);
1346 Py_DECREF(val);
1348 Py_DECREF(val);
1347 if (r < 0)
1349 if (r < 0)
1348 goto bail;
1350 goto bail;
1349 }
1351 }
1350 }
1352 }
1351 }
1353 }
1352
1354
1353 free(revstates);
1355 free(revstates);
1354 free(tovisit);
1356 free(tovisit);
1355 return reachable;
1357 return reachable;
1356 bail:
1358 bail:
1357 Py_XDECREF(reachable);
1359 Py_XDECREF(reachable);
1358 free(revstates);
1360 free(revstates);
1359 free(tovisit);
1361 free(tovisit);
1360 return NULL;
1362 return NULL;
1361 }
1363 }
1362
1364
1363 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
1365 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
1364 {
1366 {
1365 PyObject *roots = Py_None;
1367 PyObject *roots = Py_None;
1366 PyObject *ret = NULL;
1368 PyObject *ret = NULL;
1367 PyObject *phaseslist = NULL;
1369 PyObject *phaseslist = NULL;
1368 PyObject *phaseroots = NULL;
1370 PyObject *phaseroots = NULL;
1369 PyObject *phaseset = NULL;
1371 PyObject *phaseset = NULL;
1370 PyObject *phasessetlist = NULL;
1372 PyObject *phasessetlist = NULL;
1371 PyObject *rev = NULL;
1373 PyObject *rev = NULL;
1372 Py_ssize_t len = index_length(self) - 1;
1374 Py_ssize_t len = index_length(self) - 1;
1373 Py_ssize_t numphase = 0;
1375 Py_ssize_t numphase = 0;
1374 Py_ssize_t minrevallphases = 0;
1376 Py_ssize_t minrevallphases = 0;
1375 Py_ssize_t minrevphase = 0;
1377 Py_ssize_t minrevphase = 0;
1376 Py_ssize_t i = 0;
1378 Py_ssize_t i = 0;
1377 char *phases = NULL;
1379 char *phases = NULL;
1378 long phase;
1380 long phase;
1379
1381
1380 if (!PyArg_ParseTuple(args, "O", &roots))
1382 if (!PyArg_ParseTuple(args, "O", &roots))
1381 goto done;
1383 goto done;
1382 if (roots == NULL || !PyList_Check(roots))
1384 if (roots == NULL || !PyList_Check(roots))
1383 goto done;
1385 goto done;
1384
1386
1385 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
1387 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
1386 if (phases == NULL) {
1388 if (phases == NULL) {
1387 PyErr_NoMemory();
1389 PyErr_NoMemory();
1388 goto done;
1390 goto done;
1389 }
1391 }
1390 /* Put the phase information of all the roots in phases */
1392 /* Put the phase information of all the roots in phases */
1391 numphase = PyList_GET_SIZE(roots)+1;
1393 numphase = PyList_GET_SIZE(roots)+1;
1392 minrevallphases = len + 1;
1394 minrevallphases = len + 1;
1393 phasessetlist = PyList_New(numphase);
1395 phasessetlist = PyList_New(numphase);
1394 if (phasessetlist == NULL)
1396 if (phasessetlist == NULL)
1395 goto done;
1397 goto done;
1396
1398
1397 PyList_SET_ITEM(phasessetlist, 0, Py_None);
1399 PyList_SET_ITEM(phasessetlist, 0, Py_None);
1398 Py_INCREF(Py_None);
1400 Py_INCREF(Py_None);
1399
1401
1400 for (i = 0; i < numphase-1; i++) {
1402 for (i = 0; i < numphase-1; i++) {
1401 phaseroots = PyList_GET_ITEM(roots, i);
1403 phaseroots = PyList_GET_ITEM(roots, i);
1402 phaseset = PySet_New(NULL);
1404 phaseset = PySet_New(NULL);
1403 if (phaseset == NULL)
1405 if (phaseset == NULL)
1404 goto release;
1406 goto release;
1405 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
1407 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
1406 if (!PyList_Check(phaseroots))
1408 if (!PyList_Check(phaseroots))
1407 goto release;
1409 goto release;
1408 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
1410 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
1409 if (minrevphase == -2) /* Error from add_roots_get_min */
1411 if (minrevphase == -2) /* Error from add_roots_get_min */
1410 goto release;
1412 goto release;
1411 minrevallphases = MIN(minrevallphases, minrevphase);
1413 minrevallphases = MIN(minrevallphases, minrevphase);
1412 }
1414 }
1413 /* Propagate the phase information from the roots to the revs */
1415 /* Propagate the phase information from the roots to the revs */
1414 if (minrevallphases != -1) {
1416 if (minrevallphases != -1) {
1415 int parents[2];
1417 int parents[2];
1416 for (i = minrevallphases; i < len; i++) {
1418 for (i = minrevallphases; i < len; i++) {
1417 if (index_get_parents(self, i, parents,
1419 if (index_get_parents(self, i, parents,
1418 (int)len - 1) < 0)
1420 (int)len - 1) < 0)
1419 goto release;
1421 goto release;
1420 set_phase_from_parents(phases, parents[0], parents[1], i);
1422 set_phase_from_parents(phases, parents[0], parents[1], i);
1421 }
1423 }
1422 }
1424 }
1423 /* Transform phase list to a python list */
1425 /* Transform phase list to a python list */
1424 phaseslist = PyList_New(len);
1426 phaseslist = PyList_New(len);
1425 if (phaseslist == NULL)
1427 if (phaseslist == NULL)
1426 goto release;
1428 goto release;
1427 for (i = 0; i < len; i++) {
1429 for (i = 0; i < len; i++) {
1428 PyObject *phaseval;
1430 PyObject *phaseval;
1429
1431
1430 phase = phases[i];
1432 phase = phases[i];
1431 /* We only store the sets of phase for non public phase, the public phase
1433 /* We only store the sets of phase for non public phase, the public phase
1432 * is computed as a difference */
1434 * is computed as a difference */
1433 if (phase != 0) {
1435 if (phase != 0) {
1434 phaseset = PyList_GET_ITEM(phasessetlist, phase);
1436 phaseset = PyList_GET_ITEM(phasessetlist, phase);
1435 rev = PyInt_FromLong(i);
1437 rev = PyInt_FromLong(i);
1436 if (rev == NULL)
1438 if (rev == NULL)
1437 goto release;
1439 goto release;
1438 PySet_Add(phaseset, rev);
1440 PySet_Add(phaseset, rev);
1439 Py_XDECREF(rev);
1441 Py_XDECREF(rev);
1440 }
1442 }
1441 phaseval = PyInt_FromLong(phase);
1443 phaseval = PyInt_FromLong(phase);
1442 if (phaseval == NULL)
1444 if (phaseval == NULL)
1443 goto release;
1445 goto release;
1444 PyList_SET_ITEM(phaseslist, i, phaseval);
1446 PyList_SET_ITEM(phaseslist, i, phaseval);
1445 }
1447 }
1446 ret = PyTuple_Pack(2, phaseslist, phasessetlist);
1448 ret = PyTuple_Pack(2, phaseslist, phasessetlist);
1447
1449
1448 release:
1450 release:
1449 Py_XDECREF(phaseslist);
1451 Py_XDECREF(phaseslist);
1450 Py_XDECREF(phasessetlist);
1452 Py_XDECREF(phasessetlist);
1451 done:
1453 done:
1452 free(phases);
1454 free(phases);
1453 return ret;
1455 return ret;
1454 }
1456 }
1455
1457
1456 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1458 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1457 {
1459 {
1458 Py_ssize_t i, j, len;
1460 Py_ssize_t i, j, len;
1459 char *nothead = NULL;
1461 char *nothead = NULL;
1460 PyObject *heads = NULL;
1462 PyObject *heads = NULL;
1461 PyObject *filter = NULL;
1463 PyObject *filter = NULL;
1462 PyObject *filteredrevs = Py_None;
1464 PyObject *filteredrevs = Py_None;
1463
1465
1464 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1466 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1465 return NULL;
1467 return NULL;
1466 }
1468 }
1467
1469
1468 if (self->headrevs && filteredrevs == self->filteredrevs)
1470 if (self->headrevs && filteredrevs == self->filteredrevs)
1469 return list_copy(self->headrevs);
1471 return list_copy(self->headrevs);
1470
1472
1471 Py_DECREF(self->filteredrevs);
1473 Py_DECREF(self->filteredrevs);
1472 self->filteredrevs = filteredrevs;
1474 self->filteredrevs = filteredrevs;
1473 Py_INCREF(filteredrevs);
1475 Py_INCREF(filteredrevs);
1474
1476
1475 if (filteredrevs != Py_None) {
1477 if (filteredrevs != Py_None) {
1476 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1478 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1477 if (!filter) {
1479 if (!filter) {
1478 PyErr_SetString(PyExc_TypeError,
1480 PyErr_SetString(PyExc_TypeError,
1479 "filteredrevs has no attribute __contains__");
1481 "filteredrevs has no attribute __contains__");
1480 goto bail;
1482 goto bail;
1481 }
1483 }
1482 }
1484 }
1483
1485
1484 len = index_length(self) - 1;
1486 len = index_length(self) - 1;
1485 heads = PyList_New(0);
1487 heads = PyList_New(0);
1486 if (heads == NULL)
1488 if (heads == NULL)
1487 goto bail;
1489 goto bail;
1488 if (len == 0) {
1490 if (len == 0) {
1489 PyObject *nullid = PyInt_FromLong(-1);
1491 PyObject *nullid = PyInt_FromLong(-1);
1490 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1492 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1491 Py_XDECREF(nullid);
1493 Py_XDECREF(nullid);
1492 goto bail;
1494 goto bail;
1493 }
1495 }
1494 goto done;
1496 goto done;
1495 }
1497 }
1496
1498
1497 nothead = calloc(len, 1);
1499 nothead = calloc(len, 1);
1498 if (nothead == NULL) {
1500 if (nothead == NULL) {
1499 PyErr_NoMemory();
1501 PyErr_NoMemory();
1500 goto bail;
1502 goto bail;
1501 }
1503 }
1502
1504
1503 for (i = len - 1; i >= 0; i--) {
1505 for (i = len - 1; i >= 0; i--) {
1504 int isfiltered;
1506 int isfiltered;
1505 int parents[2];
1507 int parents[2];
1506
1508
1507 /* If nothead[i] == 1, it means we've seen an unfiltered child of this
1509 /* If nothead[i] == 1, it means we've seen an unfiltered child of this
1508 * node already, and therefore this node is not filtered. So we can skip
1510 * node already, and therefore this node is not filtered. So we can skip
1509 * the expensive check_filter step.
1511 * the expensive check_filter step.
1510 */
1512 */
1511 if (nothead[i] != 1) {
1513 if (nothead[i] != 1) {
1512 isfiltered = check_filter(filter, i);
1514 isfiltered = check_filter(filter, i);
1513 if (isfiltered == -1) {
1515 if (isfiltered == -1) {
1514 PyErr_SetString(PyExc_TypeError,
1516 PyErr_SetString(PyExc_TypeError,
1515 "unable to check filter");
1517 "unable to check filter");
1516 goto bail;
1518 goto bail;
1517 }
1519 }
1518
1520
1519 if (isfiltered) {
1521 if (isfiltered) {
1520 nothead[i] = 1;
1522 nothead[i] = 1;
1521 continue;
1523 continue;
1522 }
1524 }
1523 }
1525 }
1524
1526
1525 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
1527 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
1526 goto bail;
1528 goto bail;
1527 for (j = 0; j < 2; j++) {
1529 for (j = 0; j < 2; j++) {
1528 if (parents[j] >= 0)
1530 if (parents[j] >= 0)
1529 nothead[parents[j]] = 1;
1531 nothead[parents[j]] = 1;
1530 }
1532 }
1531 }
1533 }
1532
1534
1533 for (i = 0; i < len; i++) {
1535 for (i = 0; i < len; i++) {
1534 PyObject *head;
1536 PyObject *head;
1535
1537
1536 if (nothead[i])
1538 if (nothead[i])
1537 continue;
1539 continue;
1538 head = PyInt_FromSsize_t(i);
1540 head = PyInt_FromSsize_t(i);
1539 if (head == NULL || PyList_Append(heads, head) == -1) {
1541 if (head == NULL || PyList_Append(heads, head) == -1) {
1540 Py_XDECREF(head);
1542 Py_XDECREF(head);
1541 goto bail;
1543 goto bail;
1542 }
1544 }
1543 }
1545 }
1544
1546
1545 done:
1547 done:
1546 self->headrevs = heads;
1548 self->headrevs = heads;
1547 Py_XDECREF(filter);
1549 Py_XDECREF(filter);
1548 free(nothead);
1550 free(nothead);
1549 return list_copy(self->headrevs);
1551 return list_copy(self->headrevs);
1550 bail:
1552 bail:
1551 Py_XDECREF(filter);
1553 Py_XDECREF(filter);
1552 Py_XDECREF(heads);
1554 Py_XDECREF(heads);
1553 free(nothead);
1555 free(nothead);
1554 return NULL;
1556 return NULL;
1555 }
1557 }
1556
1558
1557 static inline int nt_level(const char *node, Py_ssize_t level)
1559 static inline int nt_level(const char *node, Py_ssize_t level)
1558 {
1560 {
1559 int v = node[level>>1];
1561 int v = node[level>>1];
1560 if (!(level & 1))
1562 if (!(level & 1))
1561 v >>= 4;
1563 v >>= 4;
1562 return v & 0xf;
1564 return v & 0xf;
1563 }
1565 }
1564
1566
1565 /*
1567 /*
1566 * Return values:
1568 * Return values:
1567 *
1569 *
1568 * -4: match is ambiguous (multiple candidates)
1570 * -4: match is ambiguous (multiple candidates)
1569 * -2: not found
1571 * -2: not found
1570 * rest: valid rev
1572 * rest: valid rev
1571 */
1573 */
1572 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1574 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1573 int hex)
1575 int hex)
1574 {
1576 {
1575 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1577 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1576 int level, maxlevel, off;
1578 int level, maxlevel, off;
1577
1579
1578 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1580 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1579 return -1;
1581 return -1;
1580
1582
1581 if (self->nt == NULL)
1583 if (self->nt == NULL)
1582 return -2;
1584 return -2;
1583
1585
1584 if (hex)
1586 if (hex)
1585 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1587 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1586 else
1588 else
1587 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1589 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1588
1590
1589 for (level = off = 0; level < maxlevel; level++) {
1591 for (level = off = 0; level < maxlevel; level++) {
1590 int k = getnybble(node, level);
1592 int k = getnybble(node, level);
1591 nodetree *n = &self->nt[off];
1593 nodetree *n = &self->nt[off];
1592 int v = n->children[k];
1594 int v = n->children[k];
1593
1595
1594 if (v < 0) {
1596 if (v < 0) {
1595 const char *n;
1597 const char *n;
1596 Py_ssize_t i;
1598 Py_ssize_t i;
1597
1599
1598 v = -(v + 1);
1600 v = -(v + 1);
1599 n = index_node(self, v);
1601 n = index_node(self, v);
1600 if (n == NULL)
1602 if (n == NULL)
1601 return -2;
1603 return -2;
1602 for (i = level; i < maxlevel; i++)
1604 for (i = level; i < maxlevel; i++)
1603 if (getnybble(node, i) != nt_level(n, i))
1605 if (getnybble(node, i) != nt_level(n, i))
1604 return -2;
1606 return -2;
1605 return v;
1607 return v;
1606 }
1608 }
1607 if (v == 0)
1609 if (v == 0)
1608 return -2;
1610 return -2;
1609 off = v;
1611 off = v;
1610 }
1612 }
1611 /* multiple matches against an ambiguous prefix */
1613 /* multiple matches against an ambiguous prefix */
1612 return -4;
1614 return -4;
1613 }
1615 }
1614
1616
1615 static int nt_new(indexObject *self)
1617 static int nt_new(indexObject *self)
1616 {
1618 {
1617 if (self->ntlength == self->ntcapacity) {
1619 if (self->ntlength == self->ntcapacity) {
1618 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1620 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1619 PyErr_SetString(PyExc_MemoryError,
1621 PyErr_SetString(PyExc_MemoryError,
1620 "overflow in nt_new");
1622 "overflow in nt_new");
1621 return -1;
1623 return -1;
1622 }
1624 }
1623 self->ntcapacity *= 2;
1625 self->ntcapacity *= 2;
1624 self->nt = realloc(self->nt,
1626 self->nt = realloc(self->nt,
1625 self->ntcapacity * sizeof(nodetree));
1627 self->ntcapacity * sizeof(nodetree));
1626 if (self->nt == NULL) {
1628 if (self->nt == NULL) {
1627 PyErr_SetString(PyExc_MemoryError, "out of memory");
1629 PyErr_SetString(PyExc_MemoryError, "out of memory");
1628 return -1;
1630 return -1;
1629 }
1631 }
1630 memset(&self->nt[self->ntlength], 0,
1632 memset(&self->nt[self->ntlength], 0,
1631 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1633 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1632 }
1634 }
1633 return self->ntlength++;
1635 return self->ntlength++;
1634 }
1636 }
1635
1637
1636 static int nt_insert(indexObject *self, const char *node, int rev)
1638 static int nt_insert(indexObject *self, const char *node, int rev)
1637 {
1639 {
1638 int level = 0;
1640 int level = 0;
1639 int off = 0;
1641 int off = 0;
1640
1642
1641 while (level < 40) {
1643 while (level < 40) {
1642 int k = nt_level(node, level);
1644 int k = nt_level(node, level);
1643 nodetree *n;
1645 nodetree *n;
1644 int v;
1646 int v;
1645
1647
1646 n = &self->nt[off];
1648 n = &self->nt[off];
1647 v = n->children[k];
1649 v = n->children[k];
1648
1650
1649 if (v == 0) {
1651 if (v == 0) {
1650 n->children[k] = -rev - 1;
1652 n->children[k] = -rev - 1;
1651 return 0;
1653 return 0;
1652 }
1654 }
1653 if (v < 0) {
1655 if (v < 0) {
1654 const char *oldnode = index_node(self, -(v + 1));
1656 const char *oldnode = index_node(self, -(v + 1));
1655 int noff;
1657 int noff;
1656
1658
1657 if (!oldnode || !memcmp(oldnode, node, 20)) {
1659 if (!oldnode || !memcmp(oldnode, node, 20)) {
1658 n->children[k] = -rev - 1;
1660 n->children[k] = -rev - 1;
1659 return 0;
1661 return 0;
1660 }
1662 }
1661 noff = nt_new(self);
1663 noff = nt_new(self);
1662 if (noff == -1)
1664 if (noff == -1)
1663 return -1;
1665 return -1;
1664 /* self->nt may have been changed by realloc */
1666 /* self->nt may have been changed by realloc */
1665 self->nt[off].children[k] = noff;
1667 self->nt[off].children[k] = noff;
1666 off = noff;
1668 off = noff;
1667 n = &self->nt[off];
1669 n = &self->nt[off];
1668 n->children[nt_level(oldnode, ++level)] = v;
1670 n->children[nt_level(oldnode, ++level)] = v;
1669 if (level > self->ntdepth)
1671 if (level > self->ntdepth)
1670 self->ntdepth = level;
1672 self->ntdepth = level;
1671 self->ntsplits += 1;
1673 self->ntsplits += 1;
1672 } else {
1674 } else {
1673 level += 1;
1675 level += 1;
1674 off = v;
1676 off = v;
1675 }
1677 }
1676 }
1678 }
1677
1679
1678 return -1;
1680 return -1;
1679 }
1681 }
1680
1682
1681 static int nt_init(indexObject *self)
1683 static int nt_init(indexObject *self)
1682 {
1684 {
1683 if (self->nt == NULL) {
1685 if (self->nt == NULL) {
1684 if ((size_t)self->raw_length > INT_MAX / sizeof(nodetree)) {
1686 if ((size_t)self->raw_length > INT_MAX / sizeof(nodetree)) {
1685 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1687 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1686 return -1;
1688 return -1;
1687 }
1689 }
1688 self->ntcapacity = self->raw_length < 4
1690 self->ntcapacity = self->raw_length < 4
1689 ? 4 : (int)self->raw_length / 2;
1691 ? 4 : (int)self->raw_length / 2;
1690
1692
1691 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1693 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1692 if (self->nt == NULL) {
1694 if (self->nt == NULL) {
1693 PyErr_NoMemory();
1695 PyErr_NoMemory();
1694 return -1;
1696 return -1;
1695 }
1697 }
1696 self->ntlength = 1;
1698 self->ntlength = 1;
1697 self->ntrev = (int)index_length(self) - 1;
1699 self->ntrev = (int)index_length(self) - 1;
1698 self->ntlookups = 1;
1700 self->ntlookups = 1;
1699 self->ntmisses = 0;
1701 self->ntmisses = 0;
1700 if (nt_insert(self, nullid, INT_MAX) == -1)
1702 if (nt_insert(self, nullid, INT_MAX) == -1)
1701 return -1;
1703 return -1;
1702 }
1704 }
1703 return 0;
1705 return 0;
1704 }
1706 }
1705
1707
1706 /*
1708 /*
1707 * Return values:
1709 * Return values:
1708 *
1710 *
1709 * -3: error (exception set)
1711 * -3: error (exception set)
1710 * -2: not found (no exception set)
1712 * -2: not found (no exception set)
1711 * rest: valid rev
1713 * rest: valid rev
1712 */
1714 */
1713 static int index_find_node(indexObject *self,
1715 static int index_find_node(indexObject *self,
1714 const char *node, Py_ssize_t nodelen)
1716 const char *node, Py_ssize_t nodelen)
1715 {
1717 {
1716 int rev;
1718 int rev;
1717
1719
1718 self->ntlookups++;
1720 self->ntlookups++;
1719 rev = nt_find(self, node, nodelen, 0);
1721 rev = nt_find(self, node, nodelen, 0);
1720 if (rev >= -1)
1722 if (rev >= -1)
1721 return rev;
1723 return rev;
1722
1724
1723 if (nt_init(self) == -1)
1725 if (nt_init(self) == -1)
1724 return -3;
1726 return -3;
1725
1727
1726 /*
1728 /*
1727 * For the first handful of lookups, we scan the entire index,
1729 * For the first handful of lookups, we scan the entire index,
1728 * and cache only the matching nodes. This optimizes for cases
1730 * and cache only the matching nodes. This optimizes for cases
1729 * like "hg tip", where only a few nodes are accessed.
1731 * like "hg tip", where only a few nodes are accessed.
1730 *
1732 *
1731 * After that, we cache every node we visit, using a single
1733 * After that, we cache every node we visit, using a single
1732 * scan amortized over multiple lookups. This gives the best
1734 * scan amortized over multiple lookups. This gives the best
1733 * bulk performance, e.g. for "hg log".
1735 * bulk performance, e.g. for "hg log".
1734 */
1736 */
1735 if (self->ntmisses++ < 4) {
1737 if (self->ntmisses++ < 4) {
1736 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1738 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1737 const char *n = index_node(self, rev);
1739 const char *n = index_node(self, rev);
1738 if (n == NULL)
1740 if (n == NULL)
1739 return -2;
1741 return -2;
1740 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1742 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1741 if (nt_insert(self, n, rev) == -1)
1743 if (nt_insert(self, n, rev) == -1)
1742 return -3;
1744 return -3;
1743 break;
1745 break;
1744 }
1746 }
1745 }
1747 }
1746 } else {
1748 } else {
1747 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1749 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1748 const char *n = index_node(self, rev);
1750 const char *n = index_node(self, rev);
1749 if (n == NULL) {
1751 if (n == NULL) {
1750 self->ntrev = rev + 1;
1752 self->ntrev = rev + 1;
1751 return -2;
1753 return -2;
1752 }
1754 }
1753 if (nt_insert(self, n, rev) == -1) {
1755 if (nt_insert(self, n, rev) == -1) {
1754 self->ntrev = rev + 1;
1756 self->ntrev = rev + 1;
1755 return -3;
1757 return -3;
1756 }
1758 }
1757 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1759 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1758 break;
1760 break;
1759 }
1761 }
1760 }
1762 }
1761 self->ntrev = rev;
1763 self->ntrev = rev;
1762 }
1764 }
1763
1765
1764 if (rev >= 0)
1766 if (rev >= 0)
1765 return rev;
1767 return rev;
1766 return -2;
1768 return -2;
1767 }
1769 }
1768
1770
1769 static void raise_revlog_error(void)
1771 static void raise_revlog_error(void)
1770 {
1772 {
1771 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1773 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1772
1774
1773 mod = PyImport_ImportModule("mercurial.error");
1775 mod = PyImport_ImportModule("mercurial.error");
1774 if (mod == NULL) {
1776 if (mod == NULL) {
1775 goto cleanup;
1777 goto cleanup;
1776 }
1778 }
1777
1779
1778 dict = PyModule_GetDict(mod);
1780 dict = PyModule_GetDict(mod);
1779 if (dict == NULL) {
1781 if (dict == NULL) {
1780 goto cleanup;
1782 goto cleanup;
1781 }
1783 }
1782 Py_INCREF(dict);
1784 Py_INCREF(dict);
1783
1785
1784 errclass = PyDict_GetItemString(dict, "RevlogError");
1786 errclass = PyDict_GetItemString(dict, "RevlogError");
1785 if (errclass == NULL) {
1787 if (errclass == NULL) {
1786 PyErr_SetString(PyExc_SystemError,
1788 PyErr_SetString(PyExc_SystemError,
1787 "could not find RevlogError");
1789 "could not find RevlogError");
1788 goto cleanup;
1790 goto cleanup;
1789 }
1791 }
1790
1792
1791 /* value of exception is ignored by callers */
1793 /* value of exception is ignored by callers */
1792 PyErr_SetString(errclass, "RevlogError");
1794 PyErr_SetString(errclass, "RevlogError");
1793
1795
1794 cleanup:
1796 cleanup:
1795 Py_XDECREF(dict);
1797 Py_XDECREF(dict);
1796 Py_XDECREF(mod);
1798 Py_XDECREF(mod);
1797 }
1799 }
1798
1800
1799 static PyObject *index_getitem(indexObject *self, PyObject *value)
1801 static PyObject *index_getitem(indexObject *self, PyObject *value)
1800 {
1802 {
1801 char *node;
1803 char *node;
1802 Py_ssize_t nodelen;
1804 Py_ssize_t nodelen;
1803 int rev;
1805 int rev;
1804
1806
1805 if (PyInt_Check(value))
1807 if (PyInt_Check(value))
1806 return index_get(self, PyInt_AS_LONG(value));
1808 return index_get(self, PyInt_AS_LONG(value));
1807
1809
1808 if (node_check(value, &node, &nodelen) == -1)
1810 if (node_check(value, &node, &nodelen) == -1)
1809 return NULL;
1811 return NULL;
1810 rev = index_find_node(self, node, nodelen);
1812 rev = index_find_node(self, node, nodelen);
1811 if (rev >= -1)
1813 if (rev >= -1)
1812 return PyInt_FromLong(rev);
1814 return PyInt_FromLong(rev);
1813 if (rev == -2)
1815 if (rev == -2)
1814 raise_revlog_error();
1816 raise_revlog_error();
1815 return NULL;
1817 return NULL;
1816 }
1818 }
1817
1819
1818 static int nt_partialmatch(indexObject *self, const char *node,
1820 static int nt_partialmatch(indexObject *self, const char *node,
1819 Py_ssize_t nodelen)
1821 Py_ssize_t nodelen)
1820 {
1822 {
1821 int rev;
1823 int rev;
1822
1824
1823 if (nt_init(self) == -1)
1825 if (nt_init(self) == -1)
1824 return -3;
1826 return -3;
1825
1827
1826 if (self->ntrev > 0) {
1828 if (self->ntrev > 0) {
1827 /* ensure that the radix tree is fully populated */
1829 /* ensure that the radix tree is fully populated */
1828 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1830 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1829 const char *n = index_node(self, rev);
1831 const char *n = index_node(self, rev);
1830 if (n == NULL)
1832 if (n == NULL)
1831 return -2;
1833 return -2;
1832 if (nt_insert(self, n, rev) == -1)
1834 if (nt_insert(self, n, rev) == -1)
1833 return -3;
1835 return -3;
1834 }
1836 }
1835 self->ntrev = rev;
1837 self->ntrev = rev;
1836 }
1838 }
1837
1839
1838 return nt_find(self, node, nodelen, 1);
1840 return nt_find(self, node, nodelen, 1);
1839 }
1841 }
1840
1842
1841 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1843 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1842 {
1844 {
1843 const char *fullnode;
1845 const char *fullnode;
1844 int nodelen;
1846 int nodelen;
1845 char *node;
1847 char *node;
1846 int rev, i;
1848 int rev, i;
1847
1849
1848 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1850 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1849 return NULL;
1851 return NULL;
1850
1852
1851 if (nodelen < 4) {
1853 if (nodelen < 4) {
1852 PyErr_SetString(PyExc_ValueError, "key too short");
1854 PyErr_SetString(PyExc_ValueError, "key too short");
1853 return NULL;
1855 return NULL;
1854 }
1856 }
1855
1857
1856 if (nodelen > 40) {
1858 if (nodelen > 40) {
1857 PyErr_SetString(PyExc_ValueError, "key too long");
1859 PyErr_SetString(PyExc_ValueError, "key too long");
1858 return NULL;
1860 return NULL;
1859 }
1861 }
1860
1862
1861 for (i = 0; i < nodelen; i++)
1863 for (i = 0; i < nodelen; i++)
1862 hexdigit(node, i);
1864 hexdigit(node, i);
1863 if (PyErr_Occurred()) {
1865 if (PyErr_Occurred()) {
1864 /* input contains non-hex characters */
1866 /* input contains non-hex characters */
1865 PyErr_Clear();
1867 PyErr_Clear();
1866 Py_RETURN_NONE;
1868 Py_RETURN_NONE;
1867 }
1869 }
1868
1870
1869 rev = nt_partialmatch(self, node, nodelen);
1871 rev = nt_partialmatch(self, node, nodelen);
1870
1872
1871 switch (rev) {
1873 switch (rev) {
1872 case -4:
1874 case -4:
1873 raise_revlog_error();
1875 raise_revlog_error();
1874 case -3:
1876 case -3:
1875 return NULL;
1877 return NULL;
1876 case -2:
1878 case -2:
1877 Py_RETURN_NONE;
1879 Py_RETURN_NONE;
1878 case -1:
1880 case -1:
1879 return PyBytes_FromStringAndSize(nullid, 20);
1881 return PyBytes_FromStringAndSize(nullid, 20);
1880 }
1882 }
1881
1883
1882 fullnode = index_node(self, rev);
1884 fullnode = index_node(self, rev);
1883 if (fullnode == NULL) {
1885 if (fullnode == NULL) {
1884 PyErr_Format(PyExc_IndexError,
1886 PyErr_Format(PyExc_IndexError,
1885 "could not access rev %d", rev);
1887 "could not access rev %d", rev);
1886 return NULL;
1888 return NULL;
1887 }
1889 }
1888 return PyBytes_FromStringAndSize(fullnode, 20);
1890 return PyBytes_FromStringAndSize(fullnode, 20);
1889 }
1891 }
1890
1892
1891 static PyObject *index_m_get(indexObject *self, PyObject *args)
1893 static PyObject *index_m_get(indexObject *self, PyObject *args)
1892 {
1894 {
1893 Py_ssize_t nodelen;
1895 Py_ssize_t nodelen;
1894 PyObject *val;
1896 PyObject *val;
1895 char *node;
1897 char *node;
1896 int rev;
1898 int rev;
1897
1899
1898 if (!PyArg_ParseTuple(args, "O", &val))
1900 if (!PyArg_ParseTuple(args, "O", &val))
1899 return NULL;
1901 return NULL;
1900 if (node_check(val, &node, &nodelen) == -1)
1902 if (node_check(val, &node, &nodelen) == -1)
1901 return NULL;
1903 return NULL;
1902 rev = index_find_node(self, node, nodelen);
1904 rev = index_find_node(self, node, nodelen);
1903 if (rev == -3)
1905 if (rev == -3)
1904 return NULL;
1906 return NULL;
1905 if (rev == -2)
1907 if (rev == -2)
1906 Py_RETURN_NONE;
1908 Py_RETURN_NONE;
1907 return PyInt_FromLong(rev);
1909 return PyInt_FromLong(rev);
1908 }
1910 }
1909
1911
1910 static int index_contains(indexObject *self, PyObject *value)
1912 static int index_contains(indexObject *self, PyObject *value)
1911 {
1913 {
1912 char *node;
1914 char *node;
1913 Py_ssize_t nodelen;
1915 Py_ssize_t nodelen;
1914
1916
1915 if (PyInt_Check(value)) {
1917 if (PyInt_Check(value)) {
1916 long rev = PyInt_AS_LONG(value);
1918 long rev = PyInt_AS_LONG(value);
1917 return rev >= -1 && rev < index_length(self);
1919 return rev >= -1 && rev < index_length(self);
1918 }
1920 }
1919
1921
1920 if (node_check(value, &node, &nodelen) == -1)
1922 if (node_check(value, &node, &nodelen) == -1)
1921 return -1;
1923 return -1;
1922
1924
1923 switch (index_find_node(self, node, nodelen)) {
1925 switch (index_find_node(self, node, nodelen)) {
1924 case -3:
1926 case -3:
1925 return -1;
1927 return -1;
1926 case -2:
1928 case -2:
1927 return 0;
1929 return 0;
1928 default:
1930 default:
1929 return 1;
1931 return 1;
1930 }
1932 }
1931 }
1933 }
1932
1934
1933 typedef uint64_t bitmask;
1935 typedef uint64_t bitmask;
1934
1936
1935 /*
1937 /*
1936 * Given a disjoint set of revs, return all candidates for the
1938 * Given a disjoint set of revs, return all candidates for the
1937 * greatest common ancestor. In revset notation, this is the set
1939 * greatest common ancestor. In revset notation, this is the set
1938 * "heads(::a and ::b and ...)"
1940 * "heads(::a and ::b and ...)"
1939 */
1941 */
1940 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1942 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1941 int revcount)
1943 int revcount)
1942 {
1944 {
1943 const bitmask allseen = (1ull << revcount) - 1;
1945 const bitmask allseen = (1ull << revcount) - 1;
1944 const bitmask poison = 1ull << revcount;
1946 const bitmask poison = 1ull << revcount;
1945 PyObject *gca = PyList_New(0);
1947 PyObject *gca = PyList_New(0);
1946 int i, v, interesting;
1948 int i, v, interesting;
1947 int maxrev = -1;
1949 int maxrev = -1;
1948 bitmask sp;
1950 bitmask sp;
1949 bitmask *seen;
1951 bitmask *seen;
1950
1952
1951 if (gca == NULL)
1953 if (gca == NULL)
1952 return PyErr_NoMemory();
1954 return PyErr_NoMemory();
1953
1955
1954 for (i = 0; i < revcount; i++) {
1956 for (i = 0; i < revcount; i++) {
1955 if (revs[i] > maxrev)
1957 if (revs[i] > maxrev)
1956 maxrev = revs[i];
1958 maxrev = revs[i];
1957 }
1959 }
1958
1960
1959 seen = calloc(sizeof(*seen), maxrev + 1);
1961 seen = calloc(sizeof(*seen), maxrev + 1);
1960 if (seen == NULL) {
1962 if (seen == NULL) {
1961 Py_DECREF(gca);
1963 Py_DECREF(gca);
1962 return PyErr_NoMemory();
1964 return PyErr_NoMemory();
1963 }
1965 }
1964
1966
1965 for (i = 0; i < revcount; i++)
1967 for (i = 0; i < revcount; i++)
1966 seen[revs[i]] = 1ull << i;
1968 seen[revs[i]] = 1ull << i;
1967
1969
1968 interesting = revcount;
1970 interesting = revcount;
1969
1971
1970 for (v = maxrev; v >= 0 && interesting; v--) {
1972 for (v = maxrev; v >= 0 && interesting; v--) {
1971 bitmask sv = seen[v];
1973 bitmask sv = seen[v];
1972 int parents[2];
1974 int parents[2];
1973
1975
1974 if (!sv)
1976 if (!sv)
1975 continue;
1977 continue;
1976
1978
1977 if (sv < poison) {
1979 if (sv < poison) {
1978 interesting -= 1;
1980 interesting -= 1;
1979 if (sv == allseen) {
1981 if (sv == allseen) {
1980 PyObject *obj = PyInt_FromLong(v);
1982 PyObject *obj = PyInt_FromLong(v);
1981 if (obj == NULL)
1983 if (obj == NULL)
1982 goto bail;
1984 goto bail;
1983 if (PyList_Append(gca, obj) == -1) {
1985 if (PyList_Append(gca, obj) == -1) {
1984 Py_DECREF(obj);
1986 Py_DECREF(obj);
1985 goto bail;
1987 goto bail;
1986 }
1988 }
1987 sv |= poison;
1989 sv |= poison;
1988 for (i = 0; i < revcount; i++) {
1990 for (i = 0; i < revcount; i++) {
1989 if (revs[i] == v)
1991 if (revs[i] == v)
1990 goto done;
1992 goto done;
1991 }
1993 }
1992 }
1994 }
1993 }
1995 }
1994 if (index_get_parents(self, v, parents, maxrev) < 0)
1996 if (index_get_parents(self, v, parents, maxrev) < 0)
1995 goto bail;
1997 goto bail;
1996
1998
1997 for (i = 0; i < 2; i++) {
1999 for (i = 0; i < 2; i++) {
1998 int p = parents[i];
2000 int p = parents[i];
1999 if (p == -1)
2001 if (p == -1)
2000 continue;
2002 continue;
2001 sp = seen[p];
2003 sp = seen[p];
2002 if (sv < poison) {
2004 if (sv < poison) {
2003 if (sp == 0) {
2005 if (sp == 0) {
2004 seen[p] = sv;
2006 seen[p] = sv;
2005 interesting++;
2007 interesting++;
2006 }
2008 }
2007 else if (sp != sv)
2009 else if (sp != sv)
2008 seen[p] |= sv;
2010 seen[p] |= sv;
2009 } else {
2011 } else {
2010 if (sp && sp < poison)
2012 if (sp && sp < poison)
2011 interesting--;
2013 interesting--;
2012 seen[p] = sv;
2014 seen[p] = sv;
2013 }
2015 }
2014 }
2016 }
2015 }
2017 }
2016
2018
2017 done:
2019 done:
2018 free(seen);
2020 free(seen);
2019 return gca;
2021 return gca;
2020 bail:
2022 bail:
2021 free(seen);
2023 free(seen);
2022 Py_XDECREF(gca);
2024 Py_XDECREF(gca);
2023 return NULL;
2025 return NULL;
2024 }
2026 }
2025
2027
2026 /*
2028 /*
2027 * Given a disjoint set of revs, return the subset with the longest
2029 * Given a disjoint set of revs, return the subset with the longest
2028 * path to the root.
2030 * path to the root.
2029 */
2031 */
2030 static PyObject *find_deepest(indexObject *self, PyObject *revs)
2032 static PyObject *find_deepest(indexObject *self, PyObject *revs)
2031 {
2033 {
2032 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
2034 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
2033 static const Py_ssize_t capacity = 24;
2035 static const Py_ssize_t capacity = 24;
2034 int *depth, *interesting = NULL;
2036 int *depth, *interesting = NULL;
2035 int i, j, v, ninteresting;
2037 int i, j, v, ninteresting;
2036 PyObject *dict = NULL, *keys = NULL;
2038 PyObject *dict = NULL, *keys = NULL;
2037 long *seen = NULL;
2039 long *seen = NULL;
2038 int maxrev = -1;
2040 int maxrev = -1;
2039 long final;
2041 long final;
2040
2042
2041 if (revcount > capacity) {
2043 if (revcount > capacity) {
2042 PyErr_Format(PyExc_OverflowError,
2044 PyErr_Format(PyExc_OverflowError,
2043 "bitset size (%ld) > capacity (%ld)",
2045 "bitset size (%ld) > capacity (%ld)",
2044 (long)revcount, (long)capacity);
2046 (long)revcount, (long)capacity);
2045 return NULL;
2047 return NULL;
2046 }
2048 }
2047
2049
2048 for (i = 0; i < revcount; i++) {
2050 for (i = 0; i < revcount; i++) {
2049 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2051 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2050 if (n > maxrev)
2052 if (n > maxrev)
2051 maxrev = n;
2053 maxrev = n;
2052 }
2054 }
2053
2055
2054 depth = calloc(sizeof(*depth), maxrev + 1);
2056 depth = calloc(sizeof(*depth), maxrev + 1);
2055 if (depth == NULL)
2057 if (depth == NULL)
2056 return PyErr_NoMemory();
2058 return PyErr_NoMemory();
2057
2059
2058 seen = calloc(sizeof(*seen), maxrev + 1);
2060 seen = calloc(sizeof(*seen), maxrev + 1);
2059 if (seen == NULL) {
2061 if (seen == NULL) {
2060 PyErr_NoMemory();
2062 PyErr_NoMemory();
2061 goto bail;
2063 goto bail;
2062 }
2064 }
2063
2065
2064 interesting = calloc(sizeof(*interesting), 2 << revcount);
2066 interesting = calloc(sizeof(*interesting), 2 << revcount);
2065 if (interesting == NULL) {
2067 if (interesting == NULL) {
2066 PyErr_NoMemory();
2068 PyErr_NoMemory();
2067 goto bail;
2069 goto bail;
2068 }
2070 }
2069
2071
2070 if (PyList_Sort(revs) == -1)
2072 if (PyList_Sort(revs) == -1)
2071 goto bail;
2073 goto bail;
2072
2074
2073 for (i = 0; i < revcount; i++) {
2075 for (i = 0; i < revcount; i++) {
2074 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2076 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2075 long b = 1l << i;
2077 long b = 1l << i;
2076 depth[n] = 1;
2078 depth[n] = 1;
2077 seen[n] = b;
2079 seen[n] = b;
2078 interesting[b] = 1;
2080 interesting[b] = 1;
2079 }
2081 }
2080
2082
2081 ninteresting = (int)revcount;
2083 ninteresting = (int)revcount;
2082
2084
2083 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
2085 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
2084 int dv = depth[v];
2086 int dv = depth[v];
2085 int parents[2];
2087 int parents[2];
2086 long sv;
2088 long sv;
2087
2089
2088 if (dv == 0)
2090 if (dv == 0)
2089 continue;
2091 continue;
2090
2092
2091 sv = seen[v];
2093 sv = seen[v];
2092 if (index_get_parents(self, v, parents, maxrev) < 0)
2094 if (index_get_parents(self, v, parents, maxrev) < 0)
2093 goto bail;
2095 goto bail;
2094
2096
2095 for (i = 0; i < 2; i++) {
2097 for (i = 0; i < 2; i++) {
2096 int p = parents[i];
2098 int p = parents[i];
2097 long sp;
2099 long sp;
2098 int dp;
2100 int dp;
2099
2101
2100 if (p == -1)
2102 if (p == -1)
2101 continue;
2103 continue;
2102
2104
2103 dp = depth[p];
2105 dp = depth[p];
2104 sp = seen[p];
2106 sp = seen[p];
2105 if (dp <= dv) {
2107 if (dp <= dv) {
2106 depth[p] = dv + 1;
2108 depth[p] = dv + 1;
2107 if (sp != sv) {
2109 if (sp != sv) {
2108 interesting[sv] += 1;
2110 interesting[sv] += 1;
2109 seen[p] = sv;
2111 seen[p] = sv;
2110 if (sp) {
2112 if (sp) {
2111 interesting[sp] -= 1;
2113 interesting[sp] -= 1;
2112 if (interesting[sp] == 0)
2114 if (interesting[sp] == 0)
2113 ninteresting -= 1;
2115 ninteresting -= 1;
2114 }
2116 }
2115 }
2117 }
2116 }
2118 }
2117 else if (dv == dp - 1) {
2119 else if (dv == dp - 1) {
2118 long nsp = sp | sv;
2120 long nsp = sp | sv;
2119 if (nsp == sp)
2121 if (nsp == sp)
2120 continue;
2122 continue;
2121 seen[p] = nsp;
2123 seen[p] = nsp;
2122 interesting[sp] -= 1;
2124 interesting[sp] -= 1;
2123 if (interesting[sp] == 0 && interesting[nsp] > 0)
2125 if (interesting[sp] == 0 && interesting[nsp] > 0)
2124 ninteresting -= 1;
2126 ninteresting -= 1;
2125 interesting[nsp] += 1;
2127 interesting[nsp] += 1;
2126 }
2128 }
2127 }
2129 }
2128 interesting[sv] -= 1;
2130 interesting[sv] -= 1;
2129 if (interesting[sv] == 0)
2131 if (interesting[sv] == 0)
2130 ninteresting -= 1;
2132 ninteresting -= 1;
2131 }
2133 }
2132
2134
2133 final = 0;
2135 final = 0;
2134 j = ninteresting;
2136 j = ninteresting;
2135 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2137 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2136 if (interesting[i] == 0)
2138 if (interesting[i] == 0)
2137 continue;
2139 continue;
2138 final |= i;
2140 final |= i;
2139 j -= 1;
2141 j -= 1;
2140 }
2142 }
2141 if (final == 0) {
2143 if (final == 0) {
2142 keys = PyList_New(0);
2144 keys = PyList_New(0);
2143 goto bail;
2145 goto bail;
2144 }
2146 }
2145
2147
2146 dict = PyDict_New();
2148 dict = PyDict_New();
2147 if (dict == NULL)
2149 if (dict == NULL)
2148 goto bail;
2150 goto bail;
2149
2151
2150 for (i = 0; i < revcount; i++) {
2152 for (i = 0; i < revcount; i++) {
2151 PyObject *key;
2153 PyObject *key;
2152
2154
2153 if ((final & (1 << i)) == 0)
2155 if ((final & (1 << i)) == 0)
2154 continue;
2156 continue;
2155
2157
2156 key = PyList_GET_ITEM(revs, i);
2158 key = PyList_GET_ITEM(revs, i);
2157 Py_INCREF(key);
2159 Py_INCREF(key);
2158 Py_INCREF(Py_None);
2160 Py_INCREF(Py_None);
2159 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2161 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2160 Py_DECREF(key);
2162 Py_DECREF(key);
2161 Py_DECREF(Py_None);
2163 Py_DECREF(Py_None);
2162 goto bail;
2164 goto bail;
2163 }
2165 }
2164 }
2166 }
2165
2167
2166 keys = PyDict_Keys(dict);
2168 keys = PyDict_Keys(dict);
2167
2169
2168 bail:
2170 bail:
2169 free(depth);
2171 free(depth);
2170 free(seen);
2172 free(seen);
2171 free(interesting);
2173 free(interesting);
2172 Py_XDECREF(dict);
2174 Py_XDECREF(dict);
2173
2175
2174 return keys;
2176 return keys;
2175 }
2177 }
2176
2178
2177 /*
2179 /*
2178 * Given a (possibly overlapping) set of revs, return all the
2180 * Given a (possibly overlapping) set of revs, return all the
2179 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2181 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2180 */
2182 */
2181 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2183 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2182 {
2184 {
2183 PyObject *ret = NULL;
2185 PyObject *ret = NULL;
2184 Py_ssize_t argcount, i, len;
2186 Py_ssize_t argcount, i, len;
2185 bitmask repeat = 0;
2187 bitmask repeat = 0;
2186 int revcount = 0;
2188 int revcount = 0;
2187 int *revs;
2189 int *revs;
2188
2190
2189 argcount = PySequence_Length(args);
2191 argcount = PySequence_Length(args);
2190 revs = malloc(argcount * sizeof(*revs));
2192 revs = malloc(argcount * sizeof(*revs));
2191 if (argcount > 0 && revs == NULL)
2193 if (argcount > 0 && revs == NULL)
2192 return PyErr_NoMemory();
2194 return PyErr_NoMemory();
2193 len = index_length(self) - 1;
2195 len = index_length(self) - 1;
2194
2196
2195 for (i = 0; i < argcount; i++) {
2197 for (i = 0; i < argcount; i++) {
2196 static const int capacity = 24;
2198 static const int capacity = 24;
2197 PyObject *obj = PySequence_GetItem(args, i);
2199 PyObject *obj = PySequence_GetItem(args, i);
2198 bitmask x;
2200 bitmask x;
2199 long val;
2201 long val;
2200
2202
2201 if (!PyInt_Check(obj)) {
2203 if (!PyInt_Check(obj)) {
2202 PyErr_SetString(PyExc_TypeError,
2204 PyErr_SetString(PyExc_TypeError,
2203 "arguments must all be ints");
2205 "arguments must all be ints");
2204 Py_DECREF(obj);
2206 Py_DECREF(obj);
2205 goto bail;
2207 goto bail;
2206 }
2208 }
2207 val = PyInt_AsLong(obj);
2209 val = PyInt_AsLong(obj);
2208 Py_DECREF(obj);
2210 Py_DECREF(obj);
2209 if (val == -1) {
2211 if (val == -1) {
2210 ret = PyList_New(0);
2212 ret = PyList_New(0);
2211 goto done;
2213 goto done;
2212 }
2214 }
2213 if (val < 0 || val >= len) {
2215 if (val < 0 || val >= len) {
2214 PyErr_SetString(PyExc_IndexError,
2216 PyErr_SetString(PyExc_IndexError,
2215 "index out of range");
2217 "index out of range");
2216 goto bail;
2218 goto bail;
2217 }
2219 }
2218 /* this cheesy bloom filter lets us avoid some more
2220 /* this cheesy bloom filter lets us avoid some more
2219 * expensive duplicate checks in the common set-is-disjoint
2221 * expensive duplicate checks in the common set-is-disjoint
2220 * case */
2222 * case */
2221 x = 1ull << (val & 0x3f);
2223 x = 1ull << (val & 0x3f);
2222 if (repeat & x) {
2224 if (repeat & x) {
2223 int k;
2225 int k;
2224 for (k = 0; k < revcount; k++) {
2226 for (k = 0; k < revcount; k++) {
2225 if (val == revs[k])
2227 if (val == revs[k])
2226 goto duplicate;
2228 goto duplicate;
2227 }
2229 }
2228 }
2230 }
2229 else repeat |= x;
2231 else repeat |= x;
2230 if (revcount >= capacity) {
2232 if (revcount >= capacity) {
2231 PyErr_Format(PyExc_OverflowError,
2233 PyErr_Format(PyExc_OverflowError,
2232 "bitset size (%d) > capacity (%d)",
2234 "bitset size (%d) > capacity (%d)",
2233 revcount, capacity);
2235 revcount, capacity);
2234 goto bail;
2236 goto bail;
2235 }
2237 }
2236 revs[revcount++] = (int)val;
2238 revs[revcount++] = (int)val;
2237 duplicate:;
2239 duplicate:;
2238 }
2240 }
2239
2241
2240 if (revcount == 0) {
2242 if (revcount == 0) {
2241 ret = PyList_New(0);
2243 ret = PyList_New(0);
2242 goto done;
2244 goto done;
2243 }
2245 }
2244 if (revcount == 1) {
2246 if (revcount == 1) {
2245 PyObject *obj;
2247 PyObject *obj;
2246 ret = PyList_New(1);
2248 ret = PyList_New(1);
2247 if (ret == NULL)
2249 if (ret == NULL)
2248 goto bail;
2250 goto bail;
2249 obj = PyInt_FromLong(revs[0]);
2251 obj = PyInt_FromLong(revs[0]);
2250 if (obj == NULL)
2252 if (obj == NULL)
2251 goto bail;
2253 goto bail;
2252 PyList_SET_ITEM(ret, 0, obj);
2254 PyList_SET_ITEM(ret, 0, obj);
2253 goto done;
2255 goto done;
2254 }
2256 }
2255
2257
2256 ret = find_gca_candidates(self, revs, revcount);
2258 ret = find_gca_candidates(self, revs, revcount);
2257 if (ret == NULL)
2259 if (ret == NULL)
2258 goto bail;
2260 goto bail;
2259
2261
2260 done:
2262 done:
2261 free(revs);
2263 free(revs);
2262 return ret;
2264 return ret;
2263
2265
2264 bail:
2266 bail:
2265 free(revs);
2267 free(revs);
2266 Py_XDECREF(ret);
2268 Py_XDECREF(ret);
2267 return NULL;
2269 return NULL;
2268 }
2270 }
2269
2271
2270 /*
2272 /*
2271 * Given a (possibly overlapping) set of revs, return the greatest
2273 * Given a (possibly overlapping) set of revs, return the greatest
2272 * common ancestors: those with the longest path to the root.
2274 * common ancestors: those with the longest path to the root.
2273 */
2275 */
2274 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2276 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2275 {
2277 {
2276 PyObject *ret;
2278 PyObject *ret;
2277 PyObject *gca = index_commonancestorsheads(self, args);
2279 PyObject *gca = index_commonancestorsheads(self, args);
2278 if (gca == NULL)
2280 if (gca == NULL)
2279 return NULL;
2281 return NULL;
2280
2282
2281 if (PyList_GET_SIZE(gca) <= 1) {
2283 if (PyList_GET_SIZE(gca) <= 1) {
2282 return gca;
2284 return gca;
2283 }
2285 }
2284
2286
2285 ret = find_deepest(self, gca);
2287 ret = find_deepest(self, gca);
2286 Py_DECREF(gca);
2288 Py_DECREF(gca);
2287 return ret;
2289 return ret;
2288 }
2290 }
2289
2291
2290 /*
2292 /*
2291 * Invalidate any trie entries introduced by added revs.
2293 * Invalidate any trie entries introduced by added revs.
2292 */
2294 */
2293 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
2295 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
2294 {
2296 {
2295 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2297 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2296
2298
2297 for (i = start; i < len; i++) {
2299 for (i = start; i < len; i++) {
2298 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2300 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2299 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2301 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2300
2302
2301 nt_insert(self, PyBytes_AS_STRING(node), -1);
2303 nt_insert(self, PyBytes_AS_STRING(node), -1);
2302 }
2304 }
2303
2305
2304 if (start == 0)
2306 if (start == 0)
2305 Py_CLEAR(self->added);
2307 Py_CLEAR(self->added);
2306 }
2308 }
2307
2309
2308 /*
2310 /*
2309 * Delete a numeric range of revs, which must be at the end of the
2311 * Delete a numeric range of revs, which must be at the end of the
2310 * range, but exclude the sentinel nullid entry.
2312 * range, but exclude the sentinel nullid entry.
2311 */
2313 */
2312 static int index_slice_del(indexObject *self, PyObject *item)
2314 static int index_slice_del(indexObject *self, PyObject *item)
2313 {
2315 {
2314 Py_ssize_t start, stop, step, slicelength;
2316 Py_ssize_t start, stop, step, slicelength;
2315 Py_ssize_t length = index_length(self);
2317 Py_ssize_t length = index_length(self);
2316 int ret = 0;
2318 int ret = 0;
2317
2319
2318 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
2320 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
2319 #ifdef IS_PY3K
2321 #ifdef IS_PY3K
2320 if (PySlice_GetIndicesEx(item, length,
2322 if (PySlice_GetIndicesEx(item, length,
2321 #else
2323 #else
2322 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
2324 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
2323 #endif
2325 #endif
2324 &start, &stop, &step, &slicelength) < 0)
2326 &start, &stop, &step, &slicelength) < 0)
2325 return -1;
2327 return -1;
2326
2328
2327 if (slicelength <= 0)
2329 if (slicelength <= 0)
2328 return 0;
2330 return 0;
2329
2331
2330 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2332 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2331 stop = start;
2333 stop = start;
2332
2334
2333 if (step < 0) {
2335 if (step < 0) {
2334 stop = start + 1;
2336 stop = start + 1;
2335 start = stop + step*(slicelength - 1) - 1;
2337 start = stop + step*(slicelength - 1) - 1;
2336 step = -step;
2338 step = -step;
2337 }
2339 }
2338
2340
2339 if (step != 1) {
2341 if (step != 1) {
2340 PyErr_SetString(PyExc_ValueError,
2342 PyErr_SetString(PyExc_ValueError,
2341 "revlog index delete requires step size of 1");
2343 "revlog index delete requires step size of 1");
2342 return -1;
2344 return -1;
2343 }
2345 }
2344
2346
2345 if (stop != length - 1) {
2347 if (stop != length - 1) {
2346 PyErr_SetString(PyExc_IndexError,
2348 PyErr_SetString(PyExc_IndexError,
2347 "revlog index deletion indices are invalid");
2349 "revlog index deletion indices are invalid");
2348 return -1;
2350 return -1;
2349 }
2351 }
2350
2352
2351 if (start < self->length - 1) {
2353 if (start < self->length - 1) {
2352 if (self->nt) {
2354 if (self->nt) {
2353 Py_ssize_t i;
2355 Py_ssize_t i;
2354
2356
2355 for (i = start + 1; i < self->length - 1; i++) {
2357 for (i = start + 1; i < self->length - 1; i++) {
2356 const char *node = index_node(self, i);
2358 const char *node = index_node(self, i);
2357
2359
2358 if (node)
2360 if (node)
2359 nt_insert(self, node, -1);
2361 nt_insert(self, node, -1);
2360 }
2362 }
2361 if (self->added)
2363 if (self->added)
2362 nt_invalidate_added(self, 0);
2364 nt_invalidate_added(self, 0);
2363 if (self->ntrev > start)
2365 if (self->ntrev > start)
2364 self->ntrev = (int)start;
2366 self->ntrev = (int)start;
2365 }
2367 }
2366 self->length = start + 1;
2368 self->length = start + 1;
2367 if (start < self->raw_length) {
2369 if (start < self->raw_length) {
2368 if (self->cache) {
2370 if (self->cache) {
2369 Py_ssize_t i;
2371 Py_ssize_t i;
2370 for (i = start; i < self->raw_length; i++)
2372 for (i = start; i < self->raw_length; i++)
2371 Py_CLEAR(self->cache[i]);
2373 Py_CLEAR(self->cache[i]);
2372 }
2374 }
2373 self->raw_length = start;
2375 self->raw_length = start;
2374 }
2376 }
2375 goto done;
2377 goto done;
2376 }
2378 }
2377
2379
2378 if (self->nt) {
2380 if (self->nt) {
2379 nt_invalidate_added(self, start - self->length + 1);
2381 nt_invalidate_added(self, start - self->length + 1);
2380 if (self->ntrev > start)
2382 if (self->ntrev > start)
2381 self->ntrev = (int)start;
2383 self->ntrev = (int)start;
2382 }
2384 }
2383 if (self->added)
2385 if (self->added)
2384 ret = PyList_SetSlice(self->added, start - self->length + 1,
2386 ret = PyList_SetSlice(self->added, start - self->length + 1,
2385 PyList_GET_SIZE(self->added), NULL);
2387 PyList_GET_SIZE(self->added), NULL);
2386 done:
2388 done:
2387 Py_CLEAR(self->headrevs);
2389 Py_CLEAR(self->headrevs);
2388 return ret;
2390 return ret;
2389 }
2391 }
2390
2392
2391 /*
2393 /*
2392 * Supported ops:
2394 * Supported ops:
2393 *
2395 *
2394 * slice deletion
2396 * slice deletion
2395 * string assignment (extend node->rev mapping)
2397 * string assignment (extend node->rev mapping)
2396 * string deletion (shrink node->rev mapping)
2398 * string deletion (shrink node->rev mapping)
2397 */
2399 */
2398 static int index_assign_subscript(indexObject *self, PyObject *item,
2400 static int index_assign_subscript(indexObject *self, PyObject *item,
2399 PyObject *value)
2401 PyObject *value)
2400 {
2402 {
2401 char *node;
2403 char *node;
2402 Py_ssize_t nodelen;
2404 Py_ssize_t nodelen;
2403 long rev;
2405 long rev;
2404
2406
2405 if (PySlice_Check(item) && value == NULL)
2407 if (PySlice_Check(item) && value == NULL)
2406 return index_slice_del(self, item);
2408 return index_slice_del(self, item);
2407
2409
2408 if (node_check(item, &node, &nodelen) == -1)
2410 if (node_check(item, &node, &nodelen) == -1)
2409 return -1;
2411 return -1;
2410
2412
2411 if (value == NULL)
2413 if (value == NULL)
2412 return self->nt ? nt_insert(self, node, -1) : 0;
2414 return self->nt ? nt_insert(self, node, -1) : 0;
2413 rev = PyInt_AsLong(value);
2415 rev = PyInt_AsLong(value);
2414 if (rev > INT_MAX || rev < 0) {
2416 if (rev > INT_MAX || rev < 0) {
2415 if (!PyErr_Occurred())
2417 if (!PyErr_Occurred())
2416 PyErr_SetString(PyExc_ValueError, "rev out of range");
2418 PyErr_SetString(PyExc_ValueError, "rev out of range");
2417 return -1;
2419 return -1;
2418 }
2420 }
2419
2421
2420 if (nt_init(self) == -1)
2422 if (nt_init(self) == -1)
2421 return -1;
2423 return -1;
2422 return nt_insert(self, node, (int)rev);
2424 return nt_insert(self, node, (int)rev);
2423 }
2425 }
2424
2426
2425 /*
2427 /*
2426 * Find all RevlogNG entries in an index that has inline data. Update
2428 * Find all RevlogNG entries in an index that has inline data. Update
2427 * the optional "offsets" table with those entries.
2429 * the optional "offsets" table with those entries.
2428 */
2430 */
2429 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2431 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2430 {
2432 {
2431 const char *data = (const char *)self->buf.buf;
2433 const char *data = (const char *)self->buf.buf;
2432 Py_ssize_t pos = 0;
2434 Py_ssize_t pos = 0;
2433 Py_ssize_t end = self->buf.len;
2435 Py_ssize_t end = self->buf.len;
2434 long incr = v1_hdrsize;
2436 long incr = v1_hdrsize;
2435 Py_ssize_t len = 0;
2437 Py_ssize_t len = 0;
2436
2438
2437 while (pos + v1_hdrsize <= end && pos >= 0) {
2439 while (pos + v1_hdrsize <= end && pos >= 0) {
2438 uint32_t comp_len;
2440 uint32_t comp_len;
2439 /* 3rd element of header is length of compressed inline data */
2441 /* 3rd element of header is length of compressed inline data */
2440 comp_len = getbe32(data + pos + 8);
2442 comp_len = getbe32(data + pos + 8);
2441 incr = v1_hdrsize + comp_len;
2443 incr = v1_hdrsize + comp_len;
2442 if (offsets)
2444 if (offsets)
2443 offsets[len] = data + pos;
2445 offsets[len] = data + pos;
2444 len++;
2446 len++;
2445 pos += incr;
2447 pos += incr;
2446 }
2448 }
2447
2449
2448 if (pos != end) {
2450 if (pos != end) {
2449 if (!PyErr_Occurred())
2451 if (!PyErr_Occurred())
2450 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2452 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2451 return -1;
2453 return -1;
2452 }
2454 }
2453
2455
2454 return len;
2456 return len;
2455 }
2457 }
2456
2458
2457 static int index_init(indexObject *self, PyObject *args)
2459 static int index_init(indexObject *self, PyObject *args)
2458 {
2460 {
2459 PyObject *data_obj, *inlined_obj;
2461 PyObject *data_obj, *inlined_obj;
2460 Py_ssize_t size;
2462 Py_ssize_t size;
2461
2463
2462 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2464 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2463 self->raw_length = 0;
2465 self->raw_length = 0;
2464 self->added = NULL;
2466 self->added = NULL;
2465 self->cache = NULL;
2467 self->cache = NULL;
2466 self->data = NULL;
2468 self->data = NULL;
2467 memset(&self->buf, 0, sizeof(self->buf));
2469 memset(&self->buf, 0, sizeof(self->buf));
2468 self->headrevs = NULL;
2470 self->headrevs = NULL;
2469 self->filteredrevs = Py_None;
2471 self->filteredrevs = Py_None;
2470 Py_INCREF(Py_None);
2472 Py_INCREF(Py_None);
2471 self->nt = NULL;
2473 self->nt = NULL;
2472 self->offsets = NULL;
2474 self->offsets = NULL;
2473
2475
2474 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2476 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2475 return -1;
2477 return -1;
2476 if (!PyObject_CheckBuffer(data_obj)) {
2478 if (!PyObject_CheckBuffer(data_obj)) {
2477 PyErr_SetString(PyExc_TypeError,
2479 PyErr_SetString(PyExc_TypeError,
2478 "data does not support buffer interface");
2480 "data does not support buffer interface");
2479 return -1;
2481 return -1;
2480 }
2482 }
2481
2483
2482 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
2484 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
2483 return -1;
2485 return -1;
2484 size = self->buf.len;
2486 size = self->buf.len;
2485
2487
2486 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2488 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2487 self->data = data_obj;
2489 self->data = data_obj;
2488
2490
2489 self->ntlength = self->ntcapacity = 0;
2491 self->ntlength = self->ntcapacity = 0;
2490 self->ntdepth = self->ntsplits = 0;
2492 self->ntdepth = self->ntsplits = 0;
2491 self->ntlookups = self->ntmisses = 0;
2493 self->ntlookups = self->ntmisses = 0;
2492 self->ntrev = -1;
2494 self->ntrev = -1;
2493 Py_INCREF(self->data);
2495 Py_INCREF(self->data);
2494
2496
2495 if (self->inlined) {
2497 if (self->inlined) {
2496 Py_ssize_t len = inline_scan(self, NULL);
2498 Py_ssize_t len = inline_scan(self, NULL);
2497 if (len == -1)
2499 if (len == -1)
2498 goto bail;
2500 goto bail;
2499 self->raw_length = len;
2501 self->raw_length = len;
2500 self->length = len + 1;
2502 self->length = len + 1;
2501 } else {
2503 } else {
2502 if (size % v1_hdrsize) {
2504 if (size % v1_hdrsize) {
2503 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2505 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2504 goto bail;
2506 goto bail;
2505 }
2507 }
2506 self->raw_length = size / v1_hdrsize;
2508 self->raw_length = size / v1_hdrsize;
2507 self->length = self->raw_length + 1;
2509 self->length = self->raw_length + 1;
2508 }
2510 }
2509
2511
2510 return 0;
2512 return 0;
2511 bail:
2513 bail:
2512 return -1;
2514 return -1;
2513 }
2515 }
2514
2516
2515 static PyObject *index_nodemap(indexObject *self)
2517 static PyObject *index_nodemap(indexObject *self)
2516 {
2518 {
2517 Py_INCREF(self);
2519 Py_INCREF(self);
2518 return (PyObject *)self;
2520 return (PyObject *)self;
2519 }
2521 }
2520
2522
2521 static void index_dealloc(indexObject *self)
2523 static void index_dealloc(indexObject *self)
2522 {
2524 {
2523 _index_clearcaches(self);
2525 _index_clearcaches(self);
2524 Py_XDECREF(self->filteredrevs);
2526 Py_XDECREF(self->filteredrevs);
2525 if (self->buf.buf) {
2527 if (self->buf.buf) {
2526 PyBuffer_Release(&self->buf);
2528 PyBuffer_Release(&self->buf);
2527 memset(&self->buf, 0, sizeof(self->buf));
2529 memset(&self->buf, 0, sizeof(self->buf));
2528 }
2530 }
2529 Py_XDECREF(self->data);
2531 Py_XDECREF(self->data);
2530 Py_XDECREF(self->added);
2532 Py_XDECREF(self->added);
2531 PyObject_Del(self);
2533 PyObject_Del(self);
2532 }
2534 }
2533
2535
2534 static PySequenceMethods index_sequence_methods = {
2536 static PySequenceMethods index_sequence_methods = {
2535 (lenfunc)index_length, /* sq_length */
2537 (lenfunc)index_length, /* sq_length */
2536 0, /* sq_concat */
2538 0, /* sq_concat */
2537 0, /* sq_repeat */
2539 0, /* sq_repeat */
2538 (ssizeargfunc)index_get, /* sq_item */
2540 (ssizeargfunc)index_get, /* sq_item */
2539 0, /* sq_slice */
2541 0, /* sq_slice */
2540 0, /* sq_ass_item */
2542 0, /* sq_ass_item */
2541 0, /* sq_ass_slice */
2543 0, /* sq_ass_slice */
2542 (objobjproc)index_contains, /* sq_contains */
2544 (objobjproc)index_contains, /* sq_contains */
2543 };
2545 };
2544
2546
2545 static PyMappingMethods index_mapping_methods = {
2547 static PyMappingMethods index_mapping_methods = {
2546 (lenfunc)index_length, /* mp_length */
2548 (lenfunc)index_length, /* mp_length */
2547 (binaryfunc)index_getitem, /* mp_subscript */
2549 (binaryfunc)index_getitem, /* mp_subscript */
2548 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2550 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2549 };
2551 };
2550
2552
2551 static PyMethodDef index_methods[] = {
2553 static PyMethodDef index_methods[] = {
2552 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2554 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2553 "return the gca set of the given revs"},
2555 "return the gca set of the given revs"},
2554 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2556 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2555 METH_VARARGS,
2557 METH_VARARGS,
2556 "return the heads of the common ancestors of the given revs"},
2558 "return the heads of the common ancestors of the given revs"},
2557 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2559 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2558 "clear the index caches"},
2560 "clear the index caches"},
2559 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2561 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2560 "get an index entry"},
2562 "get an index entry"},
2561 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
2563 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
2562 METH_VARARGS, "compute phases"},
2564 METH_VARARGS, "compute phases"},
2563 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
2565 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
2564 "reachableroots"},
2566 "reachableroots"},
2565 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2567 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2566 "get head revisions"}, /* Can do filtering since 3.2 */
2568 "get head revisions"}, /* Can do filtering since 3.2 */
2567 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2569 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2568 "get filtered head revisions"}, /* Can always do filtering */
2570 "get filtered head revisions"}, /* Can always do filtering */
2569 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2571 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2570 "insert an index entry"},
2572 "insert an index entry"},
2571 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2573 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2572 "match a potentially ambiguous node ID"},
2574 "match a potentially ambiguous node ID"},
2573 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2575 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2574 "stats for the index"},
2576 "stats for the index"},
2575 {NULL} /* Sentinel */
2577 {NULL} /* Sentinel */
2576 };
2578 };
2577
2579
2578 static PyGetSetDef index_getset[] = {
2580 static PyGetSetDef index_getset[] = {
2579 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2581 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2580 {NULL} /* Sentinel */
2582 {NULL} /* Sentinel */
2581 };
2583 };
2582
2584
2583 static PyTypeObject indexType = {
2585 static PyTypeObject indexType = {
2584 PyVarObject_HEAD_INIT(NULL, 0)
2586 PyVarObject_HEAD_INIT(NULL, 0)
2585 "parsers.index", /* tp_name */
2587 "parsers.index", /* tp_name */
2586 sizeof(indexObject), /* tp_basicsize */
2588 sizeof(indexObject), /* tp_basicsize */
2587 0, /* tp_itemsize */
2589 0, /* tp_itemsize */
2588 (destructor)index_dealloc, /* tp_dealloc */
2590 (destructor)index_dealloc, /* tp_dealloc */
2589 0, /* tp_print */
2591 0, /* tp_print */
2590 0, /* tp_getattr */
2592 0, /* tp_getattr */
2591 0, /* tp_setattr */
2593 0, /* tp_setattr */
2592 0, /* tp_compare */
2594 0, /* tp_compare */
2593 0, /* tp_repr */
2595 0, /* tp_repr */
2594 0, /* tp_as_number */
2596 0, /* tp_as_number */
2595 &index_sequence_methods, /* tp_as_sequence */
2597 &index_sequence_methods, /* tp_as_sequence */
2596 &index_mapping_methods, /* tp_as_mapping */
2598 &index_mapping_methods, /* tp_as_mapping */
2597 0, /* tp_hash */
2599 0, /* tp_hash */
2598 0, /* tp_call */
2600 0, /* tp_call */
2599 0, /* tp_str */
2601 0, /* tp_str */
2600 0, /* tp_getattro */
2602 0, /* tp_getattro */
2601 0, /* tp_setattro */
2603 0, /* tp_setattro */
2602 0, /* tp_as_buffer */
2604 0, /* tp_as_buffer */
2603 Py_TPFLAGS_DEFAULT, /* tp_flags */
2605 Py_TPFLAGS_DEFAULT, /* tp_flags */
2604 "revlog index", /* tp_doc */
2606 "revlog index", /* tp_doc */
2605 0, /* tp_traverse */
2607 0, /* tp_traverse */
2606 0, /* tp_clear */
2608 0, /* tp_clear */
2607 0, /* tp_richcompare */
2609 0, /* tp_richcompare */
2608 0, /* tp_weaklistoffset */
2610 0, /* tp_weaklistoffset */
2609 0, /* tp_iter */
2611 0, /* tp_iter */
2610 0, /* tp_iternext */
2612 0, /* tp_iternext */
2611 index_methods, /* tp_methods */
2613 index_methods, /* tp_methods */
2612 0, /* tp_members */
2614 0, /* tp_members */
2613 index_getset, /* tp_getset */
2615 index_getset, /* tp_getset */
2614 0, /* tp_base */
2616 0, /* tp_base */
2615 0, /* tp_dict */
2617 0, /* tp_dict */
2616 0, /* tp_descr_get */
2618 0, /* tp_descr_get */
2617 0, /* tp_descr_set */
2619 0, /* tp_descr_set */
2618 0, /* tp_dictoffset */
2620 0, /* tp_dictoffset */
2619 (initproc)index_init, /* tp_init */
2621 (initproc)index_init, /* tp_init */
2620 0, /* tp_alloc */
2622 0, /* tp_alloc */
2621 };
2623 };
2622
2624
2623 /*
2625 /*
2624 * returns a tuple of the form (index, index, cache) with elements as
2626 * returns a tuple of the form (index, index, cache) with elements as
2625 * follows:
2627 * follows:
2626 *
2628 *
2627 * index: an index object that lazily parses RevlogNG records
2629 * index: an index object that lazily parses RevlogNG records
2628 * cache: if data is inlined, a tuple (0, index_file_content), else None
2630 * cache: if data is inlined, a tuple (0, index_file_content), else None
2629 * index_file_content could be a string, or a buffer
2631 * index_file_content could be a string, or a buffer
2630 *
2632 *
2631 * added complications are for backwards compatibility
2633 * added complications are for backwards compatibility
2632 */
2634 */
2633 static PyObject *parse_index2(PyObject *self, PyObject *args)
2635 static PyObject *parse_index2(PyObject *self, PyObject *args)
2634 {
2636 {
2635 PyObject *tuple = NULL, *cache = NULL;
2637 PyObject *tuple = NULL, *cache = NULL;
2636 indexObject *idx;
2638 indexObject *idx;
2637 int ret;
2639 int ret;
2638
2640
2639 idx = PyObject_New(indexObject, &indexType);
2641 idx = PyObject_New(indexObject, &indexType);
2640 if (idx == NULL)
2642 if (idx == NULL)
2641 goto bail;
2643 goto bail;
2642
2644
2643 ret = index_init(idx, args);
2645 ret = index_init(idx, args);
2644 if (ret == -1)
2646 if (ret == -1)
2645 goto bail;
2647 goto bail;
2646
2648
2647 if (idx->inlined) {
2649 if (idx->inlined) {
2648 cache = Py_BuildValue("iO", 0, idx->data);
2650 cache = Py_BuildValue("iO", 0, idx->data);
2649 if (cache == NULL)
2651 if (cache == NULL)
2650 goto bail;
2652 goto bail;
2651 } else {
2653 } else {
2652 cache = Py_None;
2654 cache = Py_None;
2653 Py_INCREF(cache);
2655 Py_INCREF(cache);
2654 }
2656 }
2655
2657
2656 tuple = Py_BuildValue("NN", idx, cache);
2658 tuple = Py_BuildValue("NN", idx, cache);
2657 if (!tuple)
2659 if (!tuple)
2658 goto bail;
2660 goto bail;
2659 return tuple;
2661 return tuple;
2660
2662
2661 bail:
2663 bail:
2662 Py_XDECREF(idx);
2664 Py_XDECREF(idx);
2663 Py_XDECREF(cache);
2665 Py_XDECREF(cache);
2664 Py_XDECREF(tuple);
2666 Py_XDECREF(tuple);
2665 return NULL;
2667 return NULL;
2666 }
2668 }
2667
2669
2668 #define BUMPED_FIX 1
2670 #define BUMPED_FIX 1
2669 #define USING_SHA_256 2
2671 #define USING_SHA_256 2
2670 #define FM1_HEADER_SIZE (4 + 8 + 2 + 2 + 1 + 1 + 1)
2672 #define FM1_HEADER_SIZE (4 + 8 + 2 + 2 + 1 + 1 + 1)
2671
2673
2672 static PyObject *readshas(
2674 static PyObject *readshas(
2673 const char *source, unsigned char num, Py_ssize_t hashwidth)
2675 const char *source, unsigned char num, Py_ssize_t hashwidth)
2674 {
2676 {
2675 int i;
2677 int i;
2676 PyObject *list = PyTuple_New(num);
2678 PyObject *list = PyTuple_New(num);
2677 if (list == NULL) {
2679 if (list == NULL) {
2678 return NULL;
2680 return NULL;
2679 }
2681 }
2680 for (i = 0; i < num; i++) {
2682 for (i = 0; i < num; i++) {
2681 PyObject *hash = PyBytes_FromStringAndSize(source, hashwidth);
2683 PyObject *hash = PyBytes_FromStringAndSize(source, hashwidth);
2682 if (hash == NULL) {
2684 if (hash == NULL) {
2683 Py_DECREF(list);
2685 Py_DECREF(list);
2684 return NULL;
2686 return NULL;
2685 }
2687 }
2686 PyTuple_SET_ITEM(list, i, hash);
2688 PyTuple_SET_ITEM(list, i, hash);
2687 source += hashwidth;
2689 source += hashwidth;
2688 }
2690 }
2689 return list;
2691 return list;
2690 }
2692 }
2691
2693
2692 static PyObject *fm1readmarker(const char *databegin, const char *dataend,
2694 static PyObject *fm1readmarker(const char *databegin, const char *dataend,
2693 uint32_t *msize)
2695 uint32_t *msize)
2694 {
2696 {
2695 const char *data = databegin;
2697 const char *data = databegin;
2696 const char *meta;
2698 const char *meta;
2697
2699
2698 double mtime;
2700 double mtime;
2699 int16_t tz;
2701 int16_t tz;
2700 uint16_t flags;
2702 uint16_t flags;
2701 unsigned char nsuccs, nparents, nmetadata;
2703 unsigned char nsuccs, nparents, nmetadata;
2702 Py_ssize_t hashwidth = 20;
2704 Py_ssize_t hashwidth = 20;
2703
2705
2704 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2706 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2705 PyObject *metadata = NULL, *ret = NULL;
2707 PyObject *metadata = NULL, *ret = NULL;
2706 int i;
2708 int i;
2707
2709
2708 if (data + FM1_HEADER_SIZE > dataend) {
2710 if (data + FM1_HEADER_SIZE > dataend) {
2709 goto overflow;
2711 goto overflow;
2710 }
2712 }
2711
2713
2712 *msize = getbe32(data);
2714 *msize = getbe32(data);
2713 data += 4;
2715 data += 4;
2714 mtime = getbefloat64(data);
2716 mtime = getbefloat64(data);
2715 data += 8;
2717 data += 8;
2716 tz = getbeint16(data);
2718 tz = getbeint16(data);
2717 data += 2;
2719 data += 2;
2718 flags = getbeuint16(data);
2720 flags = getbeuint16(data);
2719 data += 2;
2721 data += 2;
2720
2722
2721 if (flags & USING_SHA_256) {
2723 if (flags & USING_SHA_256) {
2722 hashwidth = 32;
2724 hashwidth = 32;
2723 }
2725 }
2724
2726
2725 nsuccs = (unsigned char)(*data++);
2727 nsuccs = (unsigned char)(*data++);
2726 nparents = (unsigned char)(*data++);
2728 nparents = (unsigned char)(*data++);
2727 nmetadata = (unsigned char)(*data++);
2729 nmetadata = (unsigned char)(*data++);
2728
2730
2729 if (databegin + *msize > dataend) {
2731 if (databegin + *msize > dataend) {
2730 goto overflow;
2732 goto overflow;
2731 }
2733 }
2732 dataend = databegin + *msize; /* narrow down to marker size */
2734 dataend = databegin + *msize; /* narrow down to marker size */
2733
2735
2734 if (data + hashwidth > dataend) {
2736 if (data + hashwidth > dataend) {
2735 goto overflow;
2737 goto overflow;
2736 }
2738 }
2737 prec = PyBytes_FromStringAndSize(data, hashwidth);
2739 prec = PyBytes_FromStringAndSize(data, hashwidth);
2738 data += hashwidth;
2740 data += hashwidth;
2739 if (prec == NULL) {
2741 if (prec == NULL) {
2740 goto bail;
2742 goto bail;
2741 }
2743 }
2742
2744
2743 if (data + nsuccs * hashwidth > dataend) {
2745 if (data + nsuccs * hashwidth > dataend) {
2744 goto overflow;
2746 goto overflow;
2745 }
2747 }
2746 succs = readshas(data, nsuccs, hashwidth);
2748 succs = readshas(data, nsuccs, hashwidth);
2747 if (succs == NULL) {
2749 if (succs == NULL) {
2748 goto bail;
2750 goto bail;
2749 }
2751 }
2750 data += nsuccs * hashwidth;
2752 data += nsuccs * hashwidth;
2751
2753
2752 if (nparents == 1 || nparents == 2) {
2754 if (nparents == 1 || nparents == 2) {
2753 if (data + nparents * hashwidth > dataend) {
2755 if (data + nparents * hashwidth > dataend) {
2754 goto overflow;
2756 goto overflow;
2755 }
2757 }
2756 parents = readshas(data, nparents, hashwidth);
2758 parents = readshas(data, nparents, hashwidth);
2757 if (parents == NULL) {
2759 if (parents == NULL) {
2758 goto bail;
2760 goto bail;
2759 }
2761 }
2760 data += nparents * hashwidth;
2762 data += nparents * hashwidth;
2761 } else {
2763 } else {
2762 parents = Py_None;
2764 parents = Py_None;
2763 }
2765 }
2764
2766
2765 if (data + 2 * nmetadata > dataend) {
2767 if (data + 2 * nmetadata > dataend) {
2766 goto overflow;
2768 goto overflow;
2767 }
2769 }
2768 meta = data + (2 * nmetadata);
2770 meta = data + (2 * nmetadata);
2769 metadata = PyTuple_New(nmetadata);
2771 metadata = PyTuple_New(nmetadata);
2770 if (metadata == NULL) {
2772 if (metadata == NULL) {
2771 goto bail;
2773 goto bail;
2772 }
2774 }
2773 for (i = 0; i < nmetadata; i++) {
2775 for (i = 0; i < nmetadata; i++) {
2774 PyObject *tmp, *left = NULL, *right = NULL;
2776 PyObject *tmp, *left = NULL, *right = NULL;
2775 Py_ssize_t leftsize = (unsigned char)(*data++);
2777 Py_ssize_t leftsize = (unsigned char)(*data++);
2776 Py_ssize_t rightsize = (unsigned char)(*data++);
2778 Py_ssize_t rightsize = (unsigned char)(*data++);
2777 if (meta + leftsize + rightsize > dataend) {
2779 if (meta + leftsize + rightsize > dataend) {
2778 goto overflow;
2780 goto overflow;
2779 }
2781 }
2780 left = PyBytes_FromStringAndSize(meta, leftsize);
2782 left = PyBytes_FromStringAndSize(meta, leftsize);
2781 meta += leftsize;
2783 meta += leftsize;
2782 right = PyBytes_FromStringAndSize(meta, rightsize);
2784 right = PyBytes_FromStringAndSize(meta, rightsize);
2783 meta += rightsize;
2785 meta += rightsize;
2784 tmp = PyTuple_New(2);
2786 tmp = PyTuple_New(2);
2785 if (!left || !right || !tmp) {
2787 if (!left || !right || !tmp) {
2786 Py_XDECREF(left);
2788 Py_XDECREF(left);
2787 Py_XDECREF(right);
2789 Py_XDECREF(right);
2788 Py_XDECREF(tmp);
2790 Py_XDECREF(tmp);
2789 goto bail;
2791 goto bail;
2790 }
2792 }
2791 PyTuple_SET_ITEM(tmp, 0, left);
2793 PyTuple_SET_ITEM(tmp, 0, left);
2792 PyTuple_SET_ITEM(tmp, 1, right);
2794 PyTuple_SET_ITEM(tmp, 1, right);
2793 PyTuple_SET_ITEM(metadata, i, tmp);
2795 PyTuple_SET_ITEM(metadata, i, tmp);
2794 }
2796 }
2795 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2797 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2796 metadata, mtime, (int)tz * 60, parents);
2798 metadata, mtime, (int)tz * 60, parents);
2797 goto bail; /* return successfully */
2799 goto bail; /* return successfully */
2798
2800
2799 overflow:
2801 overflow:
2800 PyErr_SetString(PyExc_ValueError, "overflow in obsstore");
2802 PyErr_SetString(PyExc_ValueError, "overflow in obsstore");
2801 bail:
2803 bail:
2802 Py_XDECREF(prec);
2804 Py_XDECREF(prec);
2803 Py_XDECREF(succs);
2805 Py_XDECREF(succs);
2804 Py_XDECREF(metadata);
2806 Py_XDECREF(metadata);
2805 if (parents != Py_None)
2807 if (parents != Py_None)
2806 Py_XDECREF(parents);
2808 Py_XDECREF(parents);
2807 return ret;
2809 return ret;
2808 }
2810 }
2809
2811
2810
2812
2811 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2813 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2812 const char *data, *dataend;
2814 const char *data, *dataend;
2813 int datalen;
2815 int datalen;
2814 Py_ssize_t offset, stop;
2816 Py_ssize_t offset, stop;
2815 PyObject *markers = NULL;
2817 PyObject *markers = NULL;
2816
2818
2817 if (!PyArg_ParseTuple(args, "s#nn", &data, &datalen, &offset, &stop)) {
2819 if (!PyArg_ParseTuple(args, "s#nn", &data, &datalen, &offset, &stop)) {
2818 return NULL;
2820 return NULL;
2819 }
2821 }
2820 dataend = data + datalen;
2822 dataend = data + datalen;
2821 data += offset;
2823 data += offset;
2822 markers = PyList_New(0);
2824 markers = PyList_New(0);
2823 if (!markers) {
2825 if (!markers) {
2824 return NULL;
2826 return NULL;
2825 }
2827 }
2826 while (offset < stop) {
2828 while (offset < stop) {
2827 uint32_t msize;
2829 uint32_t msize;
2828 int error;
2830 int error;
2829 PyObject *record = fm1readmarker(data, dataend, &msize);
2831 PyObject *record = fm1readmarker(data, dataend, &msize);
2830 if (!record) {
2832 if (!record) {
2831 goto bail;
2833 goto bail;
2832 }
2834 }
2833 error = PyList_Append(markers, record);
2835 error = PyList_Append(markers, record);
2834 Py_DECREF(record);
2836 Py_DECREF(record);
2835 if (error) {
2837 if (error) {
2836 goto bail;
2838 goto bail;
2837 }
2839 }
2838 data += msize;
2840 data += msize;
2839 offset += msize;
2841 offset += msize;
2840 }
2842 }
2841 return markers;
2843 return markers;
2842 bail:
2844 bail:
2843 Py_DECREF(markers);
2845 Py_DECREF(markers);
2844 return NULL;
2846 return NULL;
2845 }
2847 }
2846
2848
2847 static char parsers_doc[] = "Efficient content parsing.";
2849 static char parsers_doc[] = "Efficient content parsing.";
2848
2850
2849 PyObject *encodedir(PyObject *self, PyObject *args);
2851 PyObject *encodedir(PyObject *self, PyObject *args);
2850 PyObject *pathencode(PyObject *self, PyObject *args);
2852 PyObject *pathencode(PyObject *self, PyObject *args);
2851 PyObject *lowerencode(PyObject *self, PyObject *args);
2853 PyObject *lowerencode(PyObject *self, PyObject *args);
2852
2854
2853 static PyMethodDef methods[] = {
2855 static PyMethodDef methods[] = {
2854 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2856 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2855 {"nonnormalentries", nonnormalentries, METH_VARARGS,
2857 {"nonnormalentries", nonnormalentries, METH_VARARGS,
2856 "create a set containing non-normal entries of given dirstate\n"},
2858 "create a set containing non-normal entries of given dirstate\n"},
2857 {"nonnormalotherparententries", nonnormalotherparententries, METH_VARARGS,
2859 {"nonnormalotherparententries", nonnormalotherparententries, METH_VARARGS,
2858 "create a set containing non-normal and other parent entries of given "
2860 "create a set containing non-normal and other parent entries of given "
2859 "dirstate\n"},
2861 "dirstate\n"},
2860 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2862 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2861 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2863 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2862 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2864 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2863 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2865 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2864 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
2866 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
2865 {"dict_new_presized", dict_new_presized, METH_VARARGS,
2867 {"dict_new_presized", dict_new_presized, METH_VARARGS,
2866 "construct a dict with an expected size\n"},
2868 "construct a dict with an expected size\n"},
2867 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
2869 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
2868 "make file foldmap\n"},
2870 "make file foldmap\n"},
2869 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2871 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2870 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2872 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2871 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2873 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2872 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2874 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2873 "parse v1 obsolete markers\n"},
2875 "parse v1 obsolete markers\n"},
2874 {NULL, NULL}
2876 {NULL, NULL}
2875 };
2877 };
2876
2878
2877 void dirs_module_init(PyObject *mod);
2879 void dirs_module_init(PyObject *mod);
2878 void manifest_module_init(PyObject *mod);
2880 void manifest_module_init(PyObject *mod);
2879
2881
2880 static void module_init(PyObject *mod)
2882 static void module_init(PyObject *mod)
2881 {
2883 {
2882 /* This module constant has two purposes. First, it lets us unit test
2884 /* This module constant has two purposes. First, it lets us unit test
2883 * the ImportError raised without hard-coding any error text. This
2885 * the ImportError raised without hard-coding any error text. This
2884 * means we can change the text in the future without breaking tests,
2886 * means we can change the text in the future without breaking tests,
2885 * even across changesets without a recompile. Second, its presence
2887 * even across changesets without a recompile. Second, its presence
2886 * can be used to determine whether the version-checking logic is
2888 * can be used to determine whether the version-checking logic is
2887 * present, which also helps in testing across changesets without a
2889 * present, which also helps in testing across changesets without a
2888 * recompile. Note that this means the pure-Python version of parsers
2890 * recompile. Note that this means the pure-Python version of parsers
2889 * should not have this module constant. */
2891 * should not have this module constant. */
2890 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2892 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2891
2893
2892 dirs_module_init(mod);
2894 dirs_module_init(mod);
2893 manifest_module_init(mod);
2895 manifest_module_init(mod);
2894
2896
2895 indexType.tp_new = PyType_GenericNew;
2897 indexType.tp_new = PyType_GenericNew;
2896 if (PyType_Ready(&indexType) < 0 ||
2898 if (PyType_Ready(&indexType) < 0 ||
2897 PyType_Ready(&dirstateTupleType) < 0)
2899 PyType_Ready(&dirstateTupleType) < 0)
2898 return;
2900 return;
2899 Py_INCREF(&indexType);
2901 Py_INCREF(&indexType);
2900 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2902 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2901 Py_INCREF(&dirstateTupleType);
2903 Py_INCREF(&dirstateTupleType);
2902 PyModule_AddObject(mod, "dirstatetuple",
2904 PyModule_AddObject(mod, "dirstatetuple",
2903 (PyObject *)&dirstateTupleType);
2905 (PyObject *)&dirstateTupleType);
2904
2906
2905 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2907 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2906 -1, -1, -1, -1, nullid, 20);
2908 -1, -1, -1, -1, nullid, 20);
2907 if (nullentry)
2909 if (nullentry)
2908 PyObject_GC_UnTrack(nullentry);
2910 PyObject_GC_UnTrack(nullentry);
2909 }
2911 }
2910
2912
2911 static int check_python_version(void)
2913 static int check_python_version(void)
2912 {
2914 {
2913 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2915 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2914 long hexversion;
2916 long hexversion;
2915 if (!sys)
2917 if (!sys)
2916 return -1;
2918 return -1;
2917 ver = PyObject_GetAttrString(sys, "hexversion");
2919 ver = PyObject_GetAttrString(sys, "hexversion");
2918 Py_DECREF(sys);
2920 Py_DECREF(sys);
2919 if (!ver)
2921 if (!ver)
2920 return -1;
2922 return -1;
2921 hexversion = PyInt_AsLong(ver);
2923 hexversion = PyInt_AsLong(ver);
2922 Py_DECREF(ver);
2924 Py_DECREF(ver);
2923 /* sys.hexversion is a 32-bit number by default, so the -1 case
2925 /* sys.hexversion is a 32-bit number by default, so the -1 case
2924 * should only occur in unusual circumstances (e.g. if sys.hexversion
2926 * should only occur in unusual circumstances (e.g. if sys.hexversion
2925 * is manually set to an invalid value). */
2927 * is manually set to an invalid value). */
2926 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2928 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2927 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2929 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2928 "modules were compiled with Python " PY_VERSION ", but "
2930 "modules were compiled with Python " PY_VERSION ", but "
2929 "Mercurial is currently using Python with sys.hexversion=%ld: "
2931 "Mercurial is currently using Python with sys.hexversion=%ld: "
2930 "Python %s\n at: %s", versionerrortext, hexversion,
2932 "Python %s\n at: %s", versionerrortext, hexversion,
2931 Py_GetVersion(), Py_GetProgramFullPath());
2933 Py_GetVersion(), Py_GetProgramFullPath());
2932 return -1;
2934 return -1;
2933 }
2935 }
2934 return 0;
2936 return 0;
2935 }
2937 }
2936
2938
2937 #ifdef IS_PY3K
2939 #ifdef IS_PY3K
2938 static struct PyModuleDef parsers_module = {
2940 static struct PyModuleDef parsers_module = {
2939 PyModuleDef_HEAD_INIT,
2941 PyModuleDef_HEAD_INIT,
2940 "parsers",
2942 "parsers",
2941 parsers_doc,
2943 parsers_doc,
2942 -1,
2944 -1,
2943 methods
2945 methods
2944 };
2946 };
2945
2947
2946 PyMODINIT_FUNC PyInit_parsers(void)
2948 PyMODINIT_FUNC PyInit_parsers(void)
2947 {
2949 {
2948 PyObject *mod;
2950 PyObject *mod;
2949
2951
2950 if (check_python_version() == -1)
2952 if (check_python_version() == -1)
2951 return NULL;
2953 return NULL;
2952 mod = PyModule_Create(&parsers_module);
2954 mod = PyModule_Create(&parsers_module);
2953 module_init(mod);
2955 module_init(mod);
2954 return mod;
2956 return mod;
2955 }
2957 }
2956 #else
2958 #else
2957 PyMODINIT_FUNC initparsers(void)
2959 PyMODINIT_FUNC initparsers(void)
2958 {
2960 {
2959 PyObject *mod;
2961 PyObject *mod;
2960
2962
2961 if (check_python_version() == -1)
2963 if (check_python_version() == -1)
2962 return;
2964 return;
2963 mod = Py_InitModule3("parsers", methods, parsers_doc);
2965 mod = Py_InitModule3("parsers", methods, parsers_doc);
2964 module_init(mod);
2966 module_init(mod);
2965 }
2967 }
2966 #endif
2968 #endif
General Comments 0
You need to be logged in to leave comments. Login now