##// END OF EJS Templates
phases: drop the list with phase of each rev, always comput phase sets...
Joerg Sonnenberger -
r35310:d1352633 default
parent child Browse files
Show More
@@ -1,794 +1,794
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 "bitmanipulation.h"
15 #include "bitmanipulation.h"
16 #include "charencode.h"
16 #include "charencode.h"
17 #include "util.h"
17 #include "util.h"
18
18
19 #ifdef IS_PY3K
19 #ifdef IS_PY3K
20 /* The mapping of Python types is meant to be temporary to get Python
20 /* The mapping of Python types is meant to be temporary to get Python
21 * 3 to compile. We should remove this once Python 3 support is fully
21 * 3 to compile. We should remove this once Python 3 support is fully
22 * supported and proper types are used in the extensions themselves. */
22 * supported and proper types are used in the extensions themselves. */
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_AsLong PyLong_AsLong
26 #define PyInt_AsLong PyLong_AsLong
27 #endif
27 #endif
28
28
29 static const char *const versionerrortext = "Python minor version mismatch";
29 static const char *const versionerrortext = "Python minor version mismatch";
30
30
31 static PyObject *dict_new_presized(PyObject *self, PyObject *args)
31 static PyObject *dict_new_presized(PyObject *self, PyObject *args)
32 {
32 {
33 Py_ssize_t expected_size;
33 Py_ssize_t expected_size;
34
34
35 if (!PyArg_ParseTuple(args, "n:make_presized_dict", &expected_size))
35 if (!PyArg_ParseTuple(args, "n:make_presized_dict", &expected_size))
36 return NULL;
36 return NULL;
37
37
38 return _dict_new_presized(expected_size);
38 return _dict_new_presized(expected_size);
39 }
39 }
40
40
41 /*
41 /*
42 * This code assumes that a manifest is stitched together with newline
42 * This code assumes that a manifest is stitched together with newline
43 * ('\n') characters.
43 * ('\n') characters.
44 */
44 */
45 static PyObject *parse_manifest(PyObject *self, PyObject *args)
45 static PyObject *parse_manifest(PyObject *self, PyObject *args)
46 {
46 {
47 PyObject *mfdict, *fdict;
47 PyObject *mfdict, *fdict;
48 char *str, *start, *end;
48 char *str, *start, *end;
49 int len;
49 int len;
50
50
51 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest", &PyDict_Type,
51 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest", &PyDict_Type,
52 &mfdict, &PyDict_Type, &fdict, &str, &len))
52 &mfdict, &PyDict_Type, &fdict, &str, &len))
53 goto quit;
53 goto quit;
54
54
55 start = str;
55 start = str;
56 end = str + len;
56 end = str + len;
57 while (start < end) {
57 while (start < end) {
58 PyObject *file = NULL, *node = NULL;
58 PyObject *file = NULL, *node = NULL;
59 PyObject *flags = NULL;
59 PyObject *flags = NULL;
60 char *zero = NULL, *newline = NULL;
60 char *zero = NULL, *newline = NULL;
61 ptrdiff_t nlen;
61 ptrdiff_t nlen;
62
62
63 zero = memchr(start, '\0', end - start);
63 zero = memchr(start, '\0', end - start);
64 if (!zero) {
64 if (!zero) {
65 PyErr_SetString(PyExc_ValueError,
65 PyErr_SetString(PyExc_ValueError,
66 "manifest entry has no separator");
66 "manifest entry has no separator");
67 goto quit;
67 goto quit;
68 }
68 }
69
69
70 newline = memchr(zero + 1, '\n', end - (zero + 1));
70 newline = memchr(zero + 1, '\n', end - (zero + 1));
71 if (!newline) {
71 if (!newline) {
72 PyErr_SetString(PyExc_ValueError,
72 PyErr_SetString(PyExc_ValueError,
73 "manifest contains trailing garbage");
73 "manifest contains trailing garbage");
74 goto quit;
74 goto quit;
75 }
75 }
76
76
77 file = PyBytes_FromStringAndSize(start, zero - start);
77 file = PyBytes_FromStringAndSize(start, zero - start);
78
78
79 if (!file)
79 if (!file)
80 goto bail;
80 goto bail;
81
81
82 nlen = newline - zero - 1;
82 nlen = newline - zero - 1;
83
83
84 node = unhexlify(zero + 1, nlen > 40 ? 40 : (Py_ssize_t)nlen);
84 node = unhexlify(zero + 1, nlen > 40 ? 40 : (Py_ssize_t)nlen);
85 if (!node)
85 if (!node)
86 goto bail;
86 goto bail;
87
87
88 if (nlen > 40) {
88 if (nlen > 40) {
89 flags = PyBytes_FromStringAndSize(zero + 41, nlen - 40);
89 flags = PyBytes_FromStringAndSize(zero + 41, nlen - 40);
90 if (!flags)
90 if (!flags)
91 goto bail;
91 goto bail;
92
92
93 if (PyDict_SetItem(fdict, file, flags) == -1)
93 if (PyDict_SetItem(fdict, file, flags) == -1)
94 goto bail;
94 goto bail;
95 }
95 }
96
96
97 if (PyDict_SetItem(mfdict, file, node) == -1)
97 if (PyDict_SetItem(mfdict, file, node) == -1)
98 goto bail;
98 goto bail;
99
99
100 start = newline + 1;
100 start = newline + 1;
101
101
102 Py_XDECREF(flags);
102 Py_XDECREF(flags);
103 Py_XDECREF(node);
103 Py_XDECREF(node);
104 Py_XDECREF(file);
104 Py_XDECREF(file);
105 continue;
105 continue;
106 bail:
106 bail:
107 Py_XDECREF(flags);
107 Py_XDECREF(flags);
108 Py_XDECREF(node);
108 Py_XDECREF(node);
109 Py_XDECREF(file);
109 Py_XDECREF(file);
110 goto quit;
110 goto quit;
111 }
111 }
112
112
113 Py_INCREF(Py_None);
113 Py_INCREF(Py_None);
114 return Py_None;
114 return Py_None;
115 quit:
115 quit:
116 return NULL;
116 return NULL;
117 }
117 }
118
118
119 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
119 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
120 int size, int mtime)
120 int size, int mtime)
121 {
121 {
122 dirstateTupleObject *t =
122 dirstateTupleObject *t =
123 PyObject_New(dirstateTupleObject, &dirstateTupleType);
123 PyObject_New(dirstateTupleObject, &dirstateTupleType);
124 if (!t)
124 if (!t)
125 return NULL;
125 return NULL;
126 t->state = state;
126 t->state = state;
127 t->mode = mode;
127 t->mode = mode;
128 t->size = size;
128 t->size = size;
129 t->mtime = mtime;
129 t->mtime = mtime;
130 return t;
130 return t;
131 }
131 }
132
132
133 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
133 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
134 PyObject *kwds)
134 PyObject *kwds)
135 {
135 {
136 /* We do all the initialization here and not a tp_init function because
136 /* We do all the initialization here and not a tp_init function because
137 * dirstate_tuple is immutable. */
137 * dirstate_tuple is immutable. */
138 dirstateTupleObject *t;
138 dirstateTupleObject *t;
139 char state;
139 char state;
140 int size, mode, mtime;
140 int size, mode, mtime;
141 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
141 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
142 return NULL;
142 return NULL;
143
143
144 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
144 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
145 if (!t)
145 if (!t)
146 return NULL;
146 return NULL;
147 t->state = state;
147 t->state = state;
148 t->mode = mode;
148 t->mode = mode;
149 t->size = size;
149 t->size = size;
150 t->mtime = mtime;
150 t->mtime = mtime;
151
151
152 return (PyObject *)t;
152 return (PyObject *)t;
153 }
153 }
154
154
155 static void dirstate_tuple_dealloc(PyObject *o)
155 static void dirstate_tuple_dealloc(PyObject *o)
156 {
156 {
157 PyObject_Del(o);
157 PyObject_Del(o);
158 }
158 }
159
159
160 static Py_ssize_t dirstate_tuple_length(PyObject *o)
160 static Py_ssize_t dirstate_tuple_length(PyObject *o)
161 {
161 {
162 return 4;
162 return 4;
163 }
163 }
164
164
165 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
165 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
166 {
166 {
167 dirstateTupleObject *t = (dirstateTupleObject *)o;
167 dirstateTupleObject *t = (dirstateTupleObject *)o;
168 switch (i) {
168 switch (i) {
169 case 0:
169 case 0:
170 return PyBytes_FromStringAndSize(&t->state, 1);
170 return PyBytes_FromStringAndSize(&t->state, 1);
171 case 1:
171 case 1:
172 return PyInt_FromLong(t->mode);
172 return PyInt_FromLong(t->mode);
173 case 2:
173 case 2:
174 return PyInt_FromLong(t->size);
174 return PyInt_FromLong(t->size);
175 case 3:
175 case 3:
176 return PyInt_FromLong(t->mtime);
176 return PyInt_FromLong(t->mtime);
177 default:
177 default:
178 PyErr_SetString(PyExc_IndexError, "index out of range");
178 PyErr_SetString(PyExc_IndexError, "index out of range");
179 return NULL;
179 return NULL;
180 }
180 }
181 }
181 }
182
182
183 static PySequenceMethods dirstate_tuple_sq = {
183 static PySequenceMethods dirstate_tuple_sq = {
184 dirstate_tuple_length, /* sq_length */
184 dirstate_tuple_length, /* sq_length */
185 0, /* sq_concat */
185 0, /* sq_concat */
186 0, /* sq_repeat */
186 0, /* sq_repeat */
187 dirstate_tuple_item, /* sq_item */
187 dirstate_tuple_item, /* sq_item */
188 0, /* sq_ass_item */
188 0, /* sq_ass_item */
189 0, /* sq_contains */
189 0, /* sq_contains */
190 0, /* sq_inplace_concat */
190 0, /* sq_inplace_concat */
191 0 /* sq_inplace_repeat */
191 0 /* sq_inplace_repeat */
192 };
192 };
193
193
194 PyTypeObject dirstateTupleType = {
194 PyTypeObject dirstateTupleType = {
195 PyVarObject_HEAD_INIT(NULL, 0) /* header */
195 PyVarObject_HEAD_INIT(NULL, 0) /* header */
196 "dirstate_tuple", /* tp_name */
196 "dirstate_tuple", /* tp_name */
197 sizeof(dirstateTupleObject), /* tp_basicsize */
197 sizeof(dirstateTupleObject), /* tp_basicsize */
198 0, /* tp_itemsize */
198 0, /* tp_itemsize */
199 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
199 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
200 0, /* tp_print */
200 0, /* tp_print */
201 0, /* tp_getattr */
201 0, /* tp_getattr */
202 0, /* tp_setattr */
202 0, /* tp_setattr */
203 0, /* tp_compare */
203 0, /* tp_compare */
204 0, /* tp_repr */
204 0, /* tp_repr */
205 0, /* tp_as_number */
205 0, /* tp_as_number */
206 &dirstate_tuple_sq, /* tp_as_sequence */
206 &dirstate_tuple_sq, /* tp_as_sequence */
207 0, /* tp_as_mapping */
207 0, /* tp_as_mapping */
208 0, /* tp_hash */
208 0, /* tp_hash */
209 0, /* tp_call */
209 0, /* tp_call */
210 0, /* tp_str */
210 0, /* tp_str */
211 0, /* tp_getattro */
211 0, /* tp_getattro */
212 0, /* tp_setattro */
212 0, /* tp_setattro */
213 0, /* tp_as_buffer */
213 0, /* tp_as_buffer */
214 Py_TPFLAGS_DEFAULT, /* tp_flags */
214 Py_TPFLAGS_DEFAULT, /* tp_flags */
215 "dirstate tuple", /* tp_doc */
215 "dirstate tuple", /* tp_doc */
216 0, /* tp_traverse */
216 0, /* tp_traverse */
217 0, /* tp_clear */
217 0, /* tp_clear */
218 0, /* tp_richcompare */
218 0, /* tp_richcompare */
219 0, /* tp_weaklistoffset */
219 0, /* tp_weaklistoffset */
220 0, /* tp_iter */
220 0, /* tp_iter */
221 0, /* tp_iternext */
221 0, /* tp_iternext */
222 0, /* tp_methods */
222 0, /* tp_methods */
223 0, /* tp_members */
223 0, /* tp_members */
224 0, /* tp_getset */
224 0, /* tp_getset */
225 0, /* tp_base */
225 0, /* tp_base */
226 0, /* tp_dict */
226 0, /* tp_dict */
227 0, /* tp_descr_get */
227 0, /* tp_descr_get */
228 0, /* tp_descr_set */
228 0, /* tp_descr_set */
229 0, /* tp_dictoffset */
229 0, /* tp_dictoffset */
230 0, /* tp_init */
230 0, /* tp_init */
231 0, /* tp_alloc */
231 0, /* tp_alloc */
232 dirstate_tuple_new, /* tp_new */
232 dirstate_tuple_new, /* tp_new */
233 };
233 };
234
234
235 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
235 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
236 {
236 {
237 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
237 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
238 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
238 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
239 char state, *cur, *str, *cpos;
239 char state, *cur, *str, *cpos;
240 int mode, size, mtime;
240 int mode, size, mtime;
241 unsigned int flen, len, pos = 40;
241 unsigned int flen, len, pos = 40;
242 int readlen;
242 int readlen;
243
243
244 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate", &PyDict_Type,
244 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate", &PyDict_Type,
245 &dmap, &PyDict_Type, &cmap, &str, &readlen))
245 &dmap, &PyDict_Type, &cmap, &str, &readlen))
246 goto quit;
246 goto quit;
247
247
248 len = readlen;
248 len = readlen;
249
249
250 /* read parents */
250 /* read parents */
251 if (len < 40) {
251 if (len < 40) {
252 PyErr_SetString(PyExc_ValueError,
252 PyErr_SetString(PyExc_ValueError,
253 "too little data for parents");
253 "too little data for parents");
254 goto quit;
254 goto quit;
255 }
255 }
256
256
257 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
257 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
258 if (!parents)
258 if (!parents)
259 goto quit;
259 goto quit;
260
260
261 /* read filenames */
261 /* read filenames */
262 while (pos >= 40 && pos < len) {
262 while (pos >= 40 && pos < len) {
263 if (pos + 17 > len) {
263 if (pos + 17 > len) {
264 PyErr_SetString(PyExc_ValueError,
264 PyErr_SetString(PyExc_ValueError,
265 "overflow in dirstate");
265 "overflow in dirstate");
266 goto quit;
266 goto quit;
267 }
267 }
268 cur = str + pos;
268 cur = str + pos;
269 /* unpack header */
269 /* unpack header */
270 state = *cur;
270 state = *cur;
271 mode = getbe32(cur + 1);
271 mode = getbe32(cur + 1);
272 size = getbe32(cur + 5);
272 size = getbe32(cur + 5);
273 mtime = getbe32(cur + 9);
273 mtime = getbe32(cur + 9);
274 flen = getbe32(cur + 13);
274 flen = getbe32(cur + 13);
275 pos += 17;
275 pos += 17;
276 cur += 17;
276 cur += 17;
277 if (flen > len - pos) {
277 if (flen > len - pos) {
278 PyErr_SetString(PyExc_ValueError,
278 PyErr_SetString(PyExc_ValueError,
279 "overflow in dirstate");
279 "overflow in dirstate");
280 goto quit;
280 goto quit;
281 }
281 }
282
282
283 entry =
283 entry =
284 (PyObject *)make_dirstate_tuple(state, mode, size, mtime);
284 (PyObject *)make_dirstate_tuple(state, mode, size, mtime);
285 cpos = memchr(cur, 0, flen);
285 cpos = memchr(cur, 0, flen);
286 if (cpos) {
286 if (cpos) {
287 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
287 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
288 cname = PyBytes_FromStringAndSize(
288 cname = PyBytes_FromStringAndSize(
289 cpos + 1, flen - (cpos - cur) - 1);
289 cpos + 1, flen - (cpos - cur) - 1);
290 if (!fname || !cname ||
290 if (!fname || !cname ||
291 PyDict_SetItem(cmap, fname, cname) == -1 ||
291 PyDict_SetItem(cmap, fname, cname) == -1 ||
292 PyDict_SetItem(dmap, fname, entry) == -1)
292 PyDict_SetItem(dmap, fname, entry) == -1)
293 goto quit;
293 goto quit;
294 Py_DECREF(cname);
294 Py_DECREF(cname);
295 } else {
295 } else {
296 fname = PyBytes_FromStringAndSize(cur, flen);
296 fname = PyBytes_FromStringAndSize(cur, flen);
297 if (!fname || PyDict_SetItem(dmap, fname, entry) == -1)
297 if (!fname || PyDict_SetItem(dmap, fname, entry) == -1)
298 goto quit;
298 goto quit;
299 }
299 }
300 Py_DECREF(fname);
300 Py_DECREF(fname);
301 Py_DECREF(entry);
301 Py_DECREF(entry);
302 fname = cname = entry = NULL;
302 fname = cname = entry = NULL;
303 pos += flen;
303 pos += flen;
304 }
304 }
305
305
306 ret = parents;
306 ret = parents;
307 Py_INCREF(ret);
307 Py_INCREF(ret);
308 quit:
308 quit:
309 Py_XDECREF(fname);
309 Py_XDECREF(fname);
310 Py_XDECREF(cname);
310 Py_XDECREF(cname);
311 Py_XDECREF(entry);
311 Py_XDECREF(entry);
312 Py_XDECREF(parents);
312 Py_XDECREF(parents);
313 return ret;
313 return ret;
314 }
314 }
315
315
316 /*
316 /*
317 * Build a set of non-normal and other parent entries from the dirstate dmap
317 * Build a set of non-normal and other parent entries from the dirstate dmap
318 */
318 */
319 static PyObject *nonnormalotherparententries(PyObject *self, PyObject *args)
319 static PyObject *nonnormalotherparententries(PyObject *self, PyObject *args)
320 {
320 {
321 PyObject *dmap, *fname, *v;
321 PyObject *dmap, *fname, *v;
322 PyObject *nonnset = NULL, *otherpset = NULL, *result = NULL;
322 PyObject *nonnset = NULL, *otherpset = NULL, *result = NULL;
323 Py_ssize_t pos;
323 Py_ssize_t pos;
324
324
325 if (!PyArg_ParseTuple(args, "O!:nonnormalentries", &PyDict_Type, &dmap))
325 if (!PyArg_ParseTuple(args, "O!:nonnormalentries", &PyDict_Type, &dmap))
326 goto bail;
326 goto bail;
327
327
328 nonnset = PySet_New(NULL);
328 nonnset = PySet_New(NULL);
329 if (nonnset == NULL)
329 if (nonnset == NULL)
330 goto bail;
330 goto bail;
331
331
332 otherpset = PySet_New(NULL);
332 otherpset = PySet_New(NULL);
333 if (otherpset == NULL)
333 if (otherpset == NULL)
334 goto bail;
334 goto bail;
335
335
336 pos = 0;
336 pos = 0;
337 while (PyDict_Next(dmap, &pos, &fname, &v)) {
337 while (PyDict_Next(dmap, &pos, &fname, &v)) {
338 dirstateTupleObject *t;
338 dirstateTupleObject *t;
339 if (!dirstate_tuple_check(v)) {
339 if (!dirstate_tuple_check(v)) {
340 PyErr_SetString(PyExc_TypeError,
340 PyErr_SetString(PyExc_TypeError,
341 "expected a dirstate tuple");
341 "expected a dirstate tuple");
342 goto bail;
342 goto bail;
343 }
343 }
344 t = (dirstateTupleObject *)v;
344 t = (dirstateTupleObject *)v;
345
345
346 if (t->state == 'n' && t->size == -2) {
346 if (t->state == 'n' && t->size == -2) {
347 if (PySet_Add(otherpset, fname) == -1) {
347 if (PySet_Add(otherpset, fname) == -1) {
348 goto bail;
348 goto bail;
349 }
349 }
350 }
350 }
351
351
352 if (t->state == 'n' && t->mtime != -1)
352 if (t->state == 'n' && t->mtime != -1)
353 continue;
353 continue;
354 if (PySet_Add(nonnset, fname) == -1)
354 if (PySet_Add(nonnset, fname) == -1)
355 goto bail;
355 goto bail;
356 }
356 }
357
357
358 result = Py_BuildValue("(OO)", nonnset, otherpset);
358 result = Py_BuildValue("(OO)", nonnset, otherpset);
359 if (result == NULL)
359 if (result == NULL)
360 goto bail;
360 goto bail;
361 Py_DECREF(nonnset);
361 Py_DECREF(nonnset);
362 Py_DECREF(otherpset);
362 Py_DECREF(otherpset);
363 return result;
363 return result;
364 bail:
364 bail:
365 Py_XDECREF(nonnset);
365 Py_XDECREF(nonnset);
366 Py_XDECREF(otherpset);
366 Py_XDECREF(otherpset);
367 Py_XDECREF(result);
367 Py_XDECREF(result);
368 return NULL;
368 return NULL;
369 }
369 }
370
370
371 /*
371 /*
372 * Efficiently pack a dirstate object into its on-disk format.
372 * Efficiently pack a dirstate object into its on-disk format.
373 */
373 */
374 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
374 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
375 {
375 {
376 PyObject *packobj = NULL;
376 PyObject *packobj = NULL;
377 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
377 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
378 Py_ssize_t nbytes, pos, l;
378 Py_ssize_t nbytes, pos, l;
379 PyObject *k, *v = NULL, *pn;
379 PyObject *k, *v = NULL, *pn;
380 char *p, *s;
380 char *p, *s;
381 int now;
381 int now;
382
382
383 if (!PyArg_ParseTuple(args, "O!O!Oi:pack_dirstate", &PyDict_Type, &map,
383 if (!PyArg_ParseTuple(args, "O!O!Oi:pack_dirstate", &PyDict_Type, &map,
384 &PyDict_Type, &copymap, &pl, &now))
384 &PyDict_Type, &copymap, &pl, &now))
385 return NULL;
385 return NULL;
386
386
387 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
387 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
388 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
388 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
389 return NULL;
389 return NULL;
390 }
390 }
391
391
392 /* Figure out how much we need to allocate. */
392 /* Figure out how much we need to allocate. */
393 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
393 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
394 PyObject *c;
394 PyObject *c;
395 if (!PyBytes_Check(k)) {
395 if (!PyBytes_Check(k)) {
396 PyErr_SetString(PyExc_TypeError, "expected string key");
396 PyErr_SetString(PyExc_TypeError, "expected string key");
397 goto bail;
397 goto bail;
398 }
398 }
399 nbytes += PyBytes_GET_SIZE(k) + 17;
399 nbytes += PyBytes_GET_SIZE(k) + 17;
400 c = PyDict_GetItem(copymap, k);
400 c = PyDict_GetItem(copymap, k);
401 if (c) {
401 if (c) {
402 if (!PyBytes_Check(c)) {
402 if (!PyBytes_Check(c)) {
403 PyErr_SetString(PyExc_TypeError,
403 PyErr_SetString(PyExc_TypeError,
404 "expected string key");
404 "expected string key");
405 goto bail;
405 goto bail;
406 }
406 }
407 nbytes += PyBytes_GET_SIZE(c) + 1;
407 nbytes += PyBytes_GET_SIZE(c) + 1;
408 }
408 }
409 }
409 }
410
410
411 packobj = PyBytes_FromStringAndSize(NULL, nbytes);
411 packobj = PyBytes_FromStringAndSize(NULL, nbytes);
412 if (packobj == NULL)
412 if (packobj == NULL)
413 goto bail;
413 goto bail;
414
414
415 p = PyBytes_AS_STRING(packobj);
415 p = PyBytes_AS_STRING(packobj);
416
416
417 pn = PySequence_ITEM(pl, 0);
417 pn = PySequence_ITEM(pl, 0);
418 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
418 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
419 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
419 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
420 goto bail;
420 goto bail;
421 }
421 }
422 memcpy(p, s, l);
422 memcpy(p, s, l);
423 p += 20;
423 p += 20;
424 pn = PySequence_ITEM(pl, 1);
424 pn = PySequence_ITEM(pl, 1);
425 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
425 if (PyBytes_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
426 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
426 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
427 goto bail;
427 goto bail;
428 }
428 }
429 memcpy(p, s, l);
429 memcpy(p, s, l);
430 p += 20;
430 p += 20;
431
431
432 for (pos = 0; PyDict_Next(map, &pos, &k, &v);) {
432 for (pos = 0; PyDict_Next(map, &pos, &k, &v);) {
433 dirstateTupleObject *tuple;
433 dirstateTupleObject *tuple;
434 char state;
434 char state;
435 int mode, size, mtime;
435 int mode, size, mtime;
436 Py_ssize_t len, l;
436 Py_ssize_t len, l;
437 PyObject *o;
437 PyObject *o;
438 char *t;
438 char *t;
439
439
440 if (!dirstate_tuple_check(v)) {
440 if (!dirstate_tuple_check(v)) {
441 PyErr_SetString(PyExc_TypeError,
441 PyErr_SetString(PyExc_TypeError,
442 "expected a dirstate tuple");
442 "expected a dirstate tuple");
443 goto bail;
443 goto bail;
444 }
444 }
445 tuple = (dirstateTupleObject *)v;
445 tuple = (dirstateTupleObject *)v;
446
446
447 state = tuple->state;
447 state = tuple->state;
448 mode = tuple->mode;
448 mode = tuple->mode;
449 size = tuple->size;
449 size = tuple->size;
450 mtime = tuple->mtime;
450 mtime = tuple->mtime;
451 if (state == 'n' && mtime == now) {
451 if (state == 'n' && mtime == now) {
452 /* See pure/parsers.py:pack_dirstate for why we do
452 /* See pure/parsers.py:pack_dirstate for why we do
453 * this. */
453 * this. */
454 mtime = -1;
454 mtime = -1;
455 mtime_unset = (PyObject *)make_dirstate_tuple(
455 mtime_unset = (PyObject *)make_dirstate_tuple(
456 state, mode, size, mtime);
456 state, mode, size, mtime);
457 if (!mtime_unset)
457 if (!mtime_unset)
458 goto bail;
458 goto bail;
459 if (PyDict_SetItem(map, k, mtime_unset) == -1)
459 if (PyDict_SetItem(map, k, mtime_unset) == -1)
460 goto bail;
460 goto bail;
461 Py_DECREF(mtime_unset);
461 Py_DECREF(mtime_unset);
462 mtime_unset = NULL;
462 mtime_unset = NULL;
463 }
463 }
464 *p++ = state;
464 *p++ = state;
465 putbe32((uint32_t)mode, p);
465 putbe32((uint32_t)mode, p);
466 putbe32((uint32_t)size, p + 4);
466 putbe32((uint32_t)size, p + 4);
467 putbe32((uint32_t)mtime, p + 8);
467 putbe32((uint32_t)mtime, p + 8);
468 t = p + 12;
468 t = p + 12;
469 p += 16;
469 p += 16;
470 len = PyBytes_GET_SIZE(k);
470 len = PyBytes_GET_SIZE(k);
471 memcpy(p, PyBytes_AS_STRING(k), len);
471 memcpy(p, PyBytes_AS_STRING(k), len);
472 p += len;
472 p += len;
473 o = PyDict_GetItem(copymap, k);
473 o = PyDict_GetItem(copymap, k);
474 if (o) {
474 if (o) {
475 *p++ = '\0';
475 *p++ = '\0';
476 l = PyBytes_GET_SIZE(o);
476 l = PyBytes_GET_SIZE(o);
477 memcpy(p, PyBytes_AS_STRING(o), l);
477 memcpy(p, PyBytes_AS_STRING(o), l);
478 p += l;
478 p += l;
479 len += l + 1;
479 len += l + 1;
480 }
480 }
481 putbe32((uint32_t)len, t);
481 putbe32((uint32_t)len, t);
482 }
482 }
483
483
484 pos = p - PyBytes_AS_STRING(packobj);
484 pos = p - PyBytes_AS_STRING(packobj);
485 if (pos != nbytes) {
485 if (pos != nbytes) {
486 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
486 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
487 (long)pos, (long)nbytes);
487 (long)pos, (long)nbytes);
488 goto bail;
488 goto bail;
489 }
489 }
490
490
491 return packobj;
491 return packobj;
492 bail:
492 bail:
493 Py_XDECREF(mtime_unset);
493 Py_XDECREF(mtime_unset);
494 Py_XDECREF(packobj);
494 Py_XDECREF(packobj);
495 Py_XDECREF(v);
495 Py_XDECREF(v);
496 return NULL;
496 return NULL;
497 }
497 }
498
498
499 #define BUMPED_FIX 1
499 #define BUMPED_FIX 1
500 #define USING_SHA_256 2
500 #define USING_SHA_256 2
501 #define FM1_HEADER_SIZE (4 + 8 + 2 + 2 + 1 + 1 + 1)
501 #define FM1_HEADER_SIZE (4 + 8 + 2 + 2 + 1 + 1 + 1)
502
502
503 static PyObject *readshas(const char *source, unsigned char num,
503 static PyObject *readshas(const char *source, unsigned char num,
504 Py_ssize_t hashwidth)
504 Py_ssize_t hashwidth)
505 {
505 {
506 int i;
506 int i;
507 PyObject *list = PyTuple_New(num);
507 PyObject *list = PyTuple_New(num);
508 if (list == NULL) {
508 if (list == NULL) {
509 return NULL;
509 return NULL;
510 }
510 }
511 for (i = 0; i < num; i++) {
511 for (i = 0; i < num; i++) {
512 PyObject *hash = PyBytes_FromStringAndSize(source, hashwidth);
512 PyObject *hash = PyBytes_FromStringAndSize(source, hashwidth);
513 if (hash == NULL) {
513 if (hash == NULL) {
514 Py_DECREF(list);
514 Py_DECREF(list);
515 return NULL;
515 return NULL;
516 }
516 }
517 PyTuple_SET_ITEM(list, i, hash);
517 PyTuple_SET_ITEM(list, i, hash);
518 source += hashwidth;
518 source += hashwidth;
519 }
519 }
520 return list;
520 return list;
521 }
521 }
522
522
523 static PyObject *fm1readmarker(const char *databegin, const char *dataend,
523 static PyObject *fm1readmarker(const char *databegin, const char *dataend,
524 uint32_t *msize)
524 uint32_t *msize)
525 {
525 {
526 const char *data = databegin;
526 const char *data = databegin;
527 const char *meta;
527 const char *meta;
528
528
529 double mtime;
529 double mtime;
530 int16_t tz;
530 int16_t tz;
531 uint16_t flags;
531 uint16_t flags;
532 unsigned char nsuccs, nparents, nmetadata;
532 unsigned char nsuccs, nparents, nmetadata;
533 Py_ssize_t hashwidth = 20;
533 Py_ssize_t hashwidth = 20;
534
534
535 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
535 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
536 PyObject *metadata = NULL, *ret = NULL;
536 PyObject *metadata = NULL, *ret = NULL;
537 int i;
537 int i;
538
538
539 if (data + FM1_HEADER_SIZE > dataend) {
539 if (data + FM1_HEADER_SIZE > dataend) {
540 goto overflow;
540 goto overflow;
541 }
541 }
542
542
543 *msize = getbe32(data);
543 *msize = getbe32(data);
544 data += 4;
544 data += 4;
545 mtime = getbefloat64(data);
545 mtime = getbefloat64(data);
546 data += 8;
546 data += 8;
547 tz = getbeint16(data);
547 tz = getbeint16(data);
548 data += 2;
548 data += 2;
549 flags = getbeuint16(data);
549 flags = getbeuint16(data);
550 data += 2;
550 data += 2;
551
551
552 if (flags & USING_SHA_256) {
552 if (flags & USING_SHA_256) {
553 hashwidth = 32;
553 hashwidth = 32;
554 }
554 }
555
555
556 nsuccs = (unsigned char)(*data++);
556 nsuccs = (unsigned char)(*data++);
557 nparents = (unsigned char)(*data++);
557 nparents = (unsigned char)(*data++);
558 nmetadata = (unsigned char)(*data++);
558 nmetadata = (unsigned char)(*data++);
559
559
560 if (databegin + *msize > dataend) {
560 if (databegin + *msize > dataend) {
561 goto overflow;
561 goto overflow;
562 }
562 }
563 dataend = databegin + *msize; /* narrow down to marker size */
563 dataend = databegin + *msize; /* narrow down to marker size */
564
564
565 if (data + hashwidth > dataend) {
565 if (data + hashwidth > dataend) {
566 goto overflow;
566 goto overflow;
567 }
567 }
568 prec = PyBytes_FromStringAndSize(data, hashwidth);
568 prec = PyBytes_FromStringAndSize(data, hashwidth);
569 data += hashwidth;
569 data += hashwidth;
570 if (prec == NULL) {
570 if (prec == NULL) {
571 goto bail;
571 goto bail;
572 }
572 }
573
573
574 if (data + nsuccs * hashwidth > dataend) {
574 if (data + nsuccs * hashwidth > dataend) {
575 goto overflow;
575 goto overflow;
576 }
576 }
577 succs = readshas(data, nsuccs, hashwidth);
577 succs = readshas(data, nsuccs, hashwidth);
578 if (succs == NULL) {
578 if (succs == NULL) {
579 goto bail;
579 goto bail;
580 }
580 }
581 data += nsuccs * hashwidth;
581 data += nsuccs * hashwidth;
582
582
583 if (nparents == 1 || nparents == 2) {
583 if (nparents == 1 || nparents == 2) {
584 if (data + nparents * hashwidth > dataend) {
584 if (data + nparents * hashwidth > dataend) {
585 goto overflow;
585 goto overflow;
586 }
586 }
587 parents = readshas(data, nparents, hashwidth);
587 parents = readshas(data, nparents, hashwidth);
588 if (parents == NULL) {
588 if (parents == NULL) {
589 goto bail;
589 goto bail;
590 }
590 }
591 data += nparents * hashwidth;
591 data += nparents * hashwidth;
592 } else {
592 } else {
593 parents = Py_None;
593 parents = Py_None;
594 Py_INCREF(parents);
594 Py_INCREF(parents);
595 }
595 }
596
596
597 if (data + 2 * nmetadata > dataend) {
597 if (data + 2 * nmetadata > dataend) {
598 goto overflow;
598 goto overflow;
599 }
599 }
600 meta = data + (2 * nmetadata);
600 meta = data + (2 * nmetadata);
601 metadata = PyTuple_New(nmetadata);
601 metadata = PyTuple_New(nmetadata);
602 if (metadata == NULL) {
602 if (metadata == NULL) {
603 goto bail;
603 goto bail;
604 }
604 }
605 for (i = 0; i < nmetadata; i++) {
605 for (i = 0; i < nmetadata; i++) {
606 PyObject *tmp, *left = NULL, *right = NULL;
606 PyObject *tmp, *left = NULL, *right = NULL;
607 Py_ssize_t leftsize = (unsigned char)(*data++);
607 Py_ssize_t leftsize = (unsigned char)(*data++);
608 Py_ssize_t rightsize = (unsigned char)(*data++);
608 Py_ssize_t rightsize = (unsigned char)(*data++);
609 if (meta + leftsize + rightsize > dataend) {
609 if (meta + leftsize + rightsize > dataend) {
610 goto overflow;
610 goto overflow;
611 }
611 }
612 left = PyBytes_FromStringAndSize(meta, leftsize);
612 left = PyBytes_FromStringAndSize(meta, leftsize);
613 meta += leftsize;
613 meta += leftsize;
614 right = PyBytes_FromStringAndSize(meta, rightsize);
614 right = PyBytes_FromStringAndSize(meta, rightsize);
615 meta += rightsize;
615 meta += rightsize;
616 tmp = PyTuple_New(2);
616 tmp = PyTuple_New(2);
617 if (!left || !right || !tmp) {
617 if (!left || !right || !tmp) {
618 Py_XDECREF(left);
618 Py_XDECREF(left);
619 Py_XDECREF(right);
619 Py_XDECREF(right);
620 Py_XDECREF(tmp);
620 Py_XDECREF(tmp);
621 goto bail;
621 goto bail;
622 }
622 }
623 PyTuple_SET_ITEM(tmp, 0, left);
623 PyTuple_SET_ITEM(tmp, 0, left);
624 PyTuple_SET_ITEM(tmp, 1, right);
624 PyTuple_SET_ITEM(tmp, 1, right);
625 PyTuple_SET_ITEM(metadata, i, tmp);
625 PyTuple_SET_ITEM(metadata, i, tmp);
626 }
626 }
627 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags, metadata, mtime,
627 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags, metadata, mtime,
628 (int)tz * 60, parents);
628 (int)tz * 60, parents);
629 goto bail; /* return successfully */
629 goto bail; /* return successfully */
630
630
631 overflow:
631 overflow:
632 PyErr_SetString(PyExc_ValueError, "overflow in obsstore");
632 PyErr_SetString(PyExc_ValueError, "overflow in obsstore");
633 bail:
633 bail:
634 Py_XDECREF(prec);
634 Py_XDECREF(prec);
635 Py_XDECREF(succs);
635 Py_XDECREF(succs);
636 Py_XDECREF(metadata);
636 Py_XDECREF(metadata);
637 Py_XDECREF(parents);
637 Py_XDECREF(parents);
638 return ret;
638 return ret;
639 }
639 }
640
640
641 static PyObject *fm1readmarkers(PyObject *self, PyObject *args)
641 static PyObject *fm1readmarkers(PyObject *self, PyObject *args)
642 {
642 {
643 const char *data, *dataend;
643 const char *data, *dataend;
644 int datalen;
644 int datalen;
645 Py_ssize_t offset, stop;
645 Py_ssize_t offset, stop;
646 PyObject *markers = NULL;
646 PyObject *markers = NULL;
647
647
648 if (!PyArg_ParseTuple(args, "s#nn", &data, &datalen, &offset, &stop)) {
648 if (!PyArg_ParseTuple(args, "s#nn", &data, &datalen, &offset, &stop)) {
649 return NULL;
649 return NULL;
650 }
650 }
651 dataend = data + datalen;
651 dataend = data + datalen;
652 data += offset;
652 data += offset;
653 markers = PyList_New(0);
653 markers = PyList_New(0);
654 if (!markers) {
654 if (!markers) {
655 return NULL;
655 return NULL;
656 }
656 }
657 while (offset < stop) {
657 while (offset < stop) {
658 uint32_t msize;
658 uint32_t msize;
659 int error;
659 int error;
660 PyObject *record = fm1readmarker(data, dataend, &msize);
660 PyObject *record = fm1readmarker(data, dataend, &msize);
661 if (!record) {
661 if (!record) {
662 goto bail;
662 goto bail;
663 }
663 }
664 error = PyList_Append(markers, record);
664 error = PyList_Append(markers, record);
665 Py_DECREF(record);
665 Py_DECREF(record);
666 if (error) {
666 if (error) {
667 goto bail;
667 goto bail;
668 }
668 }
669 data += msize;
669 data += msize;
670 offset += msize;
670 offset += msize;
671 }
671 }
672 return markers;
672 return markers;
673 bail:
673 bail:
674 Py_DECREF(markers);
674 Py_DECREF(markers);
675 return NULL;
675 return NULL;
676 }
676 }
677
677
678 static char parsers_doc[] = "Efficient content parsing.";
678 static char parsers_doc[] = "Efficient content parsing.";
679
679
680 PyObject *encodedir(PyObject *self, PyObject *args);
680 PyObject *encodedir(PyObject *self, PyObject *args);
681 PyObject *pathencode(PyObject *self, PyObject *args);
681 PyObject *pathencode(PyObject *self, PyObject *args);
682 PyObject *lowerencode(PyObject *self, PyObject *args);
682 PyObject *lowerencode(PyObject *self, PyObject *args);
683 PyObject *parse_index2(PyObject *self, PyObject *args);
683 PyObject *parse_index2(PyObject *self, PyObject *args);
684
684
685 static PyMethodDef methods[] = {
685 static PyMethodDef methods[] = {
686 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
686 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
687 {"nonnormalotherparententries", nonnormalotherparententries, METH_VARARGS,
687 {"nonnormalotherparententries", nonnormalotherparententries, METH_VARARGS,
688 "create a set containing non-normal and other parent entries of given "
688 "create a set containing non-normal and other parent entries of given "
689 "dirstate\n"},
689 "dirstate\n"},
690 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
690 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
691 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
691 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
692 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
692 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
693 {"isasciistr", isasciistr, METH_VARARGS, "check if an ASCII string\n"},
693 {"isasciistr", isasciistr, METH_VARARGS, "check if an ASCII string\n"},
694 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
694 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
695 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
695 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
696 {"dict_new_presized", dict_new_presized, METH_VARARGS,
696 {"dict_new_presized", dict_new_presized, METH_VARARGS,
697 "construct a dict with an expected size\n"},
697 "construct a dict with an expected size\n"},
698 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
698 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
699 "make file foldmap\n"},
699 "make file foldmap\n"},
700 {"jsonescapeu8fast", jsonescapeu8fast, METH_VARARGS,
700 {"jsonescapeu8fast", jsonescapeu8fast, METH_VARARGS,
701 "escape a UTF-8 byte string to JSON (fast path)\n"},
701 "escape a UTF-8 byte string to JSON (fast path)\n"},
702 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
702 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
703 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
703 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
704 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
704 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
705 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
705 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
706 "parse v1 obsolete markers\n"},
706 "parse v1 obsolete markers\n"},
707 {NULL, NULL}};
707 {NULL, NULL}};
708
708
709 void dirs_module_init(PyObject *mod);
709 void dirs_module_init(PyObject *mod);
710 void manifest_module_init(PyObject *mod);
710 void manifest_module_init(PyObject *mod);
711 void revlog_module_init(PyObject *mod);
711 void revlog_module_init(PyObject *mod);
712
712
713 static const int version = 3;
713 static const int version = 4;
714
714
715 static void module_init(PyObject *mod)
715 static void module_init(PyObject *mod)
716 {
716 {
717 PyModule_AddIntConstant(mod, "version", version);
717 PyModule_AddIntConstant(mod, "version", version);
718
718
719 /* This module constant has two purposes. First, it lets us unit test
719 /* This module constant has two purposes. First, it lets us unit test
720 * the ImportError raised without hard-coding any error text. This
720 * the ImportError raised without hard-coding any error text. This
721 * means we can change the text in the future without breaking tests,
721 * means we can change the text in the future without breaking tests,
722 * even across changesets without a recompile. Second, its presence
722 * even across changesets without a recompile. Second, its presence
723 * can be used to determine whether the version-checking logic is
723 * can be used to determine whether the version-checking logic is
724 * present, which also helps in testing across changesets without a
724 * present, which also helps in testing across changesets without a
725 * recompile. Note that this means the pure-Python version of parsers
725 * recompile. Note that this means the pure-Python version of parsers
726 * should not have this module constant. */
726 * should not have this module constant. */
727 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
727 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
728
728
729 dirs_module_init(mod);
729 dirs_module_init(mod);
730 manifest_module_init(mod);
730 manifest_module_init(mod);
731 revlog_module_init(mod);
731 revlog_module_init(mod);
732
732
733 if (PyType_Ready(&dirstateTupleType) < 0)
733 if (PyType_Ready(&dirstateTupleType) < 0)
734 return;
734 return;
735 Py_INCREF(&dirstateTupleType);
735 Py_INCREF(&dirstateTupleType);
736 PyModule_AddObject(mod, "dirstatetuple",
736 PyModule_AddObject(mod, "dirstatetuple",
737 (PyObject *)&dirstateTupleType);
737 (PyObject *)&dirstateTupleType);
738 }
738 }
739
739
740 static int check_python_version(void)
740 static int check_python_version(void)
741 {
741 {
742 PyObject *sys = PyImport_ImportModule("sys"), *ver;
742 PyObject *sys = PyImport_ImportModule("sys"), *ver;
743 long hexversion;
743 long hexversion;
744 if (!sys)
744 if (!sys)
745 return -1;
745 return -1;
746 ver = PyObject_GetAttrString(sys, "hexversion");
746 ver = PyObject_GetAttrString(sys, "hexversion");
747 Py_DECREF(sys);
747 Py_DECREF(sys);
748 if (!ver)
748 if (!ver)
749 return -1;
749 return -1;
750 hexversion = PyInt_AsLong(ver);
750 hexversion = PyInt_AsLong(ver);
751 Py_DECREF(ver);
751 Py_DECREF(ver);
752 /* sys.hexversion is a 32-bit number by default, so the -1 case
752 /* sys.hexversion is a 32-bit number by default, so the -1 case
753 * should only occur in unusual circumstances (e.g. if sys.hexversion
753 * should only occur in unusual circumstances (e.g. if sys.hexversion
754 * is manually set to an invalid value). */
754 * is manually set to an invalid value). */
755 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
755 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
756 PyErr_Format(PyExc_ImportError,
756 PyErr_Format(PyExc_ImportError,
757 "%s: The Mercurial extension "
757 "%s: The Mercurial extension "
758 "modules were compiled with Python " PY_VERSION
758 "modules were compiled with Python " PY_VERSION
759 ", but "
759 ", but "
760 "Mercurial is currently using Python with "
760 "Mercurial is currently using Python with "
761 "sys.hexversion=%ld: "
761 "sys.hexversion=%ld: "
762 "Python %s\n at: %s",
762 "Python %s\n at: %s",
763 versionerrortext, hexversion, Py_GetVersion(),
763 versionerrortext, hexversion, Py_GetVersion(),
764 Py_GetProgramFullPath());
764 Py_GetProgramFullPath());
765 return -1;
765 return -1;
766 }
766 }
767 return 0;
767 return 0;
768 }
768 }
769
769
770 #ifdef IS_PY3K
770 #ifdef IS_PY3K
771 static struct PyModuleDef parsers_module = {PyModuleDef_HEAD_INIT, "parsers",
771 static struct PyModuleDef parsers_module = {PyModuleDef_HEAD_INIT, "parsers",
772 parsers_doc, -1, methods};
772 parsers_doc, -1, methods};
773
773
774 PyMODINIT_FUNC PyInit_parsers(void)
774 PyMODINIT_FUNC PyInit_parsers(void)
775 {
775 {
776 PyObject *mod;
776 PyObject *mod;
777
777
778 if (check_python_version() == -1)
778 if (check_python_version() == -1)
779 return NULL;
779 return NULL;
780 mod = PyModule_Create(&parsers_module);
780 mod = PyModule_Create(&parsers_module);
781 module_init(mod);
781 module_init(mod);
782 return mod;
782 return mod;
783 }
783 }
784 #else
784 #else
785 PyMODINIT_FUNC initparsers(void)
785 PyMODINIT_FUNC initparsers(void)
786 {
786 {
787 PyObject *mod;
787 PyObject *mod;
788
788
789 if (check_python_version() == -1)
789 if (check_python_version() == -1)
790 return;
790 return;
791 mod = Py_InitModule3("parsers", methods, parsers_doc);
791 mod = Py_InitModule3("parsers", methods, parsers_doc);
792 module_init(mod);
792 module_init(mod);
793 }
793 }
794 #endif
794 #endif
@@ -1,2090 +1,2084
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 <assert.h>
11 #include <assert.h>
12 #include <ctype.h>
12 #include <ctype.h>
13 #include <stddef.h>
13 #include <stddef.h>
14 #include <string.h>
14 #include <string.h>
15
15
16 #include "bitmanipulation.h"
16 #include "bitmanipulation.h"
17 #include "charencode.h"
17 #include "charencode.h"
18 #include "util.h"
18 #include "util.h"
19
19
20 #ifdef IS_PY3K
20 #ifdef IS_PY3K
21 /* The mapping of Python types is meant to be temporary to get Python
21 /* The mapping of Python types is meant to be temporary to get Python
22 * 3 to compile. We should remove this once Python 3 support is fully
22 * 3 to compile. We should remove this once Python 3 support is fully
23 * supported and proper types are used in the extensions themselves. */
23 * supported and proper types are used in the extensions themselves. */
24 #define PyInt_Check PyLong_Check
24 #define PyInt_Check PyLong_Check
25 #define PyInt_FromLong PyLong_FromLong
25 #define PyInt_FromLong PyLong_FromLong
26 #define PyInt_FromSsize_t PyLong_FromSsize_t
26 #define PyInt_FromSsize_t PyLong_FromSsize_t
27 #define PyInt_AS_LONG PyLong_AS_LONG
27 #define PyInt_AS_LONG PyLong_AS_LONG
28 #define PyInt_AsLong PyLong_AsLong
28 #define PyInt_AsLong PyLong_AsLong
29 #endif
29 #endif
30
30
31 /*
31 /*
32 * A base-16 trie for fast node->rev mapping.
32 * A base-16 trie for fast node->rev mapping.
33 *
33 *
34 * Positive value is index of the next node in the trie
34 * Positive value is index of the next node in the trie
35 * Negative value is a leaf: -(rev + 1)
35 * Negative value is a leaf: -(rev + 1)
36 * Zero is empty
36 * Zero is empty
37 */
37 */
38 typedef struct {
38 typedef struct {
39 int children[16];
39 int children[16];
40 } nodetree;
40 } nodetree;
41
41
42 /*
42 /*
43 * This class has two behaviors.
43 * This class has two behaviors.
44 *
44 *
45 * When used in a list-like way (with integer keys), we decode an
45 * When used in a list-like way (with integer keys), we decode an
46 * entry in a RevlogNG index file on demand. Our last entry is a
46 * entry in a RevlogNG index file on demand. Our last entry is a
47 * sentinel, always a nullid. We have limited support for
47 * sentinel, always a nullid. We have limited support for
48 * integer-keyed insert and delete, only at elements right before the
48 * integer-keyed insert and delete, only at elements right before the
49 * sentinel.
49 * sentinel.
50 *
50 *
51 * With string keys, we lazily perform a reverse mapping from node to
51 * With string keys, we lazily perform a reverse mapping from node to
52 * rev, using a base-16 trie.
52 * rev, using a base-16 trie.
53 */
53 */
54 typedef struct {
54 typedef struct {
55 PyObject_HEAD
55 PyObject_HEAD
56 /* Type-specific fields go here. */
56 /* Type-specific fields go here. */
57 PyObject *data; /* raw bytes of index */
57 PyObject *data; /* raw bytes of index */
58 Py_buffer buf; /* buffer of data */
58 Py_buffer buf; /* buffer of data */
59 PyObject **cache; /* cached tuples */
59 PyObject **cache; /* cached tuples */
60 const char **offsets; /* populated on demand */
60 const char **offsets; /* populated on demand */
61 Py_ssize_t raw_length; /* original number of elements */
61 Py_ssize_t raw_length; /* original number of elements */
62 Py_ssize_t length; /* current number of elements */
62 Py_ssize_t length; /* current number of elements */
63 PyObject *added; /* populated on demand */
63 PyObject *added; /* populated on demand */
64 PyObject *headrevs; /* cache, invalidated on changes */
64 PyObject *headrevs; /* cache, invalidated on changes */
65 PyObject *filteredrevs;/* filtered revs set */
65 PyObject *filteredrevs;/* filtered revs set */
66 nodetree *nt; /* base-16 trie */
66 nodetree *nt; /* base-16 trie */
67 unsigned ntlength; /* # nodes in use */
67 unsigned ntlength; /* # nodes in use */
68 unsigned ntcapacity; /* # nodes allocated */
68 unsigned ntcapacity; /* # nodes allocated */
69 int ntdepth; /* maximum depth of tree */
69 int ntdepth; /* maximum depth of tree */
70 int ntsplits; /* # splits performed */
70 int ntsplits; /* # splits performed */
71 int ntrev; /* last rev scanned */
71 int ntrev; /* last rev scanned */
72 int ntlookups; /* # lookups */
72 int ntlookups; /* # lookups */
73 int ntmisses; /* # lookups that miss the cache */
73 int ntmisses; /* # lookups that miss the cache */
74 int inlined;
74 int inlined;
75 } indexObject;
75 } indexObject;
76
76
77 static Py_ssize_t index_length(const indexObject *self)
77 static Py_ssize_t index_length(const indexObject *self)
78 {
78 {
79 if (self->added == NULL)
79 if (self->added == NULL)
80 return self->length;
80 return self->length;
81 return self->length + PyList_GET_SIZE(self->added);
81 return self->length + PyList_GET_SIZE(self->added);
82 }
82 }
83
83
84 static PyObject *nullentry;
84 static PyObject *nullentry;
85 static const char nullid[20];
85 static const char nullid[20];
86
86
87 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
87 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
88
88
89 #if LONG_MAX == 0x7fffffffL
89 #if LONG_MAX == 0x7fffffffL
90 static char *tuple_format = "Kiiiiiis#";
90 static char *tuple_format = "Kiiiiiis#";
91 #else
91 #else
92 static char *tuple_format = "kiiiiiis#";
92 static char *tuple_format = "kiiiiiis#";
93 #endif
93 #endif
94
94
95 /* A RevlogNG v1 index entry is 64 bytes long. */
95 /* A RevlogNG v1 index entry is 64 bytes long. */
96 static const long v1_hdrsize = 64;
96 static const long v1_hdrsize = 64;
97
97
98 /*
98 /*
99 * Return a pointer to the beginning of a RevlogNG record.
99 * Return a pointer to the beginning of a RevlogNG record.
100 */
100 */
101 static const char *index_deref(indexObject *self, Py_ssize_t pos)
101 static const char *index_deref(indexObject *self, Py_ssize_t pos)
102 {
102 {
103 if (self->inlined && pos > 0) {
103 if (self->inlined && pos > 0) {
104 if (self->offsets == NULL) {
104 if (self->offsets == NULL) {
105 self->offsets = PyMem_Malloc(self->raw_length *
105 self->offsets = PyMem_Malloc(self->raw_length *
106 sizeof(*self->offsets));
106 sizeof(*self->offsets));
107 if (self->offsets == NULL)
107 if (self->offsets == NULL)
108 return (const char *)PyErr_NoMemory();
108 return (const char *)PyErr_NoMemory();
109 inline_scan(self, self->offsets);
109 inline_scan(self, self->offsets);
110 }
110 }
111 return self->offsets[pos];
111 return self->offsets[pos];
112 }
112 }
113
113
114 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
114 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
115 }
115 }
116
116
117 static inline int index_get_parents(indexObject *self, Py_ssize_t rev,
117 static inline int index_get_parents(indexObject *self, Py_ssize_t rev,
118 int *ps, int maxrev)
118 int *ps, int maxrev)
119 {
119 {
120 if (rev >= self->length - 1) {
120 if (rev >= self->length - 1) {
121 PyObject *tuple = PyList_GET_ITEM(self->added,
121 PyObject *tuple = PyList_GET_ITEM(self->added,
122 rev - self->length + 1);
122 rev - self->length + 1);
123 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
123 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
124 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
124 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
125 } else {
125 } else {
126 const char *data = index_deref(self, rev);
126 const char *data = index_deref(self, rev);
127 ps[0] = getbe32(data + 24);
127 ps[0] = getbe32(data + 24);
128 ps[1] = getbe32(data + 28);
128 ps[1] = getbe32(data + 28);
129 }
129 }
130 /* If index file is corrupted, ps[] may point to invalid revisions. So
130 /* If index file is corrupted, ps[] may point to invalid revisions. So
131 * there is a risk of buffer overflow to trust them unconditionally. */
131 * there is a risk of buffer overflow to trust them unconditionally. */
132 if (ps[0] > maxrev || ps[1] > maxrev) {
132 if (ps[0] > maxrev || ps[1] > maxrev) {
133 PyErr_SetString(PyExc_ValueError, "parent out of range");
133 PyErr_SetString(PyExc_ValueError, "parent out of range");
134 return -1;
134 return -1;
135 }
135 }
136 return 0;
136 return 0;
137 }
137 }
138
138
139
139
140 /*
140 /*
141 * RevlogNG format (all in big endian, data may be inlined):
141 * RevlogNG format (all in big endian, data may be inlined):
142 * 6 bytes: offset
142 * 6 bytes: offset
143 * 2 bytes: flags
143 * 2 bytes: flags
144 * 4 bytes: compressed length
144 * 4 bytes: compressed length
145 * 4 bytes: uncompressed length
145 * 4 bytes: uncompressed length
146 * 4 bytes: base revision
146 * 4 bytes: base revision
147 * 4 bytes: link revision
147 * 4 bytes: link revision
148 * 4 bytes: parent 1 revision
148 * 4 bytes: parent 1 revision
149 * 4 bytes: parent 2 revision
149 * 4 bytes: parent 2 revision
150 * 32 bytes: nodeid (only 20 bytes used)
150 * 32 bytes: nodeid (only 20 bytes used)
151 */
151 */
152 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
152 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
153 {
153 {
154 uint64_t offset_flags;
154 uint64_t offset_flags;
155 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
155 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
156 const char *c_node_id;
156 const char *c_node_id;
157 const char *data;
157 const char *data;
158 Py_ssize_t length = index_length(self);
158 Py_ssize_t length = index_length(self);
159 PyObject *entry;
159 PyObject *entry;
160
160
161 if (pos < 0)
161 if (pos < 0)
162 pos += length;
162 pos += length;
163
163
164 if (pos < 0 || pos >= length) {
164 if (pos < 0 || pos >= length) {
165 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
165 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
166 return NULL;
166 return NULL;
167 }
167 }
168
168
169 if (pos == length - 1) {
169 if (pos == length - 1) {
170 Py_INCREF(nullentry);
170 Py_INCREF(nullentry);
171 return nullentry;
171 return nullentry;
172 }
172 }
173
173
174 if (pos >= self->length - 1) {
174 if (pos >= self->length - 1) {
175 PyObject *obj;
175 PyObject *obj;
176 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
176 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
177 Py_INCREF(obj);
177 Py_INCREF(obj);
178 return obj;
178 return obj;
179 }
179 }
180
180
181 if (self->cache) {
181 if (self->cache) {
182 if (self->cache[pos]) {
182 if (self->cache[pos]) {
183 Py_INCREF(self->cache[pos]);
183 Py_INCREF(self->cache[pos]);
184 return self->cache[pos];
184 return self->cache[pos];
185 }
185 }
186 } else {
186 } else {
187 self->cache = calloc(self->raw_length, sizeof(PyObject *));
187 self->cache = calloc(self->raw_length, sizeof(PyObject *));
188 if (self->cache == NULL)
188 if (self->cache == NULL)
189 return PyErr_NoMemory();
189 return PyErr_NoMemory();
190 }
190 }
191
191
192 data = index_deref(self, pos);
192 data = index_deref(self, pos);
193 if (data == NULL)
193 if (data == NULL)
194 return NULL;
194 return NULL;
195
195
196 offset_flags = getbe32(data + 4);
196 offset_flags = getbe32(data + 4);
197 if (pos == 0) /* mask out version number for the first entry */
197 if (pos == 0) /* mask out version number for the first entry */
198 offset_flags &= 0xFFFF;
198 offset_flags &= 0xFFFF;
199 else {
199 else {
200 uint32_t offset_high = getbe32(data);
200 uint32_t offset_high = getbe32(data);
201 offset_flags |= ((uint64_t)offset_high) << 32;
201 offset_flags |= ((uint64_t)offset_high) << 32;
202 }
202 }
203
203
204 comp_len = getbe32(data + 8);
204 comp_len = getbe32(data + 8);
205 uncomp_len = getbe32(data + 12);
205 uncomp_len = getbe32(data + 12);
206 base_rev = getbe32(data + 16);
206 base_rev = getbe32(data + 16);
207 link_rev = getbe32(data + 20);
207 link_rev = getbe32(data + 20);
208 parent_1 = getbe32(data + 24);
208 parent_1 = getbe32(data + 24);
209 parent_2 = getbe32(data + 28);
209 parent_2 = getbe32(data + 28);
210 c_node_id = data + 32;
210 c_node_id = data + 32;
211
211
212 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
212 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
213 uncomp_len, base_rev, link_rev,
213 uncomp_len, base_rev, link_rev,
214 parent_1, parent_2, c_node_id, 20);
214 parent_1, parent_2, c_node_id, 20);
215
215
216 if (entry) {
216 if (entry) {
217 PyObject_GC_UnTrack(entry);
217 PyObject_GC_UnTrack(entry);
218 Py_INCREF(entry);
218 Py_INCREF(entry);
219 }
219 }
220
220
221 self->cache[pos] = entry;
221 self->cache[pos] = entry;
222
222
223 return entry;
223 return entry;
224 }
224 }
225
225
226 /*
226 /*
227 * Return the 20-byte SHA of the node corresponding to the given rev.
227 * Return the 20-byte SHA of the node corresponding to the given rev.
228 */
228 */
229 static const char *index_node(indexObject *self, Py_ssize_t pos)
229 static const char *index_node(indexObject *self, Py_ssize_t pos)
230 {
230 {
231 Py_ssize_t length = index_length(self);
231 Py_ssize_t length = index_length(self);
232 const char *data;
232 const char *data;
233
233
234 if (pos == length - 1 || pos == INT_MAX)
234 if (pos == length - 1 || pos == INT_MAX)
235 return nullid;
235 return nullid;
236
236
237 if (pos >= length)
237 if (pos >= length)
238 return NULL;
238 return NULL;
239
239
240 if (pos >= self->length - 1) {
240 if (pos >= self->length - 1) {
241 PyObject *tuple, *str;
241 PyObject *tuple, *str;
242 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
242 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
243 str = PyTuple_GetItem(tuple, 7);
243 str = PyTuple_GetItem(tuple, 7);
244 return str ? PyBytes_AS_STRING(str) : NULL;
244 return str ? PyBytes_AS_STRING(str) : NULL;
245 }
245 }
246
246
247 data = index_deref(self, pos);
247 data = index_deref(self, pos);
248 return data ? data + 32 : NULL;
248 return data ? data + 32 : NULL;
249 }
249 }
250
250
251 static int nt_insert(indexObject *self, const char *node, int rev);
251 static int nt_insert(indexObject *self, const char *node, int rev);
252
252
253 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
253 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
254 {
254 {
255 if (PyBytes_AsStringAndSize(obj, node, nodelen) == -1)
255 if (PyBytes_AsStringAndSize(obj, node, nodelen) == -1)
256 return -1;
256 return -1;
257 if (*nodelen == 20)
257 if (*nodelen == 20)
258 return 0;
258 return 0;
259 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
259 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
260 return -1;
260 return -1;
261 }
261 }
262
262
263 static PyObject *index_insert(indexObject *self, PyObject *args)
263 static PyObject *index_insert(indexObject *self, PyObject *args)
264 {
264 {
265 PyObject *obj;
265 PyObject *obj;
266 char *node;
266 char *node;
267 int index;
267 int index;
268 Py_ssize_t len, nodelen;
268 Py_ssize_t len, nodelen;
269
269
270 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
270 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
271 return NULL;
271 return NULL;
272
272
273 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
273 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
274 PyErr_SetString(PyExc_TypeError, "8-tuple required");
274 PyErr_SetString(PyExc_TypeError, "8-tuple required");
275 return NULL;
275 return NULL;
276 }
276 }
277
277
278 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
278 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
279 return NULL;
279 return NULL;
280
280
281 len = index_length(self);
281 len = index_length(self);
282
282
283 if (index < 0)
283 if (index < 0)
284 index += len;
284 index += len;
285
285
286 if (index != len - 1) {
286 if (index != len - 1) {
287 PyErr_SetString(PyExc_IndexError,
287 PyErr_SetString(PyExc_IndexError,
288 "insert only supported at index -1");
288 "insert only supported at index -1");
289 return NULL;
289 return NULL;
290 }
290 }
291
291
292 if (self->added == NULL) {
292 if (self->added == NULL) {
293 self->added = PyList_New(0);
293 self->added = PyList_New(0);
294 if (self->added == NULL)
294 if (self->added == NULL)
295 return NULL;
295 return NULL;
296 }
296 }
297
297
298 if (PyList_Append(self->added, obj) == -1)
298 if (PyList_Append(self->added, obj) == -1)
299 return NULL;
299 return NULL;
300
300
301 if (self->nt)
301 if (self->nt)
302 nt_insert(self, node, index);
302 nt_insert(self, node, index);
303
303
304 Py_CLEAR(self->headrevs);
304 Py_CLEAR(self->headrevs);
305 Py_RETURN_NONE;
305 Py_RETURN_NONE;
306 }
306 }
307
307
308 static void _index_clearcaches(indexObject *self)
308 static void _index_clearcaches(indexObject *self)
309 {
309 {
310 if (self->cache) {
310 if (self->cache) {
311 Py_ssize_t i;
311 Py_ssize_t i;
312
312
313 for (i = 0; i < self->raw_length; i++)
313 for (i = 0; i < self->raw_length; i++)
314 Py_CLEAR(self->cache[i]);
314 Py_CLEAR(self->cache[i]);
315 free(self->cache);
315 free(self->cache);
316 self->cache = NULL;
316 self->cache = NULL;
317 }
317 }
318 if (self->offsets) {
318 if (self->offsets) {
319 PyMem_Free(self->offsets);
319 PyMem_Free(self->offsets);
320 self->offsets = NULL;
320 self->offsets = NULL;
321 }
321 }
322 if (self->nt) {
322 if (self->nt) {
323 free(self->nt);
323 free(self->nt);
324 self->nt = NULL;
324 self->nt = NULL;
325 }
325 }
326 Py_CLEAR(self->headrevs);
326 Py_CLEAR(self->headrevs);
327 }
327 }
328
328
329 static PyObject *index_clearcaches(indexObject *self)
329 static PyObject *index_clearcaches(indexObject *self)
330 {
330 {
331 _index_clearcaches(self);
331 _index_clearcaches(self);
332 self->ntlength = self->ntcapacity = 0;
332 self->ntlength = self->ntcapacity = 0;
333 self->ntdepth = self->ntsplits = 0;
333 self->ntdepth = self->ntsplits = 0;
334 self->ntrev = -1;
334 self->ntrev = -1;
335 self->ntlookups = self->ntmisses = 0;
335 self->ntlookups = self->ntmisses = 0;
336 Py_RETURN_NONE;
336 Py_RETURN_NONE;
337 }
337 }
338
338
339 static PyObject *index_stats(indexObject *self)
339 static PyObject *index_stats(indexObject *self)
340 {
340 {
341 PyObject *obj = PyDict_New();
341 PyObject *obj = PyDict_New();
342 PyObject *t = NULL;
342 PyObject *t = NULL;
343
343
344 if (obj == NULL)
344 if (obj == NULL)
345 return NULL;
345 return NULL;
346
346
347 #define istat(__n, __d) \
347 #define istat(__n, __d) \
348 do { \
348 do { \
349 t = PyInt_FromSsize_t(self->__n); \
349 t = PyInt_FromSsize_t(self->__n); \
350 if (!t) \
350 if (!t) \
351 goto bail; \
351 goto bail; \
352 if (PyDict_SetItemString(obj, __d, t) == -1) \
352 if (PyDict_SetItemString(obj, __d, t) == -1) \
353 goto bail; \
353 goto bail; \
354 Py_DECREF(t); \
354 Py_DECREF(t); \
355 } while (0)
355 } while (0)
356
356
357 if (self->added) {
357 if (self->added) {
358 Py_ssize_t len = PyList_GET_SIZE(self->added);
358 Py_ssize_t len = PyList_GET_SIZE(self->added);
359 t = PyInt_FromSsize_t(len);
359 t = PyInt_FromSsize_t(len);
360 if (!t)
360 if (!t)
361 goto bail;
361 goto bail;
362 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
362 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
363 goto bail;
363 goto bail;
364 Py_DECREF(t);
364 Py_DECREF(t);
365 }
365 }
366
366
367 if (self->raw_length != self->length - 1)
367 if (self->raw_length != self->length - 1)
368 istat(raw_length, "revs on disk");
368 istat(raw_length, "revs on disk");
369 istat(length, "revs in memory");
369 istat(length, "revs in memory");
370 istat(ntcapacity, "node trie capacity");
370 istat(ntcapacity, "node trie capacity");
371 istat(ntdepth, "node trie depth");
371 istat(ntdepth, "node trie depth");
372 istat(ntlength, "node trie count");
372 istat(ntlength, "node trie count");
373 istat(ntlookups, "node trie lookups");
373 istat(ntlookups, "node trie lookups");
374 istat(ntmisses, "node trie misses");
374 istat(ntmisses, "node trie misses");
375 istat(ntrev, "node trie last rev scanned");
375 istat(ntrev, "node trie last rev scanned");
376 istat(ntsplits, "node trie splits");
376 istat(ntsplits, "node trie splits");
377
377
378 #undef istat
378 #undef istat
379
379
380 return obj;
380 return obj;
381
381
382 bail:
382 bail:
383 Py_XDECREF(obj);
383 Py_XDECREF(obj);
384 Py_XDECREF(t);
384 Py_XDECREF(t);
385 return NULL;
385 return NULL;
386 }
386 }
387
387
388 /*
388 /*
389 * When we cache a list, we want to be sure the caller can't mutate
389 * When we cache a list, we want to be sure the caller can't mutate
390 * the cached copy.
390 * the cached copy.
391 */
391 */
392 static PyObject *list_copy(PyObject *list)
392 static PyObject *list_copy(PyObject *list)
393 {
393 {
394 Py_ssize_t len = PyList_GET_SIZE(list);
394 Py_ssize_t len = PyList_GET_SIZE(list);
395 PyObject *newlist = PyList_New(len);
395 PyObject *newlist = PyList_New(len);
396 Py_ssize_t i;
396 Py_ssize_t i;
397
397
398 if (newlist == NULL)
398 if (newlist == NULL)
399 return NULL;
399 return NULL;
400
400
401 for (i = 0; i < len; i++) {
401 for (i = 0; i < len; i++) {
402 PyObject *obj = PyList_GET_ITEM(list, i);
402 PyObject *obj = PyList_GET_ITEM(list, i);
403 Py_INCREF(obj);
403 Py_INCREF(obj);
404 PyList_SET_ITEM(newlist, i, obj);
404 PyList_SET_ITEM(newlist, i, obj);
405 }
405 }
406
406
407 return newlist;
407 return newlist;
408 }
408 }
409
409
410 static int check_filter(PyObject *filter, Py_ssize_t arg)
410 static int check_filter(PyObject *filter, Py_ssize_t arg)
411 {
411 {
412 if (filter) {
412 if (filter) {
413 PyObject *arglist, *result;
413 PyObject *arglist, *result;
414 int isfiltered;
414 int isfiltered;
415
415
416 arglist = Py_BuildValue("(n)", arg);
416 arglist = Py_BuildValue("(n)", arg);
417 if (!arglist) {
417 if (!arglist) {
418 return -1;
418 return -1;
419 }
419 }
420
420
421 result = PyEval_CallObject(filter, arglist);
421 result = PyEval_CallObject(filter, arglist);
422 Py_DECREF(arglist);
422 Py_DECREF(arglist);
423 if (!result) {
423 if (!result) {
424 return -1;
424 return -1;
425 }
425 }
426
426
427 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
427 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
428 * same as this function, so we can just return it directly.*/
428 * same as this function, so we can just return it directly.*/
429 isfiltered = PyObject_IsTrue(result);
429 isfiltered = PyObject_IsTrue(result);
430 Py_DECREF(result);
430 Py_DECREF(result);
431 return isfiltered;
431 return isfiltered;
432 } else {
432 } else {
433 return 0;
433 return 0;
434 }
434 }
435 }
435 }
436
436
437 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
437 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
438 Py_ssize_t marker, char *phases)
438 Py_ssize_t marker, char *phases)
439 {
439 {
440 PyObject *iter = NULL;
440 PyObject *iter = NULL;
441 PyObject *iter_item = NULL;
441 PyObject *iter_item = NULL;
442 Py_ssize_t min_idx = index_length(self) + 1;
442 Py_ssize_t min_idx = index_length(self) + 1;
443 long iter_item_long;
443 long iter_item_long;
444
444
445 if (PyList_GET_SIZE(list) != 0) {
445 if (PyList_GET_SIZE(list) != 0) {
446 iter = PyObject_GetIter(list);
446 iter = PyObject_GetIter(list);
447 if (iter == NULL)
447 if (iter == NULL)
448 return -2;
448 return -2;
449 while ((iter_item = PyIter_Next(iter))) {
449 while ((iter_item = PyIter_Next(iter))) {
450 iter_item_long = PyInt_AS_LONG(iter_item);
450 iter_item_long = PyInt_AS_LONG(iter_item);
451 Py_DECREF(iter_item);
451 Py_DECREF(iter_item);
452 if (iter_item_long < min_idx)
452 if (iter_item_long < min_idx)
453 min_idx = iter_item_long;
453 min_idx = iter_item_long;
454 phases[iter_item_long] = marker;
454 phases[iter_item_long] = marker;
455 }
455 }
456 Py_DECREF(iter);
456 Py_DECREF(iter);
457 }
457 }
458
458
459 return min_idx;
459 return min_idx;
460 }
460 }
461
461
462 static inline void set_phase_from_parents(char *phases, int parent_1,
462 static inline void set_phase_from_parents(char *phases, int parent_1,
463 int parent_2, Py_ssize_t i)
463 int parent_2, Py_ssize_t i)
464 {
464 {
465 if (parent_1 >= 0 && phases[parent_1] > phases[i])
465 if (parent_1 >= 0 && phases[parent_1] > phases[i])
466 phases[i] = phases[parent_1];
466 phases[i] = phases[parent_1];
467 if (parent_2 >= 0 && phases[parent_2] > phases[i])
467 if (parent_2 >= 0 && phases[parent_2] > phases[i])
468 phases[i] = phases[parent_2];
468 phases[i] = phases[parent_2];
469 }
469 }
470
470
471 static PyObject *reachableroots2(indexObject *self, PyObject *args)
471 static PyObject *reachableroots2(indexObject *self, PyObject *args)
472 {
472 {
473
473
474 /* Input */
474 /* Input */
475 long minroot;
475 long minroot;
476 PyObject *includepatharg = NULL;
476 PyObject *includepatharg = NULL;
477 int includepath = 0;
477 int includepath = 0;
478 /* heads and roots are lists */
478 /* heads and roots are lists */
479 PyObject *heads = NULL;
479 PyObject *heads = NULL;
480 PyObject *roots = NULL;
480 PyObject *roots = NULL;
481 PyObject *reachable = NULL;
481 PyObject *reachable = NULL;
482
482
483 PyObject *val;
483 PyObject *val;
484 Py_ssize_t len = index_length(self) - 1;
484 Py_ssize_t len = index_length(self) - 1;
485 long revnum;
485 long revnum;
486 Py_ssize_t k;
486 Py_ssize_t k;
487 Py_ssize_t i;
487 Py_ssize_t i;
488 Py_ssize_t l;
488 Py_ssize_t l;
489 int r;
489 int r;
490 int parents[2];
490 int parents[2];
491
491
492 /* Internal data structure:
492 /* Internal data structure:
493 * tovisit: array of length len+1 (all revs + nullrev), filled upto lentovisit
493 * tovisit: array of length len+1 (all revs + nullrev), filled upto lentovisit
494 * revstates: array of length len+1 (all revs + nullrev) */
494 * revstates: array of length len+1 (all revs + nullrev) */
495 int *tovisit = NULL;
495 int *tovisit = NULL;
496 long lentovisit = 0;
496 long lentovisit = 0;
497 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
497 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
498 char *revstates = NULL;
498 char *revstates = NULL;
499
499
500 /* Get arguments */
500 /* Get arguments */
501 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
501 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
502 &PyList_Type, &roots,
502 &PyList_Type, &roots,
503 &PyBool_Type, &includepatharg))
503 &PyBool_Type, &includepatharg))
504 goto bail;
504 goto bail;
505
505
506 if (includepatharg == Py_True)
506 if (includepatharg == Py_True)
507 includepath = 1;
507 includepath = 1;
508
508
509 /* Initialize return set */
509 /* Initialize return set */
510 reachable = PyList_New(0);
510 reachable = PyList_New(0);
511 if (reachable == NULL)
511 if (reachable == NULL)
512 goto bail;
512 goto bail;
513
513
514 /* Initialize internal datastructures */
514 /* Initialize internal datastructures */
515 tovisit = (int *)malloc((len + 1) * sizeof(int));
515 tovisit = (int *)malloc((len + 1) * sizeof(int));
516 if (tovisit == NULL) {
516 if (tovisit == NULL) {
517 PyErr_NoMemory();
517 PyErr_NoMemory();
518 goto bail;
518 goto bail;
519 }
519 }
520
520
521 revstates = (char *)calloc(len + 1, 1);
521 revstates = (char *)calloc(len + 1, 1);
522 if (revstates == NULL) {
522 if (revstates == NULL) {
523 PyErr_NoMemory();
523 PyErr_NoMemory();
524 goto bail;
524 goto bail;
525 }
525 }
526
526
527 l = PyList_GET_SIZE(roots);
527 l = PyList_GET_SIZE(roots);
528 for (i = 0; i < l; i++) {
528 for (i = 0; i < l; i++) {
529 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
529 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
530 if (revnum == -1 && PyErr_Occurred())
530 if (revnum == -1 && PyErr_Occurred())
531 goto bail;
531 goto bail;
532 /* If root is out of range, e.g. wdir(), it must be unreachable
532 /* If root is out of range, e.g. wdir(), it must be unreachable
533 * from heads. So we can just ignore it. */
533 * from heads. So we can just ignore it. */
534 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
534 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
535 continue;
535 continue;
536 revstates[revnum + 1] |= RS_ROOT;
536 revstates[revnum + 1] |= RS_ROOT;
537 }
537 }
538
538
539 /* Populate tovisit with all the heads */
539 /* Populate tovisit with all the heads */
540 l = PyList_GET_SIZE(heads);
540 l = PyList_GET_SIZE(heads);
541 for (i = 0; i < l; i++) {
541 for (i = 0; i < l; i++) {
542 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
542 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
543 if (revnum == -1 && PyErr_Occurred())
543 if (revnum == -1 && PyErr_Occurred())
544 goto bail;
544 goto bail;
545 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
545 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
546 PyErr_SetString(PyExc_IndexError, "head out of range");
546 PyErr_SetString(PyExc_IndexError, "head out of range");
547 goto bail;
547 goto bail;
548 }
548 }
549 if (!(revstates[revnum + 1] & RS_SEEN)) {
549 if (!(revstates[revnum + 1] & RS_SEEN)) {
550 tovisit[lentovisit++] = (int)revnum;
550 tovisit[lentovisit++] = (int)revnum;
551 revstates[revnum + 1] |= RS_SEEN;
551 revstates[revnum + 1] |= RS_SEEN;
552 }
552 }
553 }
553 }
554
554
555 /* Visit the tovisit list and find the reachable roots */
555 /* Visit the tovisit list and find the reachable roots */
556 k = 0;
556 k = 0;
557 while (k < lentovisit) {
557 while (k < lentovisit) {
558 /* Add the node to reachable if it is a root*/
558 /* Add the node to reachable if it is a root*/
559 revnum = tovisit[k++];
559 revnum = tovisit[k++];
560 if (revstates[revnum + 1] & RS_ROOT) {
560 if (revstates[revnum + 1] & RS_ROOT) {
561 revstates[revnum + 1] |= RS_REACHABLE;
561 revstates[revnum + 1] |= RS_REACHABLE;
562 val = PyInt_FromLong(revnum);
562 val = PyInt_FromLong(revnum);
563 if (val == NULL)
563 if (val == NULL)
564 goto bail;
564 goto bail;
565 r = PyList_Append(reachable, val);
565 r = PyList_Append(reachable, val);
566 Py_DECREF(val);
566 Py_DECREF(val);
567 if (r < 0)
567 if (r < 0)
568 goto bail;
568 goto bail;
569 if (includepath == 0)
569 if (includepath == 0)
570 continue;
570 continue;
571 }
571 }
572
572
573 /* Add its parents to the list of nodes to visit */
573 /* Add its parents to the list of nodes to visit */
574 if (revnum == -1)
574 if (revnum == -1)
575 continue;
575 continue;
576 r = index_get_parents(self, revnum, parents, (int)len - 1);
576 r = index_get_parents(self, revnum, parents, (int)len - 1);
577 if (r < 0)
577 if (r < 0)
578 goto bail;
578 goto bail;
579 for (i = 0; i < 2; i++) {
579 for (i = 0; i < 2; i++) {
580 if (!(revstates[parents[i] + 1] & RS_SEEN)
580 if (!(revstates[parents[i] + 1] & RS_SEEN)
581 && parents[i] >= minroot) {
581 && parents[i] >= minroot) {
582 tovisit[lentovisit++] = parents[i];
582 tovisit[lentovisit++] = parents[i];
583 revstates[parents[i] + 1] |= RS_SEEN;
583 revstates[parents[i] + 1] |= RS_SEEN;
584 }
584 }
585 }
585 }
586 }
586 }
587
587
588 /* Find all the nodes in between the roots we found and the heads
588 /* Find all the nodes in between the roots we found and the heads
589 * and add them to the reachable set */
589 * and add them to the reachable set */
590 if (includepath == 1) {
590 if (includepath == 1) {
591 long minidx = minroot;
591 long minidx = minroot;
592 if (minidx < 0)
592 if (minidx < 0)
593 minidx = 0;
593 minidx = 0;
594 for (i = minidx; i < len; i++) {
594 for (i = minidx; i < len; i++) {
595 if (!(revstates[i + 1] & RS_SEEN))
595 if (!(revstates[i + 1] & RS_SEEN))
596 continue;
596 continue;
597 r = index_get_parents(self, i, parents, (int)len - 1);
597 r = index_get_parents(self, i, parents, (int)len - 1);
598 /* Corrupted index file, error is set from
598 /* Corrupted index file, error is set from
599 * index_get_parents */
599 * index_get_parents */
600 if (r < 0)
600 if (r < 0)
601 goto bail;
601 goto bail;
602 if (((revstates[parents[0] + 1] |
602 if (((revstates[parents[0] + 1] |
603 revstates[parents[1] + 1]) & RS_REACHABLE)
603 revstates[parents[1] + 1]) & RS_REACHABLE)
604 && !(revstates[i + 1] & RS_REACHABLE)) {
604 && !(revstates[i + 1] & RS_REACHABLE)) {
605 revstates[i + 1] |= RS_REACHABLE;
605 revstates[i + 1] |= RS_REACHABLE;
606 val = PyInt_FromLong(i);
606 val = PyInt_FromLong(i);
607 if (val == NULL)
607 if (val == NULL)
608 goto bail;
608 goto bail;
609 r = PyList_Append(reachable, val);
609 r = PyList_Append(reachable, val);
610 Py_DECREF(val);
610 Py_DECREF(val);
611 if (r < 0)
611 if (r < 0)
612 goto bail;
612 goto bail;
613 }
613 }
614 }
614 }
615 }
615 }
616
616
617 free(revstates);
617 free(revstates);
618 free(tovisit);
618 free(tovisit);
619 return reachable;
619 return reachable;
620 bail:
620 bail:
621 Py_XDECREF(reachable);
621 Py_XDECREF(reachable);
622 free(revstates);
622 free(revstates);
623 free(tovisit);
623 free(tovisit);
624 return NULL;
624 return NULL;
625 }
625 }
626
626
627 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
627 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
628 {
628 {
629 PyObject *roots = Py_None;
629 PyObject *roots = Py_None;
630 PyObject *ret = NULL;
630 PyObject *ret = NULL;
631 PyObject *phaseslist = NULL;
631 PyObject *phasessize = NULL;
632 PyObject *phaseroots = NULL;
632 PyObject *phaseroots = NULL;
633 PyObject *phaseset = NULL;
633 PyObject *phaseset = NULL;
634 PyObject *phasessetlist = NULL;
634 PyObject *phasessetlist = NULL;
635 PyObject *rev = NULL;
635 PyObject *rev = NULL;
636 Py_ssize_t len = index_length(self) - 1;
636 Py_ssize_t len = index_length(self) - 1;
637 Py_ssize_t numphase = 0;
637 Py_ssize_t numphase = 0;
638 Py_ssize_t minrevallphases = 0;
638 Py_ssize_t minrevallphases = 0;
639 Py_ssize_t minrevphase = 0;
639 Py_ssize_t minrevphase = 0;
640 Py_ssize_t i = 0;
640 Py_ssize_t i = 0;
641 char *phases = NULL;
641 char *phases = NULL;
642 long phase;
642 long phase;
643
643
644 if (!PyArg_ParseTuple(args, "O", &roots))
644 if (!PyArg_ParseTuple(args, "O", &roots))
645 goto done;
645 goto done;
646 if (roots == NULL || !PyList_Check(roots))
646 if (roots == NULL || !PyList_Check(roots))
647 goto done;
647 goto done;
648
648
649 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
649 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
650 if (phases == NULL) {
650 if (phases == NULL) {
651 PyErr_NoMemory();
651 PyErr_NoMemory();
652 goto done;
652 goto done;
653 }
653 }
654 /* Put the phase information of all the roots in phases */
654 /* Put the phase information of all the roots in phases */
655 numphase = PyList_GET_SIZE(roots)+1;
655 numphase = PyList_GET_SIZE(roots)+1;
656 minrevallphases = len + 1;
656 minrevallphases = len + 1;
657 phasessetlist = PyList_New(numphase);
657 phasessetlist = PyList_New(numphase);
658 if (phasessetlist == NULL)
658 if (phasessetlist == NULL)
659 goto done;
659 goto done;
660
660
661 PyList_SET_ITEM(phasessetlist, 0, Py_None);
661 PyList_SET_ITEM(phasessetlist, 0, Py_None);
662 Py_INCREF(Py_None);
662 Py_INCREF(Py_None);
663
663
664 for (i = 0; i < numphase-1; i++) {
664 for (i = 0; i < numphase-1; i++) {
665 phaseroots = PyList_GET_ITEM(roots, i);
665 phaseroots = PyList_GET_ITEM(roots, i);
666 phaseset = PySet_New(NULL);
666 phaseset = PySet_New(NULL);
667 if (phaseset == NULL)
667 if (phaseset == NULL)
668 goto release;
668 goto release;
669 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
669 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
670 if (!PyList_Check(phaseroots))
670 if (!PyList_Check(phaseroots))
671 goto release;
671 goto release;
672 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
672 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
673 if (minrevphase == -2) /* Error from add_roots_get_min */
673 if (minrevphase == -2) /* Error from add_roots_get_min */
674 goto release;
674 goto release;
675 minrevallphases = MIN(minrevallphases, minrevphase);
675 minrevallphases = MIN(minrevallphases, minrevphase);
676 }
676 }
677 /* Propagate the phase information from the roots to the revs */
677 /* Propagate the phase information from the roots to the revs */
678 if (minrevallphases != -1) {
678 if (minrevallphases != -1) {
679 int parents[2];
679 int parents[2];
680 for (i = minrevallphases; i < len; i++) {
680 for (i = minrevallphases; i < len; i++) {
681 if (index_get_parents(self, i, parents,
681 if (index_get_parents(self, i, parents,
682 (int)len - 1) < 0)
682 (int)len - 1) < 0)
683 goto release;
683 goto release;
684 set_phase_from_parents(phases, parents[0], parents[1], i);
684 set_phase_from_parents(phases, parents[0], parents[1], i);
685 }
685 }
686 }
686 }
687 /* Transform phase list to a python list */
687 /* Transform phase list to a python list */
688 phaseslist = PyList_New(len);
688 phasessize = PyInt_FromLong(len);
689 if (phaseslist == NULL)
689 if (phasessize == NULL)
690 goto release;
690 goto release;
691 for (i = 0; i < len; i++) {
691 for (i = 0; i < len; i++) {
692 PyObject *phaseval;
693
694 phase = phases[i];
692 phase = phases[i];
695 /* We only store the sets of phase for non public phase, the public phase
693 /* We only store the sets of phase for non public phase, the public phase
696 * is computed as a difference */
694 * is computed as a difference */
697 if (phase != 0) {
695 if (phase != 0) {
698 phaseset = PyList_GET_ITEM(phasessetlist, phase);
696 phaseset = PyList_GET_ITEM(phasessetlist, phase);
699 rev = PyInt_FromLong(i);
697 rev = PyInt_FromLong(i);
700 if (rev == NULL)
698 if (rev == NULL)
701 goto release;
699 goto release;
702 PySet_Add(phaseset, rev);
700 PySet_Add(phaseset, rev);
703 Py_XDECREF(rev);
701 Py_XDECREF(rev);
704 }
702 }
705 phaseval = PyInt_FromLong(phase);
706 if (phaseval == NULL)
707 goto release;
708 PyList_SET_ITEM(phaseslist, i, phaseval);
709 }
703 }
710 ret = PyTuple_Pack(2, phaseslist, phasessetlist);
704 ret = PyTuple_Pack(2, phasessize, phasessetlist);
711
705
712 release:
706 release:
713 Py_XDECREF(phaseslist);
707 Py_XDECREF(phasessize);
714 Py_XDECREF(phasessetlist);
708 Py_XDECREF(phasessetlist);
715 done:
709 done:
716 free(phases);
710 free(phases);
717 return ret;
711 return ret;
718 }
712 }
719
713
720 static PyObject *index_headrevs(indexObject *self, PyObject *args)
714 static PyObject *index_headrevs(indexObject *self, PyObject *args)
721 {
715 {
722 Py_ssize_t i, j, len;
716 Py_ssize_t i, j, len;
723 char *nothead = NULL;
717 char *nothead = NULL;
724 PyObject *heads = NULL;
718 PyObject *heads = NULL;
725 PyObject *filter = NULL;
719 PyObject *filter = NULL;
726 PyObject *filteredrevs = Py_None;
720 PyObject *filteredrevs = Py_None;
727
721
728 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
722 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
729 return NULL;
723 return NULL;
730 }
724 }
731
725
732 if (self->headrevs && filteredrevs == self->filteredrevs)
726 if (self->headrevs && filteredrevs == self->filteredrevs)
733 return list_copy(self->headrevs);
727 return list_copy(self->headrevs);
734
728
735 Py_DECREF(self->filteredrevs);
729 Py_DECREF(self->filteredrevs);
736 self->filteredrevs = filteredrevs;
730 self->filteredrevs = filteredrevs;
737 Py_INCREF(filteredrevs);
731 Py_INCREF(filteredrevs);
738
732
739 if (filteredrevs != Py_None) {
733 if (filteredrevs != Py_None) {
740 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
734 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
741 if (!filter) {
735 if (!filter) {
742 PyErr_SetString(PyExc_TypeError,
736 PyErr_SetString(PyExc_TypeError,
743 "filteredrevs has no attribute __contains__");
737 "filteredrevs has no attribute __contains__");
744 goto bail;
738 goto bail;
745 }
739 }
746 }
740 }
747
741
748 len = index_length(self) - 1;
742 len = index_length(self) - 1;
749 heads = PyList_New(0);
743 heads = PyList_New(0);
750 if (heads == NULL)
744 if (heads == NULL)
751 goto bail;
745 goto bail;
752 if (len == 0) {
746 if (len == 0) {
753 PyObject *nullid = PyInt_FromLong(-1);
747 PyObject *nullid = PyInt_FromLong(-1);
754 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
748 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
755 Py_XDECREF(nullid);
749 Py_XDECREF(nullid);
756 goto bail;
750 goto bail;
757 }
751 }
758 goto done;
752 goto done;
759 }
753 }
760
754
761 nothead = calloc(len, 1);
755 nothead = calloc(len, 1);
762 if (nothead == NULL) {
756 if (nothead == NULL) {
763 PyErr_NoMemory();
757 PyErr_NoMemory();
764 goto bail;
758 goto bail;
765 }
759 }
766
760
767 for (i = len - 1; i >= 0; i--) {
761 for (i = len - 1; i >= 0; i--) {
768 int isfiltered;
762 int isfiltered;
769 int parents[2];
763 int parents[2];
770
764
771 /* If nothead[i] == 1, it means we've seen an unfiltered child of this
765 /* If nothead[i] == 1, it means we've seen an unfiltered child of this
772 * node already, and therefore this node is not filtered. So we can skip
766 * node already, and therefore this node is not filtered. So we can skip
773 * the expensive check_filter step.
767 * the expensive check_filter step.
774 */
768 */
775 if (nothead[i] != 1) {
769 if (nothead[i] != 1) {
776 isfiltered = check_filter(filter, i);
770 isfiltered = check_filter(filter, i);
777 if (isfiltered == -1) {
771 if (isfiltered == -1) {
778 PyErr_SetString(PyExc_TypeError,
772 PyErr_SetString(PyExc_TypeError,
779 "unable to check filter");
773 "unable to check filter");
780 goto bail;
774 goto bail;
781 }
775 }
782
776
783 if (isfiltered) {
777 if (isfiltered) {
784 nothead[i] = 1;
778 nothead[i] = 1;
785 continue;
779 continue;
786 }
780 }
787 }
781 }
788
782
789 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
783 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
790 goto bail;
784 goto bail;
791 for (j = 0; j < 2; j++) {
785 for (j = 0; j < 2; j++) {
792 if (parents[j] >= 0)
786 if (parents[j] >= 0)
793 nothead[parents[j]] = 1;
787 nothead[parents[j]] = 1;
794 }
788 }
795 }
789 }
796
790
797 for (i = 0; i < len; i++) {
791 for (i = 0; i < len; i++) {
798 PyObject *head;
792 PyObject *head;
799
793
800 if (nothead[i])
794 if (nothead[i])
801 continue;
795 continue;
802 head = PyInt_FromSsize_t(i);
796 head = PyInt_FromSsize_t(i);
803 if (head == NULL || PyList_Append(heads, head) == -1) {
797 if (head == NULL || PyList_Append(heads, head) == -1) {
804 Py_XDECREF(head);
798 Py_XDECREF(head);
805 goto bail;
799 goto bail;
806 }
800 }
807 }
801 }
808
802
809 done:
803 done:
810 self->headrevs = heads;
804 self->headrevs = heads;
811 Py_XDECREF(filter);
805 Py_XDECREF(filter);
812 free(nothead);
806 free(nothead);
813 return list_copy(self->headrevs);
807 return list_copy(self->headrevs);
814 bail:
808 bail:
815 Py_XDECREF(filter);
809 Py_XDECREF(filter);
816 Py_XDECREF(heads);
810 Py_XDECREF(heads);
817 free(nothead);
811 free(nothead);
818 return NULL;
812 return NULL;
819 }
813 }
820
814
821 /**
815 /**
822 * Obtain the base revision index entry.
816 * Obtain the base revision index entry.
823 *
817 *
824 * Callers must ensure that rev >= 0 or illegal memory access may occur.
818 * Callers must ensure that rev >= 0 or illegal memory access may occur.
825 */
819 */
826 static inline int index_baserev(indexObject *self, int rev)
820 static inline int index_baserev(indexObject *self, int rev)
827 {
821 {
828 const char *data;
822 const char *data;
829
823
830 if (rev >= self->length - 1) {
824 if (rev >= self->length - 1) {
831 PyObject *tuple = PyList_GET_ITEM(self->added,
825 PyObject *tuple = PyList_GET_ITEM(self->added,
832 rev - self->length + 1);
826 rev - self->length + 1);
833 return (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 3));
827 return (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 3));
834 }
828 }
835 else {
829 else {
836 data = index_deref(self, rev);
830 data = index_deref(self, rev);
837 if (data == NULL) {
831 if (data == NULL) {
838 return -2;
832 return -2;
839 }
833 }
840
834
841 return getbe32(data + 16);
835 return getbe32(data + 16);
842 }
836 }
843 }
837 }
844
838
845 static PyObject *index_deltachain(indexObject *self, PyObject *args)
839 static PyObject *index_deltachain(indexObject *self, PyObject *args)
846 {
840 {
847 int rev, generaldelta;
841 int rev, generaldelta;
848 PyObject *stoparg;
842 PyObject *stoparg;
849 int stoprev, iterrev, baserev = -1;
843 int stoprev, iterrev, baserev = -1;
850 int stopped;
844 int stopped;
851 PyObject *chain = NULL, *result = NULL;
845 PyObject *chain = NULL, *result = NULL;
852 const Py_ssize_t length = index_length(self);
846 const Py_ssize_t length = index_length(self);
853
847
854 if (!PyArg_ParseTuple(args, "iOi", &rev, &stoparg, &generaldelta)) {
848 if (!PyArg_ParseTuple(args, "iOi", &rev, &stoparg, &generaldelta)) {
855 return NULL;
849 return NULL;
856 }
850 }
857
851
858 if (PyInt_Check(stoparg)) {
852 if (PyInt_Check(stoparg)) {
859 stoprev = (int)PyInt_AsLong(stoparg);
853 stoprev = (int)PyInt_AsLong(stoparg);
860 if (stoprev == -1 && PyErr_Occurred()) {
854 if (stoprev == -1 && PyErr_Occurred()) {
861 return NULL;
855 return NULL;
862 }
856 }
863 }
857 }
864 else if (stoparg == Py_None) {
858 else if (stoparg == Py_None) {
865 stoprev = -2;
859 stoprev = -2;
866 }
860 }
867 else {
861 else {
868 PyErr_SetString(PyExc_ValueError,
862 PyErr_SetString(PyExc_ValueError,
869 "stoprev must be integer or None");
863 "stoprev must be integer or None");
870 return NULL;
864 return NULL;
871 }
865 }
872
866
873 if (rev < 0 || rev >= length - 1) {
867 if (rev < 0 || rev >= length - 1) {
874 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
868 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
875 return NULL;
869 return NULL;
876 }
870 }
877
871
878 chain = PyList_New(0);
872 chain = PyList_New(0);
879 if (chain == NULL) {
873 if (chain == NULL) {
880 return NULL;
874 return NULL;
881 }
875 }
882
876
883 baserev = index_baserev(self, rev);
877 baserev = index_baserev(self, rev);
884
878
885 /* This should never happen. */
879 /* This should never happen. */
886 if (baserev <= -2) {
880 if (baserev <= -2) {
887 /* Error should be set by index_deref() */
881 /* Error should be set by index_deref() */
888 assert(PyErr_Occurred());
882 assert(PyErr_Occurred());
889 goto bail;
883 goto bail;
890 }
884 }
891
885
892 iterrev = rev;
886 iterrev = rev;
893
887
894 while (iterrev != baserev && iterrev != stoprev) {
888 while (iterrev != baserev && iterrev != stoprev) {
895 PyObject *value = PyInt_FromLong(iterrev);
889 PyObject *value = PyInt_FromLong(iterrev);
896 if (value == NULL) {
890 if (value == NULL) {
897 goto bail;
891 goto bail;
898 }
892 }
899 if (PyList_Append(chain, value)) {
893 if (PyList_Append(chain, value)) {
900 Py_DECREF(value);
894 Py_DECREF(value);
901 goto bail;
895 goto bail;
902 }
896 }
903 Py_DECREF(value);
897 Py_DECREF(value);
904
898
905 if (generaldelta) {
899 if (generaldelta) {
906 iterrev = baserev;
900 iterrev = baserev;
907 }
901 }
908 else {
902 else {
909 iterrev--;
903 iterrev--;
910 }
904 }
911
905
912 if (iterrev < 0) {
906 if (iterrev < 0) {
913 break;
907 break;
914 }
908 }
915
909
916 if (iterrev >= length - 1) {
910 if (iterrev >= length - 1) {
917 PyErr_SetString(PyExc_IndexError, "revision outside index");
911 PyErr_SetString(PyExc_IndexError, "revision outside index");
918 return NULL;
912 return NULL;
919 }
913 }
920
914
921 baserev = index_baserev(self, iterrev);
915 baserev = index_baserev(self, iterrev);
922
916
923 /* This should never happen. */
917 /* This should never happen. */
924 if (baserev <= -2) {
918 if (baserev <= -2) {
925 /* Error should be set by index_deref() */
919 /* Error should be set by index_deref() */
926 assert(PyErr_Occurred());
920 assert(PyErr_Occurred());
927 goto bail;
921 goto bail;
928 }
922 }
929 }
923 }
930
924
931 if (iterrev == stoprev) {
925 if (iterrev == stoprev) {
932 stopped = 1;
926 stopped = 1;
933 }
927 }
934 else {
928 else {
935 PyObject *value = PyInt_FromLong(iterrev);
929 PyObject *value = PyInt_FromLong(iterrev);
936 if (value == NULL) {
930 if (value == NULL) {
937 goto bail;
931 goto bail;
938 }
932 }
939 if (PyList_Append(chain, value)) {
933 if (PyList_Append(chain, value)) {
940 Py_DECREF(value);
934 Py_DECREF(value);
941 goto bail;
935 goto bail;
942 }
936 }
943 Py_DECREF(value);
937 Py_DECREF(value);
944
938
945 stopped = 0;
939 stopped = 0;
946 }
940 }
947
941
948 if (PyList_Reverse(chain)) {
942 if (PyList_Reverse(chain)) {
949 goto bail;
943 goto bail;
950 }
944 }
951
945
952 result = Py_BuildValue("OO", chain, stopped ? Py_True : Py_False);
946 result = Py_BuildValue("OO", chain, stopped ? Py_True : Py_False);
953 Py_DECREF(chain);
947 Py_DECREF(chain);
954 return result;
948 return result;
955
949
956 bail:
950 bail:
957 Py_DECREF(chain);
951 Py_DECREF(chain);
958 return NULL;
952 return NULL;
959 }
953 }
960
954
961 static inline int nt_level(const char *node, Py_ssize_t level)
955 static inline int nt_level(const char *node, Py_ssize_t level)
962 {
956 {
963 int v = node[level>>1];
957 int v = node[level>>1];
964 if (!(level & 1))
958 if (!(level & 1))
965 v >>= 4;
959 v >>= 4;
966 return v & 0xf;
960 return v & 0xf;
967 }
961 }
968
962
969 /*
963 /*
970 * Return values:
964 * Return values:
971 *
965 *
972 * -4: match is ambiguous (multiple candidates)
966 * -4: match is ambiguous (multiple candidates)
973 * -2: not found
967 * -2: not found
974 * rest: valid rev
968 * rest: valid rev
975 */
969 */
976 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
970 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
977 int hex)
971 int hex)
978 {
972 {
979 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
973 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
980 int level, maxlevel, off;
974 int level, maxlevel, off;
981
975
982 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
976 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
983 return -1;
977 return -1;
984
978
985 if (self->nt == NULL)
979 if (self->nt == NULL)
986 return -2;
980 return -2;
987
981
988 if (hex)
982 if (hex)
989 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
983 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
990 else
984 else
991 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
985 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
992
986
993 for (level = off = 0; level < maxlevel; level++) {
987 for (level = off = 0; level < maxlevel; level++) {
994 int k = getnybble(node, level);
988 int k = getnybble(node, level);
995 nodetree *n = &self->nt[off];
989 nodetree *n = &self->nt[off];
996 int v = n->children[k];
990 int v = n->children[k];
997
991
998 if (v < 0) {
992 if (v < 0) {
999 const char *n;
993 const char *n;
1000 Py_ssize_t i;
994 Py_ssize_t i;
1001
995
1002 v = -(v + 1);
996 v = -(v + 1);
1003 n = index_node(self, v);
997 n = index_node(self, v);
1004 if (n == NULL)
998 if (n == NULL)
1005 return -2;
999 return -2;
1006 for (i = level; i < maxlevel; i++)
1000 for (i = level; i < maxlevel; i++)
1007 if (getnybble(node, i) != nt_level(n, i))
1001 if (getnybble(node, i) != nt_level(n, i))
1008 return -2;
1002 return -2;
1009 return v;
1003 return v;
1010 }
1004 }
1011 if (v == 0)
1005 if (v == 0)
1012 return -2;
1006 return -2;
1013 off = v;
1007 off = v;
1014 }
1008 }
1015 /* multiple matches against an ambiguous prefix */
1009 /* multiple matches against an ambiguous prefix */
1016 return -4;
1010 return -4;
1017 }
1011 }
1018
1012
1019 static int nt_new(indexObject *self)
1013 static int nt_new(indexObject *self)
1020 {
1014 {
1021 if (self->ntlength == self->ntcapacity) {
1015 if (self->ntlength == self->ntcapacity) {
1022 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1016 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1023 PyErr_SetString(PyExc_MemoryError,
1017 PyErr_SetString(PyExc_MemoryError,
1024 "overflow in nt_new");
1018 "overflow in nt_new");
1025 return -1;
1019 return -1;
1026 }
1020 }
1027 self->ntcapacity *= 2;
1021 self->ntcapacity *= 2;
1028 self->nt = realloc(self->nt,
1022 self->nt = realloc(self->nt,
1029 self->ntcapacity * sizeof(nodetree));
1023 self->ntcapacity * sizeof(nodetree));
1030 if (self->nt == NULL) {
1024 if (self->nt == NULL) {
1031 PyErr_SetString(PyExc_MemoryError, "out of memory");
1025 PyErr_SetString(PyExc_MemoryError, "out of memory");
1032 return -1;
1026 return -1;
1033 }
1027 }
1034 memset(&self->nt[self->ntlength], 0,
1028 memset(&self->nt[self->ntlength], 0,
1035 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1029 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1036 }
1030 }
1037 return self->ntlength++;
1031 return self->ntlength++;
1038 }
1032 }
1039
1033
1040 static int nt_insert(indexObject *self, const char *node, int rev)
1034 static int nt_insert(indexObject *self, const char *node, int rev)
1041 {
1035 {
1042 int level = 0;
1036 int level = 0;
1043 int off = 0;
1037 int off = 0;
1044
1038
1045 while (level < 40) {
1039 while (level < 40) {
1046 int k = nt_level(node, level);
1040 int k = nt_level(node, level);
1047 nodetree *n;
1041 nodetree *n;
1048 int v;
1042 int v;
1049
1043
1050 n = &self->nt[off];
1044 n = &self->nt[off];
1051 v = n->children[k];
1045 v = n->children[k];
1052
1046
1053 if (v == 0) {
1047 if (v == 0) {
1054 n->children[k] = -rev - 1;
1048 n->children[k] = -rev - 1;
1055 return 0;
1049 return 0;
1056 }
1050 }
1057 if (v < 0) {
1051 if (v < 0) {
1058 const char *oldnode = index_node(self, -(v + 1));
1052 const char *oldnode = index_node(self, -(v + 1));
1059 int noff;
1053 int noff;
1060
1054
1061 if (!oldnode || !memcmp(oldnode, node, 20)) {
1055 if (!oldnode || !memcmp(oldnode, node, 20)) {
1062 n->children[k] = -rev - 1;
1056 n->children[k] = -rev - 1;
1063 return 0;
1057 return 0;
1064 }
1058 }
1065 noff = nt_new(self);
1059 noff = nt_new(self);
1066 if (noff == -1)
1060 if (noff == -1)
1067 return -1;
1061 return -1;
1068 /* self->nt may have been changed by realloc */
1062 /* self->nt may have been changed by realloc */
1069 self->nt[off].children[k] = noff;
1063 self->nt[off].children[k] = noff;
1070 off = noff;
1064 off = noff;
1071 n = &self->nt[off];
1065 n = &self->nt[off];
1072 n->children[nt_level(oldnode, ++level)] = v;
1066 n->children[nt_level(oldnode, ++level)] = v;
1073 if (level > self->ntdepth)
1067 if (level > self->ntdepth)
1074 self->ntdepth = level;
1068 self->ntdepth = level;
1075 self->ntsplits += 1;
1069 self->ntsplits += 1;
1076 } else {
1070 } else {
1077 level += 1;
1071 level += 1;
1078 off = v;
1072 off = v;
1079 }
1073 }
1080 }
1074 }
1081
1075
1082 return -1;
1076 return -1;
1083 }
1077 }
1084
1078
1085 static int nt_init(indexObject *self)
1079 static int nt_init(indexObject *self)
1086 {
1080 {
1087 if (self->nt == NULL) {
1081 if (self->nt == NULL) {
1088 if ((size_t)self->raw_length > INT_MAX / sizeof(nodetree)) {
1082 if ((size_t)self->raw_length > INT_MAX / sizeof(nodetree)) {
1089 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1083 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1090 return -1;
1084 return -1;
1091 }
1085 }
1092 self->ntcapacity = self->raw_length < 4
1086 self->ntcapacity = self->raw_length < 4
1093 ? 4 : (int)self->raw_length / 2;
1087 ? 4 : (int)self->raw_length / 2;
1094
1088
1095 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1089 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1096 if (self->nt == NULL) {
1090 if (self->nt == NULL) {
1097 PyErr_NoMemory();
1091 PyErr_NoMemory();
1098 return -1;
1092 return -1;
1099 }
1093 }
1100 self->ntlength = 1;
1094 self->ntlength = 1;
1101 self->ntrev = (int)index_length(self) - 1;
1095 self->ntrev = (int)index_length(self) - 1;
1102 self->ntlookups = 1;
1096 self->ntlookups = 1;
1103 self->ntmisses = 0;
1097 self->ntmisses = 0;
1104 if (nt_insert(self, nullid, INT_MAX) == -1)
1098 if (nt_insert(self, nullid, INT_MAX) == -1)
1105 return -1;
1099 return -1;
1106 }
1100 }
1107 return 0;
1101 return 0;
1108 }
1102 }
1109
1103
1110 /*
1104 /*
1111 * Return values:
1105 * Return values:
1112 *
1106 *
1113 * -3: error (exception set)
1107 * -3: error (exception set)
1114 * -2: not found (no exception set)
1108 * -2: not found (no exception set)
1115 * rest: valid rev
1109 * rest: valid rev
1116 */
1110 */
1117 static int index_find_node(indexObject *self,
1111 static int index_find_node(indexObject *self,
1118 const char *node, Py_ssize_t nodelen)
1112 const char *node, Py_ssize_t nodelen)
1119 {
1113 {
1120 int rev;
1114 int rev;
1121
1115
1122 self->ntlookups++;
1116 self->ntlookups++;
1123 rev = nt_find(self, node, nodelen, 0);
1117 rev = nt_find(self, node, nodelen, 0);
1124 if (rev >= -1)
1118 if (rev >= -1)
1125 return rev;
1119 return rev;
1126
1120
1127 if (nt_init(self) == -1)
1121 if (nt_init(self) == -1)
1128 return -3;
1122 return -3;
1129
1123
1130 /*
1124 /*
1131 * For the first handful of lookups, we scan the entire index,
1125 * For the first handful of lookups, we scan the entire index,
1132 * and cache only the matching nodes. This optimizes for cases
1126 * and cache only the matching nodes. This optimizes for cases
1133 * like "hg tip", where only a few nodes are accessed.
1127 * like "hg tip", where only a few nodes are accessed.
1134 *
1128 *
1135 * After that, we cache every node we visit, using a single
1129 * After that, we cache every node we visit, using a single
1136 * scan amortized over multiple lookups. This gives the best
1130 * scan amortized over multiple lookups. This gives the best
1137 * bulk performance, e.g. for "hg log".
1131 * bulk performance, e.g. for "hg log".
1138 */
1132 */
1139 if (self->ntmisses++ < 4) {
1133 if (self->ntmisses++ < 4) {
1140 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1134 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1141 const char *n = index_node(self, rev);
1135 const char *n = index_node(self, rev);
1142 if (n == NULL)
1136 if (n == NULL)
1143 return -2;
1137 return -2;
1144 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1138 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1145 if (nt_insert(self, n, rev) == -1)
1139 if (nt_insert(self, n, rev) == -1)
1146 return -3;
1140 return -3;
1147 break;
1141 break;
1148 }
1142 }
1149 }
1143 }
1150 } else {
1144 } else {
1151 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1145 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1152 const char *n = index_node(self, rev);
1146 const char *n = index_node(self, rev);
1153 if (n == NULL) {
1147 if (n == NULL) {
1154 self->ntrev = rev + 1;
1148 self->ntrev = rev + 1;
1155 return -2;
1149 return -2;
1156 }
1150 }
1157 if (nt_insert(self, n, rev) == -1) {
1151 if (nt_insert(self, n, rev) == -1) {
1158 self->ntrev = rev + 1;
1152 self->ntrev = rev + 1;
1159 return -3;
1153 return -3;
1160 }
1154 }
1161 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1155 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1162 break;
1156 break;
1163 }
1157 }
1164 }
1158 }
1165 self->ntrev = rev;
1159 self->ntrev = rev;
1166 }
1160 }
1167
1161
1168 if (rev >= 0)
1162 if (rev >= 0)
1169 return rev;
1163 return rev;
1170 return -2;
1164 return -2;
1171 }
1165 }
1172
1166
1173 static void raise_revlog_error(void)
1167 static void raise_revlog_error(void)
1174 {
1168 {
1175 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1169 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1176
1170
1177 mod = PyImport_ImportModule("mercurial.error");
1171 mod = PyImport_ImportModule("mercurial.error");
1178 if (mod == NULL) {
1172 if (mod == NULL) {
1179 goto cleanup;
1173 goto cleanup;
1180 }
1174 }
1181
1175
1182 dict = PyModule_GetDict(mod);
1176 dict = PyModule_GetDict(mod);
1183 if (dict == NULL) {
1177 if (dict == NULL) {
1184 goto cleanup;
1178 goto cleanup;
1185 }
1179 }
1186 Py_INCREF(dict);
1180 Py_INCREF(dict);
1187
1181
1188 errclass = PyDict_GetItemString(dict, "RevlogError");
1182 errclass = PyDict_GetItemString(dict, "RevlogError");
1189 if (errclass == NULL) {
1183 if (errclass == NULL) {
1190 PyErr_SetString(PyExc_SystemError,
1184 PyErr_SetString(PyExc_SystemError,
1191 "could not find RevlogError");
1185 "could not find RevlogError");
1192 goto cleanup;
1186 goto cleanup;
1193 }
1187 }
1194
1188
1195 /* value of exception is ignored by callers */
1189 /* value of exception is ignored by callers */
1196 PyErr_SetString(errclass, "RevlogError");
1190 PyErr_SetString(errclass, "RevlogError");
1197
1191
1198 cleanup:
1192 cleanup:
1199 Py_XDECREF(dict);
1193 Py_XDECREF(dict);
1200 Py_XDECREF(mod);
1194 Py_XDECREF(mod);
1201 }
1195 }
1202
1196
1203 static PyObject *index_getitem(indexObject *self, PyObject *value)
1197 static PyObject *index_getitem(indexObject *self, PyObject *value)
1204 {
1198 {
1205 char *node;
1199 char *node;
1206 Py_ssize_t nodelen;
1200 Py_ssize_t nodelen;
1207 int rev;
1201 int rev;
1208
1202
1209 if (PyInt_Check(value))
1203 if (PyInt_Check(value))
1210 return index_get(self, PyInt_AS_LONG(value));
1204 return index_get(self, PyInt_AS_LONG(value));
1211
1205
1212 if (node_check(value, &node, &nodelen) == -1)
1206 if (node_check(value, &node, &nodelen) == -1)
1213 return NULL;
1207 return NULL;
1214 rev = index_find_node(self, node, nodelen);
1208 rev = index_find_node(self, node, nodelen);
1215 if (rev >= -1)
1209 if (rev >= -1)
1216 return PyInt_FromLong(rev);
1210 return PyInt_FromLong(rev);
1217 if (rev == -2)
1211 if (rev == -2)
1218 raise_revlog_error();
1212 raise_revlog_error();
1219 return NULL;
1213 return NULL;
1220 }
1214 }
1221
1215
1222 static int nt_partialmatch(indexObject *self, const char *node,
1216 static int nt_partialmatch(indexObject *self, const char *node,
1223 Py_ssize_t nodelen)
1217 Py_ssize_t nodelen)
1224 {
1218 {
1225 int rev;
1219 int rev;
1226
1220
1227 if (nt_init(self) == -1)
1221 if (nt_init(self) == -1)
1228 return -3;
1222 return -3;
1229
1223
1230 if (self->ntrev > 0) {
1224 if (self->ntrev > 0) {
1231 /* ensure that the radix tree is fully populated */
1225 /* ensure that the radix tree is fully populated */
1232 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1226 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1233 const char *n = index_node(self, rev);
1227 const char *n = index_node(self, rev);
1234 if (n == NULL)
1228 if (n == NULL)
1235 return -2;
1229 return -2;
1236 if (nt_insert(self, n, rev) == -1)
1230 if (nt_insert(self, n, rev) == -1)
1237 return -3;
1231 return -3;
1238 }
1232 }
1239 self->ntrev = rev;
1233 self->ntrev = rev;
1240 }
1234 }
1241
1235
1242 return nt_find(self, node, nodelen, 1);
1236 return nt_find(self, node, nodelen, 1);
1243 }
1237 }
1244
1238
1245 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1239 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1246 {
1240 {
1247 const char *fullnode;
1241 const char *fullnode;
1248 int nodelen;
1242 int nodelen;
1249 char *node;
1243 char *node;
1250 int rev, i;
1244 int rev, i;
1251
1245
1252 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1246 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1253 return NULL;
1247 return NULL;
1254
1248
1255 if (nodelen < 4) {
1249 if (nodelen < 4) {
1256 PyErr_SetString(PyExc_ValueError, "key too short");
1250 PyErr_SetString(PyExc_ValueError, "key too short");
1257 return NULL;
1251 return NULL;
1258 }
1252 }
1259
1253
1260 if (nodelen > 40) {
1254 if (nodelen > 40) {
1261 PyErr_SetString(PyExc_ValueError, "key too long");
1255 PyErr_SetString(PyExc_ValueError, "key too long");
1262 return NULL;
1256 return NULL;
1263 }
1257 }
1264
1258
1265 for (i = 0; i < nodelen; i++)
1259 for (i = 0; i < nodelen; i++)
1266 hexdigit(node, i);
1260 hexdigit(node, i);
1267 if (PyErr_Occurred()) {
1261 if (PyErr_Occurred()) {
1268 /* input contains non-hex characters */
1262 /* input contains non-hex characters */
1269 PyErr_Clear();
1263 PyErr_Clear();
1270 Py_RETURN_NONE;
1264 Py_RETURN_NONE;
1271 }
1265 }
1272
1266
1273 rev = nt_partialmatch(self, node, nodelen);
1267 rev = nt_partialmatch(self, node, nodelen);
1274
1268
1275 switch (rev) {
1269 switch (rev) {
1276 case -4:
1270 case -4:
1277 raise_revlog_error();
1271 raise_revlog_error();
1278 case -3:
1272 case -3:
1279 return NULL;
1273 return NULL;
1280 case -2:
1274 case -2:
1281 Py_RETURN_NONE;
1275 Py_RETURN_NONE;
1282 case -1:
1276 case -1:
1283 return PyBytes_FromStringAndSize(nullid, 20);
1277 return PyBytes_FromStringAndSize(nullid, 20);
1284 }
1278 }
1285
1279
1286 fullnode = index_node(self, rev);
1280 fullnode = index_node(self, rev);
1287 if (fullnode == NULL) {
1281 if (fullnode == NULL) {
1288 PyErr_Format(PyExc_IndexError,
1282 PyErr_Format(PyExc_IndexError,
1289 "could not access rev %d", rev);
1283 "could not access rev %d", rev);
1290 return NULL;
1284 return NULL;
1291 }
1285 }
1292 return PyBytes_FromStringAndSize(fullnode, 20);
1286 return PyBytes_FromStringAndSize(fullnode, 20);
1293 }
1287 }
1294
1288
1295 static PyObject *index_m_get(indexObject *self, PyObject *args)
1289 static PyObject *index_m_get(indexObject *self, PyObject *args)
1296 {
1290 {
1297 Py_ssize_t nodelen;
1291 Py_ssize_t nodelen;
1298 PyObject *val;
1292 PyObject *val;
1299 char *node;
1293 char *node;
1300 int rev;
1294 int rev;
1301
1295
1302 if (!PyArg_ParseTuple(args, "O", &val))
1296 if (!PyArg_ParseTuple(args, "O", &val))
1303 return NULL;
1297 return NULL;
1304 if (node_check(val, &node, &nodelen) == -1)
1298 if (node_check(val, &node, &nodelen) == -1)
1305 return NULL;
1299 return NULL;
1306 rev = index_find_node(self, node, nodelen);
1300 rev = index_find_node(self, node, nodelen);
1307 if (rev == -3)
1301 if (rev == -3)
1308 return NULL;
1302 return NULL;
1309 if (rev == -2)
1303 if (rev == -2)
1310 Py_RETURN_NONE;
1304 Py_RETURN_NONE;
1311 return PyInt_FromLong(rev);
1305 return PyInt_FromLong(rev);
1312 }
1306 }
1313
1307
1314 static int index_contains(indexObject *self, PyObject *value)
1308 static int index_contains(indexObject *self, PyObject *value)
1315 {
1309 {
1316 char *node;
1310 char *node;
1317 Py_ssize_t nodelen;
1311 Py_ssize_t nodelen;
1318
1312
1319 if (PyInt_Check(value)) {
1313 if (PyInt_Check(value)) {
1320 long rev = PyInt_AS_LONG(value);
1314 long rev = PyInt_AS_LONG(value);
1321 return rev >= -1 && rev < index_length(self);
1315 return rev >= -1 && rev < index_length(self);
1322 }
1316 }
1323
1317
1324 if (node_check(value, &node, &nodelen) == -1)
1318 if (node_check(value, &node, &nodelen) == -1)
1325 return -1;
1319 return -1;
1326
1320
1327 switch (index_find_node(self, node, nodelen)) {
1321 switch (index_find_node(self, node, nodelen)) {
1328 case -3:
1322 case -3:
1329 return -1;
1323 return -1;
1330 case -2:
1324 case -2:
1331 return 0;
1325 return 0;
1332 default:
1326 default:
1333 return 1;
1327 return 1;
1334 }
1328 }
1335 }
1329 }
1336
1330
1337 typedef uint64_t bitmask;
1331 typedef uint64_t bitmask;
1338
1332
1339 /*
1333 /*
1340 * Given a disjoint set of revs, return all candidates for the
1334 * Given a disjoint set of revs, return all candidates for the
1341 * greatest common ancestor. In revset notation, this is the set
1335 * greatest common ancestor. In revset notation, this is the set
1342 * "heads(::a and ::b and ...)"
1336 * "heads(::a and ::b and ...)"
1343 */
1337 */
1344 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1338 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1345 int revcount)
1339 int revcount)
1346 {
1340 {
1347 const bitmask allseen = (1ull << revcount) - 1;
1341 const bitmask allseen = (1ull << revcount) - 1;
1348 const bitmask poison = 1ull << revcount;
1342 const bitmask poison = 1ull << revcount;
1349 PyObject *gca = PyList_New(0);
1343 PyObject *gca = PyList_New(0);
1350 int i, v, interesting;
1344 int i, v, interesting;
1351 int maxrev = -1;
1345 int maxrev = -1;
1352 bitmask sp;
1346 bitmask sp;
1353 bitmask *seen;
1347 bitmask *seen;
1354
1348
1355 if (gca == NULL)
1349 if (gca == NULL)
1356 return PyErr_NoMemory();
1350 return PyErr_NoMemory();
1357
1351
1358 for (i = 0; i < revcount; i++) {
1352 for (i = 0; i < revcount; i++) {
1359 if (revs[i] > maxrev)
1353 if (revs[i] > maxrev)
1360 maxrev = revs[i];
1354 maxrev = revs[i];
1361 }
1355 }
1362
1356
1363 seen = calloc(sizeof(*seen), maxrev + 1);
1357 seen = calloc(sizeof(*seen), maxrev + 1);
1364 if (seen == NULL) {
1358 if (seen == NULL) {
1365 Py_DECREF(gca);
1359 Py_DECREF(gca);
1366 return PyErr_NoMemory();
1360 return PyErr_NoMemory();
1367 }
1361 }
1368
1362
1369 for (i = 0; i < revcount; i++)
1363 for (i = 0; i < revcount; i++)
1370 seen[revs[i]] = 1ull << i;
1364 seen[revs[i]] = 1ull << i;
1371
1365
1372 interesting = revcount;
1366 interesting = revcount;
1373
1367
1374 for (v = maxrev; v >= 0 && interesting; v--) {
1368 for (v = maxrev; v >= 0 && interesting; v--) {
1375 bitmask sv = seen[v];
1369 bitmask sv = seen[v];
1376 int parents[2];
1370 int parents[2];
1377
1371
1378 if (!sv)
1372 if (!sv)
1379 continue;
1373 continue;
1380
1374
1381 if (sv < poison) {
1375 if (sv < poison) {
1382 interesting -= 1;
1376 interesting -= 1;
1383 if (sv == allseen) {
1377 if (sv == allseen) {
1384 PyObject *obj = PyInt_FromLong(v);
1378 PyObject *obj = PyInt_FromLong(v);
1385 if (obj == NULL)
1379 if (obj == NULL)
1386 goto bail;
1380 goto bail;
1387 if (PyList_Append(gca, obj) == -1) {
1381 if (PyList_Append(gca, obj) == -1) {
1388 Py_DECREF(obj);
1382 Py_DECREF(obj);
1389 goto bail;
1383 goto bail;
1390 }
1384 }
1391 sv |= poison;
1385 sv |= poison;
1392 for (i = 0; i < revcount; i++) {
1386 for (i = 0; i < revcount; i++) {
1393 if (revs[i] == v)
1387 if (revs[i] == v)
1394 goto done;
1388 goto done;
1395 }
1389 }
1396 }
1390 }
1397 }
1391 }
1398 if (index_get_parents(self, v, parents, maxrev) < 0)
1392 if (index_get_parents(self, v, parents, maxrev) < 0)
1399 goto bail;
1393 goto bail;
1400
1394
1401 for (i = 0; i < 2; i++) {
1395 for (i = 0; i < 2; i++) {
1402 int p = parents[i];
1396 int p = parents[i];
1403 if (p == -1)
1397 if (p == -1)
1404 continue;
1398 continue;
1405 sp = seen[p];
1399 sp = seen[p];
1406 if (sv < poison) {
1400 if (sv < poison) {
1407 if (sp == 0) {
1401 if (sp == 0) {
1408 seen[p] = sv;
1402 seen[p] = sv;
1409 interesting++;
1403 interesting++;
1410 }
1404 }
1411 else if (sp != sv)
1405 else if (sp != sv)
1412 seen[p] |= sv;
1406 seen[p] |= sv;
1413 } else {
1407 } else {
1414 if (sp && sp < poison)
1408 if (sp && sp < poison)
1415 interesting--;
1409 interesting--;
1416 seen[p] = sv;
1410 seen[p] = sv;
1417 }
1411 }
1418 }
1412 }
1419 }
1413 }
1420
1414
1421 done:
1415 done:
1422 free(seen);
1416 free(seen);
1423 return gca;
1417 return gca;
1424 bail:
1418 bail:
1425 free(seen);
1419 free(seen);
1426 Py_XDECREF(gca);
1420 Py_XDECREF(gca);
1427 return NULL;
1421 return NULL;
1428 }
1422 }
1429
1423
1430 /*
1424 /*
1431 * Given a disjoint set of revs, return the subset with the longest
1425 * Given a disjoint set of revs, return the subset with the longest
1432 * path to the root.
1426 * path to the root.
1433 */
1427 */
1434 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1428 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1435 {
1429 {
1436 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1430 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1437 static const Py_ssize_t capacity = 24;
1431 static const Py_ssize_t capacity = 24;
1438 int *depth, *interesting = NULL;
1432 int *depth, *interesting = NULL;
1439 int i, j, v, ninteresting;
1433 int i, j, v, ninteresting;
1440 PyObject *dict = NULL, *keys = NULL;
1434 PyObject *dict = NULL, *keys = NULL;
1441 long *seen = NULL;
1435 long *seen = NULL;
1442 int maxrev = -1;
1436 int maxrev = -1;
1443 long final;
1437 long final;
1444
1438
1445 if (revcount > capacity) {
1439 if (revcount > capacity) {
1446 PyErr_Format(PyExc_OverflowError,
1440 PyErr_Format(PyExc_OverflowError,
1447 "bitset size (%ld) > capacity (%ld)",
1441 "bitset size (%ld) > capacity (%ld)",
1448 (long)revcount, (long)capacity);
1442 (long)revcount, (long)capacity);
1449 return NULL;
1443 return NULL;
1450 }
1444 }
1451
1445
1452 for (i = 0; i < revcount; i++) {
1446 for (i = 0; i < revcount; i++) {
1453 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1447 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1454 if (n > maxrev)
1448 if (n > maxrev)
1455 maxrev = n;
1449 maxrev = n;
1456 }
1450 }
1457
1451
1458 depth = calloc(sizeof(*depth), maxrev + 1);
1452 depth = calloc(sizeof(*depth), maxrev + 1);
1459 if (depth == NULL)
1453 if (depth == NULL)
1460 return PyErr_NoMemory();
1454 return PyErr_NoMemory();
1461
1455
1462 seen = calloc(sizeof(*seen), maxrev + 1);
1456 seen = calloc(sizeof(*seen), maxrev + 1);
1463 if (seen == NULL) {
1457 if (seen == NULL) {
1464 PyErr_NoMemory();
1458 PyErr_NoMemory();
1465 goto bail;
1459 goto bail;
1466 }
1460 }
1467
1461
1468 interesting = calloc(sizeof(*interesting), 1 << revcount);
1462 interesting = calloc(sizeof(*interesting), 1 << revcount);
1469 if (interesting == NULL) {
1463 if (interesting == NULL) {
1470 PyErr_NoMemory();
1464 PyErr_NoMemory();
1471 goto bail;
1465 goto bail;
1472 }
1466 }
1473
1467
1474 if (PyList_Sort(revs) == -1)
1468 if (PyList_Sort(revs) == -1)
1475 goto bail;
1469 goto bail;
1476
1470
1477 for (i = 0; i < revcount; i++) {
1471 for (i = 0; i < revcount; i++) {
1478 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1472 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1479 long b = 1l << i;
1473 long b = 1l << i;
1480 depth[n] = 1;
1474 depth[n] = 1;
1481 seen[n] = b;
1475 seen[n] = b;
1482 interesting[b] = 1;
1476 interesting[b] = 1;
1483 }
1477 }
1484
1478
1485 /* invariant: ninteresting is the number of non-zero entries in
1479 /* invariant: ninteresting is the number of non-zero entries in
1486 * interesting. */
1480 * interesting. */
1487 ninteresting = (int)revcount;
1481 ninteresting = (int)revcount;
1488
1482
1489 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1483 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1490 int dv = depth[v];
1484 int dv = depth[v];
1491 int parents[2];
1485 int parents[2];
1492 long sv;
1486 long sv;
1493
1487
1494 if (dv == 0)
1488 if (dv == 0)
1495 continue;
1489 continue;
1496
1490
1497 sv = seen[v];
1491 sv = seen[v];
1498 if (index_get_parents(self, v, parents, maxrev) < 0)
1492 if (index_get_parents(self, v, parents, maxrev) < 0)
1499 goto bail;
1493 goto bail;
1500
1494
1501 for (i = 0; i < 2; i++) {
1495 for (i = 0; i < 2; i++) {
1502 int p = parents[i];
1496 int p = parents[i];
1503 long sp;
1497 long sp;
1504 int dp;
1498 int dp;
1505
1499
1506 if (p == -1)
1500 if (p == -1)
1507 continue;
1501 continue;
1508
1502
1509 dp = depth[p];
1503 dp = depth[p];
1510 sp = seen[p];
1504 sp = seen[p];
1511 if (dp <= dv) {
1505 if (dp <= dv) {
1512 depth[p] = dv + 1;
1506 depth[p] = dv + 1;
1513 if (sp != sv) {
1507 if (sp != sv) {
1514 interesting[sv] += 1;
1508 interesting[sv] += 1;
1515 seen[p] = sv;
1509 seen[p] = sv;
1516 if (sp) {
1510 if (sp) {
1517 interesting[sp] -= 1;
1511 interesting[sp] -= 1;
1518 if (interesting[sp] == 0)
1512 if (interesting[sp] == 0)
1519 ninteresting -= 1;
1513 ninteresting -= 1;
1520 }
1514 }
1521 }
1515 }
1522 }
1516 }
1523 else if (dv == dp - 1) {
1517 else if (dv == dp - 1) {
1524 long nsp = sp | sv;
1518 long nsp = sp | sv;
1525 if (nsp == sp)
1519 if (nsp == sp)
1526 continue;
1520 continue;
1527 seen[p] = nsp;
1521 seen[p] = nsp;
1528 interesting[sp] -= 1;
1522 interesting[sp] -= 1;
1529 if (interesting[sp] == 0)
1523 if (interesting[sp] == 0)
1530 ninteresting -= 1;
1524 ninteresting -= 1;
1531 if (interesting[nsp] == 0)
1525 if (interesting[nsp] == 0)
1532 ninteresting += 1;
1526 ninteresting += 1;
1533 interesting[nsp] += 1;
1527 interesting[nsp] += 1;
1534 }
1528 }
1535 }
1529 }
1536 interesting[sv] -= 1;
1530 interesting[sv] -= 1;
1537 if (interesting[sv] == 0)
1531 if (interesting[sv] == 0)
1538 ninteresting -= 1;
1532 ninteresting -= 1;
1539 }
1533 }
1540
1534
1541 final = 0;
1535 final = 0;
1542 j = ninteresting;
1536 j = ninteresting;
1543 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
1537 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
1544 if (interesting[i] == 0)
1538 if (interesting[i] == 0)
1545 continue;
1539 continue;
1546 final |= i;
1540 final |= i;
1547 j -= 1;
1541 j -= 1;
1548 }
1542 }
1549 if (final == 0) {
1543 if (final == 0) {
1550 keys = PyList_New(0);
1544 keys = PyList_New(0);
1551 goto bail;
1545 goto bail;
1552 }
1546 }
1553
1547
1554 dict = PyDict_New();
1548 dict = PyDict_New();
1555 if (dict == NULL)
1549 if (dict == NULL)
1556 goto bail;
1550 goto bail;
1557
1551
1558 for (i = 0; i < revcount; i++) {
1552 for (i = 0; i < revcount; i++) {
1559 PyObject *key;
1553 PyObject *key;
1560
1554
1561 if ((final & (1 << i)) == 0)
1555 if ((final & (1 << i)) == 0)
1562 continue;
1556 continue;
1563
1557
1564 key = PyList_GET_ITEM(revs, i);
1558 key = PyList_GET_ITEM(revs, i);
1565 Py_INCREF(key);
1559 Py_INCREF(key);
1566 Py_INCREF(Py_None);
1560 Py_INCREF(Py_None);
1567 if (PyDict_SetItem(dict, key, Py_None) == -1) {
1561 if (PyDict_SetItem(dict, key, Py_None) == -1) {
1568 Py_DECREF(key);
1562 Py_DECREF(key);
1569 Py_DECREF(Py_None);
1563 Py_DECREF(Py_None);
1570 goto bail;
1564 goto bail;
1571 }
1565 }
1572 }
1566 }
1573
1567
1574 keys = PyDict_Keys(dict);
1568 keys = PyDict_Keys(dict);
1575
1569
1576 bail:
1570 bail:
1577 free(depth);
1571 free(depth);
1578 free(seen);
1572 free(seen);
1579 free(interesting);
1573 free(interesting);
1580 Py_XDECREF(dict);
1574 Py_XDECREF(dict);
1581
1575
1582 return keys;
1576 return keys;
1583 }
1577 }
1584
1578
1585 /*
1579 /*
1586 * Given a (possibly overlapping) set of revs, return all the
1580 * Given a (possibly overlapping) set of revs, return all the
1587 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
1581 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
1588 */
1582 */
1589 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
1583 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
1590 {
1584 {
1591 PyObject *ret = NULL;
1585 PyObject *ret = NULL;
1592 Py_ssize_t argcount, i, len;
1586 Py_ssize_t argcount, i, len;
1593 bitmask repeat = 0;
1587 bitmask repeat = 0;
1594 int revcount = 0;
1588 int revcount = 0;
1595 int *revs;
1589 int *revs;
1596
1590
1597 argcount = PySequence_Length(args);
1591 argcount = PySequence_Length(args);
1598 revs = PyMem_Malloc(argcount * sizeof(*revs));
1592 revs = PyMem_Malloc(argcount * sizeof(*revs));
1599 if (argcount > 0 && revs == NULL)
1593 if (argcount > 0 && revs == NULL)
1600 return PyErr_NoMemory();
1594 return PyErr_NoMemory();
1601 len = index_length(self) - 1;
1595 len = index_length(self) - 1;
1602
1596
1603 for (i = 0; i < argcount; i++) {
1597 for (i = 0; i < argcount; i++) {
1604 static const int capacity = 24;
1598 static const int capacity = 24;
1605 PyObject *obj = PySequence_GetItem(args, i);
1599 PyObject *obj = PySequence_GetItem(args, i);
1606 bitmask x;
1600 bitmask x;
1607 long val;
1601 long val;
1608
1602
1609 if (!PyInt_Check(obj)) {
1603 if (!PyInt_Check(obj)) {
1610 PyErr_SetString(PyExc_TypeError,
1604 PyErr_SetString(PyExc_TypeError,
1611 "arguments must all be ints");
1605 "arguments must all be ints");
1612 Py_DECREF(obj);
1606 Py_DECREF(obj);
1613 goto bail;
1607 goto bail;
1614 }
1608 }
1615 val = PyInt_AsLong(obj);
1609 val = PyInt_AsLong(obj);
1616 Py_DECREF(obj);
1610 Py_DECREF(obj);
1617 if (val == -1) {
1611 if (val == -1) {
1618 ret = PyList_New(0);
1612 ret = PyList_New(0);
1619 goto done;
1613 goto done;
1620 }
1614 }
1621 if (val < 0 || val >= len) {
1615 if (val < 0 || val >= len) {
1622 PyErr_SetString(PyExc_IndexError,
1616 PyErr_SetString(PyExc_IndexError,
1623 "index out of range");
1617 "index out of range");
1624 goto bail;
1618 goto bail;
1625 }
1619 }
1626 /* this cheesy bloom filter lets us avoid some more
1620 /* this cheesy bloom filter lets us avoid some more
1627 * expensive duplicate checks in the common set-is-disjoint
1621 * expensive duplicate checks in the common set-is-disjoint
1628 * case */
1622 * case */
1629 x = 1ull << (val & 0x3f);
1623 x = 1ull << (val & 0x3f);
1630 if (repeat & x) {
1624 if (repeat & x) {
1631 int k;
1625 int k;
1632 for (k = 0; k < revcount; k++) {
1626 for (k = 0; k < revcount; k++) {
1633 if (val == revs[k])
1627 if (val == revs[k])
1634 goto duplicate;
1628 goto duplicate;
1635 }
1629 }
1636 }
1630 }
1637 else repeat |= x;
1631 else repeat |= x;
1638 if (revcount >= capacity) {
1632 if (revcount >= capacity) {
1639 PyErr_Format(PyExc_OverflowError,
1633 PyErr_Format(PyExc_OverflowError,
1640 "bitset size (%d) > capacity (%d)",
1634 "bitset size (%d) > capacity (%d)",
1641 revcount, capacity);
1635 revcount, capacity);
1642 goto bail;
1636 goto bail;
1643 }
1637 }
1644 revs[revcount++] = (int)val;
1638 revs[revcount++] = (int)val;
1645 duplicate:;
1639 duplicate:;
1646 }
1640 }
1647
1641
1648 if (revcount == 0) {
1642 if (revcount == 0) {
1649 ret = PyList_New(0);
1643 ret = PyList_New(0);
1650 goto done;
1644 goto done;
1651 }
1645 }
1652 if (revcount == 1) {
1646 if (revcount == 1) {
1653 PyObject *obj;
1647 PyObject *obj;
1654 ret = PyList_New(1);
1648 ret = PyList_New(1);
1655 if (ret == NULL)
1649 if (ret == NULL)
1656 goto bail;
1650 goto bail;
1657 obj = PyInt_FromLong(revs[0]);
1651 obj = PyInt_FromLong(revs[0]);
1658 if (obj == NULL)
1652 if (obj == NULL)
1659 goto bail;
1653 goto bail;
1660 PyList_SET_ITEM(ret, 0, obj);
1654 PyList_SET_ITEM(ret, 0, obj);
1661 goto done;
1655 goto done;
1662 }
1656 }
1663
1657
1664 ret = find_gca_candidates(self, revs, revcount);
1658 ret = find_gca_candidates(self, revs, revcount);
1665 if (ret == NULL)
1659 if (ret == NULL)
1666 goto bail;
1660 goto bail;
1667
1661
1668 done:
1662 done:
1669 PyMem_Free(revs);
1663 PyMem_Free(revs);
1670 return ret;
1664 return ret;
1671
1665
1672 bail:
1666 bail:
1673 PyMem_Free(revs);
1667 PyMem_Free(revs);
1674 Py_XDECREF(ret);
1668 Py_XDECREF(ret);
1675 return NULL;
1669 return NULL;
1676 }
1670 }
1677
1671
1678 /*
1672 /*
1679 * Given a (possibly overlapping) set of revs, return the greatest
1673 * Given a (possibly overlapping) set of revs, return the greatest
1680 * common ancestors: those with the longest path to the root.
1674 * common ancestors: those with the longest path to the root.
1681 */
1675 */
1682 static PyObject *index_ancestors(indexObject *self, PyObject *args)
1676 static PyObject *index_ancestors(indexObject *self, PyObject *args)
1683 {
1677 {
1684 PyObject *ret;
1678 PyObject *ret;
1685 PyObject *gca = index_commonancestorsheads(self, args);
1679 PyObject *gca = index_commonancestorsheads(self, args);
1686 if (gca == NULL)
1680 if (gca == NULL)
1687 return NULL;
1681 return NULL;
1688
1682
1689 if (PyList_GET_SIZE(gca) <= 1) {
1683 if (PyList_GET_SIZE(gca) <= 1) {
1690 return gca;
1684 return gca;
1691 }
1685 }
1692
1686
1693 ret = find_deepest(self, gca);
1687 ret = find_deepest(self, gca);
1694 Py_DECREF(gca);
1688 Py_DECREF(gca);
1695 return ret;
1689 return ret;
1696 }
1690 }
1697
1691
1698 /*
1692 /*
1699 * Invalidate any trie entries introduced by added revs.
1693 * Invalidate any trie entries introduced by added revs.
1700 */
1694 */
1701 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
1695 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
1702 {
1696 {
1703 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
1697 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
1704
1698
1705 for (i = start; i < len; i++) {
1699 for (i = start; i < len; i++) {
1706 PyObject *tuple = PyList_GET_ITEM(self->added, i);
1700 PyObject *tuple = PyList_GET_ITEM(self->added, i);
1707 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
1701 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
1708
1702
1709 nt_insert(self, PyBytes_AS_STRING(node), -1);
1703 nt_insert(self, PyBytes_AS_STRING(node), -1);
1710 }
1704 }
1711
1705
1712 if (start == 0)
1706 if (start == 0)
1713 Py_CLEAR(self->added);
1707 Py_CLEAR(self->added);
1714 }
1708 }
1715
1709
1716 /*
1710 /*
1717 * Delete a numeric range of revs, which must be at the end of the
1711 * Delete a numeric range of revs, which must be at the end of the
1718 * range, but exclude the sentinel nullid entry.
1712 * range, but exclude the sentinel nullid entry.
1719 */
1713 */
1720 static int index_slice_del(indexObject *self, PyObject *item)
1714 static int index_slice_del(indexObject *self, PyObject *item)
1721 {
1715 {
1722 Py_ssize_t start, stop, step, slicelength;
1716 Py_ssize_t start, stop, step, slicelength;
1723 Py_ssize_t length = index_length(self);
1717 Py_ssize_t length = index_length(self);
1724 int ret = 0;
1718 int ret = 0;
1725
1719
1726 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
1720 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
1727 #ifdef IS_PY3K
1721 #ifdef IS_PY3K
1728 if (PySlice_GetIndicesEx(item, length,
1722 if (PySlice_GetIndicesEx(item, length,
1729 #else
1723 #else
1730 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
1724 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
1731 #endif
1725 #endif
1732 &start, &stop, &step, &slicelength) < 0)
1726 &start, &stop, &step, &slicelength) < 0)
1733 return -1;
1727 return -1;
1734
1728
1735 if (slicelength <= 0)
1729 if (slicelength <= 0)
1736 return 0;
1730 return 0;
1737
1731
1738 if ((step < 0 && start < stop) || (step > 0 && start > stop))
1732 if ((step < 0 && start < stop) || (step > 0 && start > stop))
1739 stop = start;
1733 stop = start;
1740
1734
1741 if (step < 0) {
1735 if (step < 0) {
1742 stop = start + 1;
1736 stop = start + 1;
1743 start = stop + step*(slicelength - 1) - 1;
1737 start = stop + step*(slicelength - 1) - 1;
1744 step = -step;
1738 step = -step;
1745 }
1739 }
1746
1740
1747 if (step != 1) {
1741 if (step != 1) {
1748 PyErr_SetString(PyExc_ValueError,
1742 PyErr_SetString(PyExc_ValueError,
1749 "revlog index delete requires step size of 1");
1743 "revlog index delete requires step size of 1");
1750 return -1;
1744 return -1;
1751 }
1745 }
1752
1746
1753 if (stop != length - 1) {
1747 if (stop != length - 1) {
1754 PyErr_SetString(PyExc_IndexError,
1748 PyErr_SetString(PyExc_IndexError,
1755 "revlog index deletion indices are invalid");
1749 "revlog index deletion indices are invalid");
1756 return -1;
1750 return -1;
1757 }
1751 }
1758
1752
1759 if (start < self->length - 1) {
1753 if (start < self->length - 1) {
1760 if (self->nt) {
1754 if (self->nt) {
1761 Py_ssize_t i;
1755 Py_ssize_t i;
1762
1756
1763 for (i = start + 1; i < self->length - 1; i++) {
1757 for (i = start + 1; i < self->length - 1; i++) {
1764 const char *node = index_node(self, i);
1758 const char *node = index_node(self, i);
1765
1759
1766 if (node)
1760 if (node)
1767 nt_insert(self, node, -1);
1761 nt_insert(self, node, -1);
1768 }
1762 }
1769 if (self->added)
1763 if (self->added)
1770 nt_invalidate_added(self, 0);
1764 nt_invalidate_added(self, 0);
1771 if (self->ntrev > start)
1765 if (self->ntrev > start)
1772 self->ntrev = (int)start;
1766 self->ntrev = (int)start;
1773 }
1767 }
1774 self->length = start + 1;
1768 self->length = start + 1;
1775 if (start < self->raw_length) {
1769 if (start < self->raw_length) {
1776 if (self->cache) {
1770 if (self->cache) {
1777 Py_ssize_t i;
1771 Py_ssize_t i;
1778 for (i = start; i < self->raw_length; i++)
1772 for (i = start; i < self->raw_length; i++)
1779 Py_CLEAR(self->cache[i]);
1773 Py_CLEAR(self->cache[i]);
1780 }
1774 }
1781 self->raw_length = start;
1775 self->raw_length = start;
1782 }
1776 }
1783 goto done;
1777 goto done;
1784 }
1778 }
1785
1779
1786 if (self->nt) {
1780 if (self->nt) {
1787 nt_invalidate_added(self, start - self->length + 1);
1781 nt_invalidate_added(self, start - self->length + 1);
1788 if (self->ntrev > start)
1782 if (self->ntrev > start)
1789 self->ntrev = (int)start;
1783 self->ntrev = (int)start;
1790 }
1784 }
1791 if (self->added)
1785 if (self->added)
1792 ret = PyList_SetSlice(self->added, start - self->length + 1,
1786 ret = PyList_SetSlice(self->added, start - self->length + 1,
1793 PyList_GET_SIZE(self->added), NULL);
1787 PyList_GET_SIZE(self->added), NULL);
1794 done:
1788 done:
1795 Py_CLEAR(self->headrevs);
1789 Py_CLEAR(self->headrevs);
1796 return ret;
1790 return ret;
1797 }
1791 }
1798
1792
1799 /*
1793 /*
1800 * Supported ops:
1794 * Supported ops:
1801 *
1795 *
1802 * slice deletion
1796 * slice deletion
1803 * string assignment (extend node->rev mapping)
1797 * string assignment (extend node->rev mapping)
1804 * string deletion (shrink node->rev mapping)
1798 * string deletion (shrink node->rev mapping)
1805 */
1799 */
1806 static int index_assign_subscript(indexObject *self, PyObject *item,
1800 static int index_assign_subscript(indexObject *self, PyObject *item,
1807 PyObject *value)
1801 PyObject *value)
1808 {
1802 {
1809 char *node;
1803 char *node;
1810 Py_ssize_t nodelen;
1804 Py_ssize_t nodelen;
1811 long rev;
1805 long rev;
1812
1806
1813 if (PySlice_Check(item) && value == NULL)
1807 if (PySlice_Check(item) && value == NULL)
1814 return index_slice_del(self, item);
1808 return index_slice_del(self, item);
1815
1809
1816 if (node_check(item, &node, &nodelen) == -1)
1810 if (node_check(item, &node, &nodelen) == -1)
1817 return -1;
1811 return -1;
1818
1812
1819 if (value == NULL)
1813 if (value == NULL)
1820 return self->nt ? nt_insert(self, node, -1) : 0;
1814 return self->nt ? nt_insert(self, node, -1) : 0;
1821 rev = PyInt_AsLong(value);
1815 rev = PyInt_AsLong(value);
1822 if (rev > INT_MAX || rev < 0) {
1816 if (rev > INT_MAX || rev < 0) {
1823 if (!PyErr_Occurred())
1817 if (!PyErr_Occurred())
1824 PyErr_SetString(PyExc_ValueError, "rev out of range");
1818 PyErr_SetString(PyExc_ValueError, "rev out of range");
1825 return -1;
1819 return -1;
1826 }
1820 }
1827
1821
1828 if (nt_init(self) == -1)
1822 if (nt_init(self) == -1)
1829 return -1;
1823 return -1;
1830 return nt_insert(self, node, (int)rev);
1824 return nt_insert(self, node, (int)rev);
1831 }
1825 }
1832
1826
1833 /*
1827 /*
1834 * Find all RevlogNG entries in an index that has inline data. Update
1828 * Find all RevlogNG entries in an index that has inline data. Update
1835 * the optional "offsets" table with those entries.
1829 * the optional "offsets" table with those entries.
1836 */
1830 */
1837 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
1831 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
1838 {
1832 {
1839 const char *data = (const char *)self->buf.buf;
1833 const char *data = (const char *)self->buf.buf;
1840 Py_ssize_t pos = 0;
1834 Py_ssize_t pos = 0;
1841 Py_ssize_t end = self->buf.len;
1835 Py_ssize_t end = self->buf.len;
1842 long incr = v1_hdrsize;
1836 long incr = v1_hdrsize;
1843 Py_ssize_t len = 0;
1837 Py_ssize_t len = 0;
1844
1838
1845 while (pos + v1_hdrsize <= end && pos >= 0) {
1839 while (pos + v1_hdrsize <= end && pos >= 0) {
1846 uint32_t comp_len;
1840 uint32_t comp_len;
1847 /* 3rd element of header is length of compressed inline data */
1841 /* 3rd element of header is length of compressed inline data */
1848 comp_len = getbe32(data + pos + 8);
1842 comp_len = getbe32(data + pos + 8);
1849 incr = v1_hdrsize + comp_len;
1843 incr = v1_hdrsize + comp_len;
1850 if (offsets)
1844 if (offsets)
1851 offsets[len] = data + pos;
1845 offsets[len] = data + pos;
1852 len++;
1846 len++;
1853 pos += incr;
1847 pos += incr;
1854 }
1848 }
1855
1849
1856 if (pos != end) {
1850 if (pos != end) {
1857 if (!PyErr_Occurred())
1851 if (!PyErr_Occurred())
1858 PyErr_SetString(PyExc_ValueError, "corrupt index file");
1852 PyErr_SetString(PyExc_ValueError, "corrupt index file");
1859 return -1;
1853 return -1;
1860 }
1854 }
1861
1855
1862 return len;
1856 return len;
1863 }
1857 }
1864
1858
1865 static int index_init(indexObject *self, PyObject *args)
1859 static int index_init(indexObject *self, PyObject *args)
1866 {
1860 {
1867 PyObject *data_obj, *inlined_obj;
1861 PyObject *data_obj, *inlined_obj;
1868 Py_ssize_t size;
1862 Py_ssize_t size;
1869
1863
1870 /* Initialize before argument-checking to avoid index_dealloc() crash. */
1864 /* Initialize before argument-checking to avoid index_dealloc() crash. */
1871 self->raw_length = 0;
1865 self->raw_length = 0;
1872 self->added = NULL;
1866 self->added = NULL;
1873 self->cache = NULL;
1867 self->cache = NULL;
1874 self->data = NULL;
1868 self->data = NULL;
1875 memset(&self->buf, 0, sizeof(self->buf));
1869 memset(&self->buf, 0, sizeof(self->buf));
1876 self->headrevs = NULL;
1870 self->headrevs = NULL;
1877 self->filteredrevs = Py_None;
1871 self->filteredrevs = Py_None;
1878 Py_INCREF(Py_None);
1872 Py_INCREF(Py_None);
1879 self->nt = NULL;
1873 self->nt = NULL;
1880 self->offsets = NULL;
1874 self->offsets = NULL;
1881
1875
1882 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
1876 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
1883 return -1;
1877 return -1;
1884 if (!PyObject_CheckBuffer(data_obj)) {
1878 if (!PyObject_CheckBuffer(data_obj)) {
1885 PyErr_SetString(PyExc_TypeError,
1879 PyErr_SetString(PyExc_TypeError,
1886 "data does not support buffer interface");
1880 "data does not support buffer interface");
1887 return -1;
1881 return -1;
1888 }
1882 }
1889
1883
1890 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
1884 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
1891 return -1;
1885 return -1;
1892 size = self->buf.len;
1886 size = self->buf.len;
1893
1887
1894 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
1888 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
1895 self->data = data_obj;
1889 self->data = data_obj;
1896
1890
1897 self->ntlength = self->ntcapacity = 0;
1891 self->ntlength = self->ntcapacity = 0;
1898 self->ntdepth = self->ntsplits = 0;
1892 self->ntdepth = self->ntsplits = 0;
1899 self->ntlookups = self->ntmisses = 0;
1893 self->ntlookups = self->ntmisses = 0;
1900 self->ntrev = -1;
1894 self->ntrev = -1;
1901 Py_INCREF(self->data);
1895 Py_INCREF(self->data);
1902
1896
1903 if (self->inlined) {
1897 if (self->inlined) {
1904 Py_ssize_t len = inline_scan(self, NULL);
1898 Py_ssize_t len = inline_scan(self, NULL);
1905 if (len == -1)
1899 if (len == -1)
1906 goto bail;
1900 goto bail;
1907 self->raw_length = len;
1901 self->raw_length = len;
1908 self->length = len + 1;
1902 self->length = len + 1;
1909 } else {
1903 } else {
1910 if (size % v1_hdrsize) {
1904 if (size % v1_hdrsize) {
1911 PyErr_SetString(PyExc_ValueError, "corrupt index file");
1905 PyErr_SetString(PyExc_ValueError, "corrupt index file");
1912 goto bail;
1906 goto bail;
1913 }
1907 }
1914 self->raw_length = size / v1_hdrsize;
1908 self->raw_length = size / v1_hdrsize;
1915 self->length = self->raw_length + 1;
1909 self->length = self->raw_length + 1;
1916 }
1910 }
1917
1911
1918 return 0;
1912 return 0;
1919 bail:
1913 bail:
1920 return -1;
1914 return -1;
1921 }
1915 }
1922
1916
1923 static PyObject *index_nodemap(indexObject *self)
1917 static PyObject *index_nodemap(indexObject *self)
1924 {
1918 {
1925 Py_INCREF(self);
1919 Py_INCREF(self);
1926 return (PyObject *)self;
1920 return (PyObject *)self;
1927 }
1921 }
1928
1922
1929 static void index_dealloc(indexObject *self)
1923 static void index_dealloc(indexObject *self)
1930 {
1924 {
1931 _index_clearcaches(self);
1925 _index_clearcaches(self);
1932 Py_XDECREF(self->filteredrevs);
1926 Py_XDECREF(self->filteredrevs);
1933 if (self->buf.buf) {
1927 if (self->buf.buf) {
1934 PyBuffer_Release(&self->buf);
1928 PyBuffer_Release(&self->buf);
1935 memset(&self->buf, 0, sizeof(self->buf));
1929 memset(&self->buf, 0, sizeof(self->buf));
1936 }
1930 }
1937 Py_XDECREF(self->data);
1931 Py_XDECREF(self->data);
1938 Py_XDECREF(self->added);
1932 Py_XDECREF(self->added);
1939 PyObject_Del(self);
1933 PyObject_Del(self);
1940 }
1934 }
1941
1935
1942 static PySequenceMethods index_sequence_methods = {
1936 static PySequenceMethods index_sequence_methods = {
1943 (lenfunc)index_length, /* sq_length */
1937 (lenfunc)index_length, /* sq_length */
1944 0, /* sq_concat */
1938 0, /* sq_concat */
1945 0, /* sq_repeat */
1939 0, /* sq_repeat */
1946 (ssizeargfunc)index_get, /* sq_item */
1940 (ssizeargfunc)index_get, /* sq_item */
1947 0, /* sq_slice */
1941 0, /* sq_slice */
1948 0, /* sq_ass_item */
1942 0, /* sq_ass_item */
1949 0, /* sq_ass_slice */
1943 0, /* sq_ass_slice */
1950 (objobjproc)index_contains, /* sq_contains */
1944 (objobjproc)index_contains, /* sq_contains */
1951 };
1945 };
1952
1946
1953 static PyMappingMethods index_mapping_methods = {
1947 static PyMappingMethods index_mapping_methods = {
1954 (lenfunc)index_length, /* mp_length */
1948 (lenfunc)index_length, /* mp_length */
1955 (binaryfunc)index_getitem, /* mp_subscript */
1949 (binaryfunc)index_getitem, /* mp_subscript */
1956 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
1950 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
1957 };
1951 };
1958
1952
1959 static PyMethodDef index_methods[] = {
1953 static PyMethodDef index_methods[] = {
1960 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
1954 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
1961 "return the gca set of the given revs"},
1955 "return the gca set of the given revs"},
1962 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
1956 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
1963 METH_VARARGS,
1957 METH_VARARGS,
1964 "return the heads of the common ancestors of the given revs"},
1958 "return the heads of the common ancestors of the given revs"},
1965 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
1959 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
1966 "clear the index caches"},
1960 "clear the index caches"},
1967 {"get", (PyCFunction)index_m_get, METH_VARARGS,
1961 {"get", (PyCFunction)index_m_get, METH_VARARGS,
1968 "get an index entry"},
1962 "get an index entry"},
1969 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
1963 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
1970 METH_VARARGS, "compute phases"},
1964 METH_VARARGS, "compute phases"},
1971 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
1965 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
1972 "reachableroots"},
1966 "reachableroots"},
1973 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
1967 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
1974 "get head revisions"}, /* Can do filtering since 3.2 */
1968 "get head revisions"}, /* Can do filtering since 3.2 */
1975 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
1969 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
1976 "get filtered head revisions"}, /* Can always do filtering */
1970 "get filtered head revisions"}, /* Can always do filtering */
1977 {"deltachain", (PyCFunction)index_deltachain, METH_VARARGS,
1971 {"deltachain", (PyCFunction)index_deltachain, METH_VARARGS,
1978 "determine revisions with deltas to reconstruct fulltext"},
1972 "determine revisions with deltas to reconstruct fulltext"},
1979 {"insert", (PyCFunction)index_insert, METH_VARARGS,
1973 {"insert", (PyCFunction)index_insert, METH_VARARGS,
1980 "insert an index entry"},
1974 "insert an index entry"},
1981 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
1975 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
1982 "match a potentially ambiguous node ID"},
1976 "match a potentially ambiguous node ID"},
1983 {"stats", (PyCFunction)index_stats, METH_NOARGS,
1977 {"stats", (PyCFunction)index_stats, METH_NOARGS,
1984 "stats for the index"},
1978 "stats for the index"},
1985 {NULL} /* Sentinel */
1979 {NULL} /* Sentinel */
1986 };
1980 };
1987
1981
1988 static PyGetSetDef index_getset[] = {
1982 static PyGetSetDef index_getset[] = {
1989 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
1983 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
1990 {NULL} /* Sentinel */
1984 {NULL} /* Sentinel */
1991 };
1985 };
1992
1986
1993 static PyTypeObject indexType = {
1987 static PyTypeObject indexType = {
1994 PyVarObject_HEAD_INIT(NULL, 0) /* header */
1988 PyVarObject_HEAD_INIT(NULL, 0) /* header */
1995 "parsers.index", /* tp_name */
1989 "parsers.index", /* tp_name */
1996 sizeof(indexObject), /* tp_basicsize */
1990 sizeof(indexObject), /* tp_basicsize */
1997 0, /* tp_itemsize */
1991 0, /* tp_itemsize */
1998 (destructor)index_dealloc, /* tp_dealloc */
1992 (destructor)index_dealloc, /* tp_dealloc */
1999 0, /* tp_print */
1993 0, /* tp_print */
2000 0, /* tp_getattr */
1994 0, /* tp_getattr */
2001 0, /* tp_setattr */
1995 0, /* tp_setattr */
2002 0, /* tp_compare */
1996 0, /* tp_compare */
2003 0, /* tp_repr */
1997 0, /* tp_repr */
2004 0, /* tp_as_number */
1998 0, /* tp_as_number */
2005 &index_sequence_methods, /* tp_as_sequence */
1999 &index_sequence_methods, /* tp_as_sequence */
2006 &index_mapping_methods, /* tp_as_mapping */
2000 &index_mapping_methods, /* tp_as_mapping */
2007 0, /* tp_hash */
2001 0, /* tp_hash */
2008 0, /* tp_call */
2002 0, /* tp_call */
2009 0, /* tp_str */
2003 0, /* tp_str */
2010 0, /* tp_getattro */
2004 0, /* tp_getattro */
2011 0, /* tp_setattro */
2005 0, /* tp_setattro */
2012 0, /* tp_as_buffer */
2006 0, /* tp_as_buffer */
2013 Py_TPFLAGS_DEFAULT, /* tp_flags */
2007 Py_TPFLAGS_DEFAULT, /* tp_flags */
2014 "revlog index", /* tp_doc */
2008 "revlog index", /* tp_doc */
2015 0, /* tp_traverse */
2009 0, /* tp_traverse */
2016 0, /* tp_clear */
2010 0, /* tp_clear */
2017 0, /* tp_richcompare */
2011 0, /* tp_richcompare */
2018 0, /* tp_weaklistoffset */
2012 0, /* tp_weaklistoffset */
2019 0, /* tp_iter */
2013 0, /* tp_iter */
2020 0, /* tp_iternext */
2014 0, /* tp_iternext */
2021 index_methods, /* tp_methods */
2015 index_methods, /* tp_methods */
2022 0, /* tp_members */
2016 0, /* tp_members */
2023 index_getset, /* tp_getset */
2017 index_getset, /* tp_getset */
2024 0, /* tp_base */
2018 0, /* tp_base */
2025 0, /* tp_dict */
2019 0, /* tp_dict */
2026 0, /* tp_descr_get */
2020 0, /* tp_descr_get */
2027 0, /* tp_descr_set */
2021 0, /* tp_descr_set */
2028 0, /* tp_dictoffset */
2022 0, /* tp_dictoffset */
2029 (initproc)index_init, /* tp_init */
2023 (initproc)index_init, /* tp_init */
2030 0, /* tp_alloc */
2024 0, /* tp_alloc */
2031 };
2025 };
2032
2026
2033 /*
2027 /*
2034 * returns a tuple of the form (index, index, cache) with elements as
2028 * returns a tuple of the form (index, index, cache) with elements as
2035 * follows:
2029 * follows:
2036 *
2030 *
2037 * index: an index object that lazily parses RevlogNG records
2031 * index: an index object that lazily parses RevlogNG records
2038 * cache: if data is inlined, a tuple (0, index_file_content), else None
2032 * cache: if data is inlined, a tuple (0, index_file_content), else None
2039 * index_file_content could be a string, or a buffer
2033 * index_file_content could be a string, or a buffer
2040 *
2034 *
2041 * added complications are for backwards compatibility
2035 * added complications are for backwards compatibility
2042 */
2036 */
2043 PyObject *parse_index2(PyObject *self, PyObject *args)
2037 PyObject *parse_index2(PyObject *self, PyObject *args)
2044 {
2038 {
2045 PyObject *tuple = NULL, *cache = NULL;
2039 PyObject *tuple = NULL, *cache = NULL;
2046 indexObject *idx;
2040 indexObject *idx;
2047 int ret;
2041 int ret;
2048
2042
2049 idx = PyObject_New(indexObject, &indexType);
2043 idx = PyObject_New(indexObject, &indexType);
2050 if (idx == NULL)
2044 if (idx == NULL)
2051 goto bail;
2045 goto bail;
2052
2046
2053 ret = index_init(idx, args);
2047 ret = index_init(idx, args);
2054 if (ret == -1)
2048 if (ret == -1)
2055 goto bail;
2049 goto bail;
2056
2050
2057 if (idx->inlined) {
2051 if (idx->inlined) {
2058 cache = Py_BuildValue("iO", 0, idx->data);
2052 cache = Py_BuildValue("iO", 0, idx->data);
2059 if (cache == NULL)
2053 if (cache == NULL)
2060 goto bail;
2054 goto bail;
2061 } else {
2055 } else {
2062 cache = Py_None;
2056 cache = Py_None;
2063 Py_INCREF(cache);
2057 Py_INCREF(cache);
2064 }
2058 }
2065
2059
2066 tuple = Py_BuildValue("NN", idx, cache);
2060 tuple = Py_BuildValue("NN", idx, cache);
2067 if (!tuple)
2061 if (!tuple)
2068 goto bail;
2062 goto bail;
2069 return tuple;
2063 return tuple;
2070
2064
2071 bail:
2065 bail:
2072 Py_XDECREF(idx);
2066 Py_XDECREF(idx);
2073 Py_XDECREF(cache);
2067 Py_XDECREF(cache);
2074 Py_XDECREF(tuple);
2068 Py_XDECREF(tuple);
2075 return NULL;
2069 return NULL;
2076 }
2070 }
2077
2071
2078 void revlog_module_init(PyObject *mod)
2072 void revlog_module_init(PyObject *mod)
2079 {
2073 {
2080 indexType.tp_new = PyType_GenericNew;
2074 indexType.tp_new = PyType_GenericNew;
2081 if (PyType_Ready(&indexType) < 0)
2075 if (PyType_Ready(&indexType) < 0)
2082 return;
2076 return;
2083 Py_INCREF(&indexType);
2077 Py_INCREF(&indexType);
2084 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2078 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2085
2079
2086 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2080 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2087 -1, -1, -1, -1, nullid, 20);
2081 -1, -1, -1, -1, nullid, 20);
2088 if (nullentry)
2082 if (nullentry)
2089 PyObject_GC_UnTrack(nullentry);
2083 PyObject_GC_UnTrack(nullentry);
2090 }
2084 }
@@ -1,2274 +1,2274
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import inspect
12 import inspect
13 import os
13 import os
14 import random
14 import random
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 hex,
20 hex,
21 nullid,
21 nullid,
22 short,
22 short,
23 )
23 )
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 branchmap,
26 branchmap,
27 bundle2,
27 bundle2,
28 changegroup,
28 changegroup,
29 changelog,
29 changelog,
30 color,
30 color,
31 context,
31 context,
32 dirstate,
32 dirstate,
33 dirstateguard,
33 dirstateguard,
34 discovery,
34 discovery,
35 encoding,
35 encoding,
36 error,
36 error,
37 exchange,
37 exchange,
38 extensions,
38 extensions,
39 filelog,
39 filelog,
40 hook,
40 hook,
41 lock as lockmod,
41 lock as lockmod,
42 manifest,
42 manifest,
43 match as matchmod,
43 match as matchmod,
44 merge as mergemod,
44 merge as mergemod,
45 mergeutil,
45 mergeutil,
46 namespaces,
46 namespaces,
47 obsolete,
47 obsolete,
48 pathutil,
48 pathutil,
49 peer,
49 peer,
50 phases,
50 phases,
51 pushkey,
51 pushkey,
52 pycompat,
52 pycompat,
53 repository,
53 repository,
54 repoview,
54 repoview,
55 revset,
55 revset,
56 revsetlang,
56 revsetlang,
57 scmutil,
57 scmutil,
58 sparse,
58 sparse,
59 store,
59 store,
60 subrepo,
60 subrepo,
61 tags as tagsmod,
61 tags as tagsmod,
62 transaction,
62 transaction,
63 txnutil,
63 txnutil,
64 util,
64 util,
65 vfs as vfsmod,
65 vfs as vfsmod,
66 )
66 )
67
67
68 release = lockmod.release
68 release = lockmod.release
69 urlerr = util.urlerr
69 urlerr = util.urlerr
70 urlreq = util.urlreq
70 urlreq = util.urlreq
71
71
72 # set of (path, vfs-location) tuples. vfs-location is:
72 # set of (path, vfs-location) tuples. vfs-location is:
73 # - 'plain for vfs relative paths
73 # - 'plain for vfs relative paths
74 # - '' for svfs relative paths
74 # - '' for svfs relative paths
75 _cachedfiles = set()
75 _cachedfiles = set()
76
76
77 class _basefilecache(scmutil.filecache):
77 class _basefilecache(scmutil.filecache):
78 """All filecache usage on repo are done for logic that should be unfiltered
78 """All filecache usage on repo are done for logic that should be unfiltered
79 """
79 """
80 def __get__(self, repo, type=None):
80 def __get__(self, repo, type=None):
81 if repo is None:
81 if repo is None:
82 return self
82 return self
83 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
83 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
84 def __set__(self, repo, value):
84 def __set__(self, repo, value):
85 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
85 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
86 def __delete__(self, repo):
86 def __delete__(self, repo):
87 return super(_basefilecache, self).__delete__(repo.unfiltered())
87 return super(_basefilecache, self).__delete__(repo.unfiltered())
88
88
89 class repofilecache(_basefilecache):
89 class repofilecache(_basefilecache):
90 """filecache for files in .hg but outside of .hg/store"""
90 """filecache for files in .hg but outside of .hg/store"""
91 def __init__(self, *paths):
91 def __init__(self, *paths):
92 super(repofilecache, self).__init__(*paths)
92 super(repofilecache, self).__init__(*paths)
93 for path in paths:
93 for path in paths:
94 _cachedfiles.add((path, 'plain'))
94 _cachedfiles.add((path, 'plain'))
95
95
96 def join(self, obj, fname):
96 def join(self, obj, fname):
97 return obj.vfs.join(fname)
97 return obj.vfs.join(fname)
98
98
99 class storecache(_basefilecache):
99 class storecache(_basefilecache):
100 """filecache for files in the store"""
100 """filecache for files in the store"""
101 def __init__(self, *paths):
101 def __init__(self, *paths):
102 super(storecache, self).__init__(*paths)
102 super(storecache, self).__init__(*paths)
103 for path in paths:
103 for path in paths:
104 _cachedfiles.add((path, ''))
104 _cachedfiles.add((path, ''))
105
105
106 def join(self, obj, fname):
106 def join(self, obj, fname):
107 return obj.sjoin(fname)
107 return obj.sjoin(fname)
108
108
109 def isfilecached(repo, name):
109 def isfilecached(repo, name):
110 """check if a repo has already cached "name" filecache-ed property
110 """check if a repo has already cached "name" filecache-ed property
111
111
112 This returns (cachedobj-or-None, iscached) tuple.
112 This returns (cachedobj-or-None, iscached) tuple.
113 """
113 """
114 cacheentry = repo.unfiltered()._filecache.get(name, None)
114 cacheentry = repo.unfiltered()._filecache.get(name, None)
115 if not cacheentry:
115 if not cacheentry:
116 return None, False
116 return None, False
117 return cacheentry.obj, True
117 return cacheentry.obj, True
118
118
119 class unfilteredpropertycache(util.propertycache):
119 class unfilteredpropertycache(util.propertycache):
120 """propertycache that apply to unfiltered repo only"""
120 """propertycache that apply to unfiltered repo only"""
121
121
122 def __get__(self, repo, type=None):
122 def __get__(self, repo, type=None):
123 unfi = repo.unfiltered()
123 unfi = repo.unfiltered()
124 if unfi is repo:
124 if unfi is repo:
125 return super(unfilteredpropertycache, self).__get__(unfi)
125 return super(unfilteredpropertycache, self).__get__(unfi)
126 return getattr(unfi, self.name)
126 return getattr(unfi, self.name)
127
127
128 class filteredpropertycache(util.propertycache):
128 class filteredpropertycache(util.propertycache):
129 """propertycache that must take filtering in account"""
129 """propertycache that must take filtering in account"""
130
130
131 def cachevalue(self, obj, value):
131 def cachevalue(self, obj, value):
132 object.__setattr__(obj, self.name, value)
132 object.__setattr__(obj, self.name, value)
133
133
134
134
135 def hasunfilteredcache(repo, name):
135 def hasunfilteredcache(repo, name):
136 """check if a repo has an unfilteredpropertycache value for <name>"""
136 """check if a repo has an unfilteredpropertycache value for <name>"""
137 return name in vars(repo.unfiltered())
137 return name in vars(repo.unfiltered())
138
138
139 def unfilteredmethod(orig):
139 def unfilteredmethod(orig):
140 """decorate method that always need to be run on unfiltered version"""
140 """decorate method that always need to be run on unfiltered version"""
141 def wrapper(repo, *args, **kwargs):
141 def wrapper(repo, *args, **kwargs):
142 return orig(repo.unfiltered(), *args, **kwargs)
142 return orig(repo.unfiltered(), *args, **kwargs)
143 return wrapper
143 return wrapper
144
144
145 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
145 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
146 'unbundle'}
146 'unbundle'}
147 legacycaps = moderncaps.union({'changegroupsubset'})
147 legacycaps = moderncaps.union({'changegroupsubset'})
148
148
149 class localpeer(repository.peer):
149 class localpeer(repository.peer):
150 '''peer for a local repo; reflects only the most recent API'''
150 '''peer for a local repo; reflects only the most recent API'''
151
151
152 def __init__(self, repo, caps=None):
152 def __init__(self, repo, caps=None):
153 super(localpeer, self).__init__()
153 super(localpeer, self).__init__()
154
154
155 if caps is None:
155 if caps is None:
156 caps = moderncaps.copy()
156 caps = moderncaps.copy()
157 self._repo = repo.filtered('served')
157 self._repo = repo.filtered('served')
158 self._ui = repo.ui
158 self._ui = repo.ui
159 self._caps = repo._restrictcapabilities(caps)
159 self._caps = repo._restrictcapabilities(caps)
160
160
161 # Begin of _basepeer interface.
161 # Begin of _basepeer interface.
162
162
163 @util.propertycache
163 @util.propertycache
164 def ui(self):
164 def ui(self):
165 return self._ui
165 return self._ui
166
166
167 def url(self):
167 def url(self):
168 return self._repo.url()
168 return self._repo.url()
169
169
170 def local(self):
170 def local(self):
171 return self._repo
171 return self._repo
172
172
173 def peer(self):
173 def peer(self):
174 return self
174 return self
175
175
176 def canpush(self):
176 def canpush(self):
177 return True
177 return True
178
178
179 def close(self):
179 def close(self):
180 self._repo.close()
180 self._repo.close()
181
181
182 # End of _basepeer interface.
182 # End of _basepeer interface.
183
183
184 # Begin of _basewirecommands interface.
184 # Begin of _basewirecommands interface.
185
185
186 def branchmap(self):
186 def branchmap(self):
187 return self._repo.branchmap()
187 return self._repo.branchmap()
188
188
189 def capabilities(self):
189 def capabilities(self):
190 return self._caps
190 return self._caps
191
191
192 def debugwireargs(self, one, two, three=None, four=None, five=None):
192 def debugwireargs(self, one, two, three=None, four=None, five=None):
193 """Used to test argument passing over the wire"""
193 """Used to test argument passing over the wire"""
194 return "%s %s %s %s %s" % (one, two, three, four, five)
194 return "%s %s %s %s %s" % (one, two, three, four, five)
195
195
196 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
196 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
197 **kwargs):
197 **kwargs):
198 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
198 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
199 common=common, bundlecaps=bundlecaps,
199 common=common, bundlecaps=bundlecaps,
200 **kwargs)
200 **kwargs)
201 cb = util.chunkbuffer(chunks)
201 cb = util.chunkbuffer(chunks)
202
202
203 if exchange.bundle2requested(bundlecaps):
203 if exchange.bundle2requested(bundlecaps):
204 # When requesting a bundle2, getbundle returns a stream to make the
204 # When requesting a bundle2, getbundle returns a stream to make the
205 # wire level function happier. We need to build a proper object
205 # wire level function happier. We need to build a proper object
206 # from it in local peer.
206 # from it in local peer.
207 return bundle2.getunbundler(self.ui, cb)
207 return bundle2.getunbundler(self.ui, cb)
208 else:
208 else:
209 return changegroup.getunbundler('01', cb, None)
209 return changegroup.getunbundler('01', cb, None)
210
210
211 def heads(self):
211 def heads(self):
212 return self._repo.heads()
212 return self._repo.heads()
213
213
214 def known(self, nodes):
214 def known(self, nodes):
215 return self._repo.known(nodes)
215 return self._repo.known(nodes)
216
216
217 def listkeys(self, namespace):
217 def listkeys(self, namespace):
218 return self._repo.listkeys(namespace)
218 return self._repo.listkeys(namespace)
219
219
220 def lookup(self, key):
220 def lookup(self, key):
221 return self._repo.lookup(key)
221 return self._repo.lookup(key)
222
222
223 def pushkey(self, namespace, key, old, new):
223 def pushkey(self, namespace, key, old, new):
224 return self._repo.pushkey(namespace, key, old, new)
224 return self._repo.pushkey(namespace, key, old, new)
225
225
226 def stream_out(self):
226 def stream_out(self):
227 raise error.Abort(_('cannot perform stream clone against local '
227 raise error.Abort(_('cannot perform stream clone against local '
228 'peer'))
228 'peer'))
229
229
230 def unbundle(self, cg, heads, url):
230 def unbundle(self, cg, heads, url):
231 """apply a bundle on a repo
231 """apply a bundle on a repo
232
232
233 This function handles the repo locking itself."""
233 This function handles the repo locking itself."""
234 try:
234 try:
235 try:
235 try:
236 cg = exchange.readbundle(self.ui, cg, None)
236 cg = exchange.readbundle(self.ui, cg, None)
237 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
237 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
238 if util.safehasattr(ret, 'getchunks'):
238 if util.safehasattr(ret, 'getchunks'):
239 # This is a bundle20 object, turn it into an unbundler.
239 # This is a bundle20 object, turn it into an unbundler.
240 # This little dance should be dropped eventually when the
240 # This little dance should be dropped eventually when the
241 # API is finally improved.
241 # API is finally improved.
242 stream = util.chunkbuffer(ret.getchunks())
242 stream = util.chunkbuffer(ret.getchunks())
243 ret = bundle2.getunbundler(self.ui, stream)
243 ret = bundle2.getunbundler(self.ui, stream)
244 return ret
244 return ret
245 except Exception as exc:
245 except Exception as exc:
246 # If the exception contains output salvaged from a bundle2
246 # If the exception contains output salvaged from a bundle2
247 # reply, we need to make sure it is printed before continuing
247 # reply, we need to make sure it is printed before continuing
248 # to fail. So we build a bundle2 with such output and consume
248 # to fail. So we build a bundle2 with such output and consume
249 # it directly.
249 # it directly.
250 #
250 #
251 # This is not very elegant but allows a "simple" solution for
251 # This is not very elegant but allows a "simple" solution for
252 # issue4594
252 # issue4594
253 output = getattr(exc, '_bundle2salvagedoutput', ())
253 output = getattr(exc, '_bundle2salvagedoutput', ())
254 if output:
254 if output:
255 bundler = bundle2.bundle20(self._repo.ui)
255 bundler = bundle2.bundle20(self._repo.ui)
256 for out in output:
256 for out in output:
257 bundler.addpart(out)
257 bundler.addpart(out)
258 stream = util.chunkbuffer(bundler.getchunks())
258 stream = util.chunkbuffer(bundler.getchunks())
259 b = bundle2.getunbundler(self.ui, stream)
259 b = bundle2.getunbundler(self.ui, stream)
260 bundle2.processbundle(self._repo, b)
260 bundle2.processbundle(self._repo, b)
261 raise
261 raise
262 except error.PushRaced as exc:
262 except error.PushRaced as exc:
263 raise error.ResponseError(_('push failed:'), str(exc))
263 raise error.ResponseError(_('push failed:'), str(exc))
264
264
265 # End of _basewirecommands interface.
265 # End of _basewirecommands interface.
266
266
267 # Begin of peer interface.
267 # Begin of peer interface.
268
268
269 def iterbatch(self):
269 def iterbatch(self):
270 return peer.localiterbatcher(self)
270 return peer.localiterbatcher(self)
271
271
272 # End of peer interface.
272 # End of peer interface.
273
273
274 class locallegacypeer(repository.legacypeer, localpeer):
274 class locallegacypeer(repository.legacypeer, localpeer):
275 '''peer extension which implements legacy methods too; used for tests with
275 '''peer extension which implements legacy methods too; used for tests with
276 restricted capabilities'''
276 restricted capabilities'''
277
277
278 def __init__(self, repo):
278 def __init__(self, repo):
279 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
279 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
280
280
281 # Begin of baselegacywirecommands interface.
281 # Begin of baselegacywirecommands interface.
282
282
283 def between(self, pairs):
283 def between(self, pairs):
284 return self._repo.between(pairs)
284 return self._repo.between(pairs)
285
285
286 def branches(self, nodes):
286 def branches(self, nodes):
287 return self._repo.branches(nodes)
287 return self._repo.branches(nodes)
288
288
289 def changegroup(self, basenodes, source):
289 def changegroup(self, basenodes, source):
290 outgoing = discovery.outgoing(self._repo, missingroots=basenodes,
290 outgoing = discovery.outgoing(self._repo, missingroots=basenodes,
291 missingheads=self._repo.heads())
291 missingheads=self._repo.heads())
292 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
292 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
293
293
294 def changegroupsubset(self, bases, heads, source):
294 def changegroupsubset(self, bases, heads, source):
295 outgoing = discovery.outgoing(self._repo, missingroots=bases,
295 outgoing = discovery.outgoing(self._repo, missingroots=bases,
296 missingheads=heads)
296 missingheads=heads)
297 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
297 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
298
298
299 # End of baselegacywirecommands interface.
299 # End of baselegacywirecommands interface.
300
300
301 # Increment the sub-version when the revlog v2 format changes to lock out old
301 # Increment the sub-version when the revlog v2 format changes to lock out old
302 # clients.
302 # clients.
303 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
303 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
304
304
305 class localrepository(object):
305 class localrepository(object):
306
306
307 supportedformats = {
307 supportedformats = {
308 'revlogv1',
308 'revlogv1',
309 'generaldelta',
309 'generaldelta',
310 'treemanifest',
310 'treemanifest',
311 'manifestv2',
311 'manifestv2',
312 REVLOGV2_REQUIREMENT,
312 REVLOGV2_REQUIREMENT,
313 }
313 }
314 _basesupported = supportedformats | {
314 _basesupported = supportedformats | {
315 'store',
315 'store',
316 'fncache',
316 'fncache',
317 'shared',
317 'shared',
318 'relshared',
318 'relshared',
319 'dotencode',
319 'dotencode',
320 'exp-sparse',
320 'exp-sparse',
321 }
321 }
322 openerreqs = {
322 openerreqs = {
323 'revlogv1',
323 'revlogv1',
324 'generaldelta',
324 'generaldelta',
325 'treemanifest',
325 'treemanifest',
326 'manifestv2',
326 'manifestv2',
327 }
327 }
328
328
329 # a list of (ui, featureset) functions.
329 # a list of (ui, featureset) functions.
330 # only functions defined in module of enabled extensions are invoked
330 # only functions defined in module of enabled extensions are invoked
331 featuresetupfuncs = set()
331 featuresetupfuncs = set()
332
332
333 # list of prefix for file which can be written without 'wlock'
333 # list of prefix for file which can be written without 'wlock'
334 # Extensions should extend this list when needed
334 # Extensions should extend this list when needed
335 _wlockfreeprefix = {
335 _wlockfreeprefix = {
336 # We migh consider requiring 'wlock' for the next
336 # We migh consider requiring 'wlock' for the next
337 # two, but pretty much all the existing code assume
337 # two, but pretty much all the existing code assume
338 # wlock is not needed so we keep them excluded for
338 # wlock is not needed so we keep them excluded for
339 # now.
339 # now.
340 'hgrc',
340 'hgrc',
341 'requires',
341 'requires',
342 # XXX cache is a complicatged business someone
342 # XXX cache is a complicatged business someone
343 # should investigate this in depth at some point
343 # should investigate this in depth at some point
344 'cache/',
344 'cache/',
345 # XXX shouldn't be dirstate covered by the wlock?
345 # XXX shouldn't be dirstate covered by the wlock?
346 'dirstate',
346 'dirstate',
347 # XXX bisect was still a bit too messy at the time
347 # XXX bisect was still a bit too messy at the time
348 # this changeset was introduced. Someone should fix
348 # this changeset was introduced. Someone should fix
349 # the remainig bit and drop this line
349 # the remainig bit and drop this line
350 'bisect.state',
350 'bisect.state',
351 }
351 }
352
352
353 def __init__(self, baseui, path, create=False):
353 def __init__(self, baseui, path, create=False):
354 self.requirements = set()
354 self.requirements = set()
355 self.filtername = None
355 self.filtername = None
356 # wvfs: rooted at the repository root, used to access the working copy
356 # wvfs: rooted at the repository root, used to access the working copy
357 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
357 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
358 # vfs: rooted at .hg, used to access repo files outside of .hg/store
358 # vfs: rooted at .hg, used to access repo files outside of .hg/store
359 self.vfs = None
359 self.vfs = None
360 # svfs: usually rooted at .hg/store, used to access repository history
360 # svfs: usually rooted at .hg/store, used to access repository history
361 # If this is a shared repository, this vfs may point to another
361 # If this is a shared repository, this vfs may point to another
362 # repository's .hg/store directory.
362 # repository's .hg/store directory.
363 self.svfs = None
363 self.svfs = None
364 self.root = self.wvfs.base
364 self.root = self.wvfs.base
365 self.path = self.wvfs.join(".hg")
365 self.path = self.wvfs.join(".hg")
366 self.origroot = path
366 self.origroot = path
367 # This is only used by context.workingctx.match in order to
367 # This is only used by context.workingctx.match in order to
368 # detect files in subrepos.
368 # detect files in subrepos.
369 self.auditor = pathutil.pathauditor(
369 self.auditor = pathutil.pathauditor(
370 self.root, callback=self._checknested)
370 self.root, callback=self._checknested)
371 # This is only used by context.basectx.match in order to detect
371 # This is only used by context.basectx.match in order to detect
372 # files in subrepos.
372 # files in subrepos.
373 self.nofsauditor = pathutil.pathauditor(
373 self.nofsauditor = pathutil.pathauditor(
374 self.root, callback=self._checknested, realfs=False, cached=True)
374 self.root, callback=self._checknested, realfs=False, cached=True)
375 self.baseui = baseui
375 self.baseui = baseui
376 self.ui = baseui.copy()
376 self.ui = baseui.copy()
377 self.ui.copy = baseui.copy # prevent copying repo configuration
377 self.ui.copy = baseui.copy # prevent copying repo configuration
378 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
378 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
379 if (self.ui.configbool('devel', 'all-warnings') or
379 if (self.ui.configbool('devel', 'all-warnings') or
380 self.ui.configbool('devel', 'check-locks')):
380 self.ui.configbool('devel', 'check-locks')):
381 self.vfs.audit = self._getvfsward(self.vfs.audit)
381 self.vfs.audit = self._getvfsward(self.vfs.audit)
382 # A list of callback to shape the phase if no data were found.
382 # A list of callback to shape the phase if no data were found.
383 # Callback are in the form: func(repo, roots) --> processed root.
383 # Callback are in the form: func(repo, roots) --> processed root.
384 # This list it to be filled by extension during repo setup
384 # This list it to be filled by extension during repo setup
385 self._phasedefaults = []
385 self._phasedefaults = []
386 try:
386 try:
387 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
387 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
388 self._loadextensions()
388 self._loadextensions()
389 except IOError:
389 except IOError:
390 pass
390 pass
391
391
392 if self.featuresetupfuncs:
392 if self.featuresetupfuncs:
393 self.supported = set(self._basesupported) # use private copy
393 self.supported = set(self._basesupported) # use private copy
394 extmods = set(m.__name__ for n, m
394 extmods = set(m.__name__ for n, m
395 in extensions.extensions(self.ui))
395 in extensions.extensions(self.ui))
396 for setupfunc in self.featuresetupfuncs:
396 for setupfunc in self.featuresetupfuncs:
397 if setupfunc.__module__ in extmods:
397 if setupfunc.__module__ in extmods:
398 setupfunc(self.ui, self.supported)
398 setupfunc(self.ui, self.supported)
399 else:
399 else:
400 self.supported = self._basesupported
400 self.supported = self._basesupported
401 color.setup(self.ui)
401 color.setup(self.ui)
402
402
403 # Add compression engines.
403 # Add compression engines.
404 for name in util.compengines:
404 for name in util.compengines:
405 engine = util.compengines[name]
405 engine = util.compengines[name]
406 if engine.revlogheader():
406 if engine.revlogheader():
407 self.supported.add('exp-compression-%s' % name)
407 self.supported.add('exp-compression-%s' % name)
408
408
409 if not self.vfs.isdir():
409 if not self.vfs.isdir():
410 if create:
410 if create:
411 self.requirements = newreporequirements(self)
411 self.requirements = newreporequirements(self)
412
412
413 if not self.wvfs.exists():
413 if not self.wvfs.exists():
414 self.wvfs.makedirs()
414 self.wvfs.makedirs()
415 self.vfs.makedir(notindexed=True)
415 self.vfs.makedir(notindexed=True)
416
416
417 if 'store' in self.requirements:
417 if 'store' in self.requirements:
418 self.vfs.mkdir("store")
418 self.vfs.mkdir("store")
419
419
420 # create an invalid changelog
420 # create an invalid changelog
421 self.vfs.append(
421 self.vfs.append(
422 "00changelog.i",
422 "00changelog.i",
423 '\0\0\0\2' # represents revlogv2
423 '\0\0\0\2' # represents revlogv2
424 ' dummy changelog to prevent using the old repo layout'
424 ' dummy changelog to prevent using the old repo layout'
425 )
425 )
426 else:
426 else:
427 raise error.RepoError(_("repository %s not found") % path)
427 raise error.RepoError(_("repository %s not found") % path)
428 elif create:
428 elif create:
429 raise error.RepoError(_("repository %s already exists") % path)
429 raise error.RepoError(_("repository %s already exists") % path)
430 else:
430 else:
431 try:
431 try:
432 self.requirements = scmutil.readrequires(
432 self.requirements = scmutil.readrequires(
433 self.vfs, self.supported)
433 self.vfs, self.supported)
434 except IOError as inst:
434 except IOError as inst:
435 if inst.errno != errno.ENOENT:
435 if inst.errno != errno.ENOENT:
436 raise
436 raise
437
437
438 cachepath = self.vfs.join('cache')
438 cachepath = self.vfs.join('cache')
439 self.sharedpath = self.path
439 self.sharedpath = self.path
440 try:
440 try:
441 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
441 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
442 if 'relshared' in self.requirements:
442 if 'relshared' in self.requirements:
443 sharedpath = self.vfs.join(sharedpath)
443 sharedpath = self.vfs.join(sharedpath)
444 vfs = vfsmod.vfs(sharedpath, realpath=True)
444 vfs = vfsmod.vfs(sharedpath, realpath=True)
445 cachepath = vfs.join('cache')
445 cachepath = vfs.join('cache')
446 s = vfs.base
446 s = vfs.base
447 if not vfs.exists():
447 if not vfs.exists():
448 raise error.RepoError(
448 raise error.RepoError(
449 _('.hg/sharedpath points to nonexistent directory %s') % s)
449 _('.hg/sharedpath points to nonexistent directory %s') % s)
450 self.sharedpath = s
450 self.sharedpath = s
451 except IOError as inst:
451 except IOError as inst:
452 if inst.errno != errno.ENOENT:
452 if inst.errno != errno.ENOENT:
453 raise
453 raise
454
454
455 if 'exp-sparse' in self.requirements and not sparse.enabled:
455 if 'exp-sparse' in self.requirements and not sparse.enabled:
456 raise error.RepoError(_('repository is using sparse feature but '
456 raise error.RepoError(_('repository is using sparse feature but '
457 'sparse is not enabled; enable the '
457 'sparse is not enabled; enable the '
458 '"sparse" extensions to access'))
458 '"sparse" extensions to access'))
459
459
460 self.store = store.store(
460 self.store = store.store(
461 self.requirements, self.sharedpath,
461 self.requirements, self.sharedpath,
462 lambda base: vfsmod.vfs(base, cacheaudited=True))
462 lambda base: vfsmod.vfs(base, cacheaudited=True))
463 self.spath = self.store.path
463 self.spath = self.store.path
464 self.svfs = self.store.vfs
464 self.svfs = self.store.vfs
465 self.sjoin = self.store.join
465 self.sjoin = self.store.join
466 self.vfs.createmode = self.store.createmode
466 self.vfs.createmode = self.store.createmode
467 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
467 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
468 self.cachevfs.createmode = self.store.createmode
468 self.cachevfs.createmode = self.store.createmode
469 if (self.ui.configbool('devel', 'all-warnings') or
469 if (self.ui.configbool('devel', 'all-warnings') or
470 self.ui.configbool('devel', 'check-locks')):
470 self.ui.configbool('devel', 'check-locks')):
471 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
471 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
472 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
472 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
473 else: # standard vfs
473 else: # standard vfs
474 self.svfs.audit = self._getsvfsward(self.svfs.audit)
474 self.svfs.audit = self._getsvfsward(self.svfs.audit)
475 self._applyopenerreqs()
475 self._applyopenerreqs()
476 if create:
476 if create:
477 self._writerequirements()
477 self._writerequirements()
478
478
479 self._dirstatevalidatewarned = False
479 self._dirstatevalidatewarned = False
480
480
481 self._branchcaches = {}
481 self._branchcaches = {}
482 self._revbranchcache = None
482 self._revbranchcache = None
483 self.filterpats = {}
483 self.filterpats = {}
484 self._datafilters = {}
484 self._datafilters = {}
485 self._transref = self._lockref = self._wlockref = None
485 self._transref = self._lockref = self._wlockref = None
486
486
487 # A cache for various files under .hg/ that tracks file changes,
487 # A cache for various files under .hg/ that tracks file changes,
488 # (used by the filecache decorator)
488 # (used by the filecache decorator)
489 #
489 #
490 # Maps a property name to its util.filecacheentry
490 # Maps a property name to its util.filecacheentry
491 self._filecache = {}
491 self._filecache = {}
492
492
493 # hold sets of revision to be filtered
493 # hold sets of revision to be filtered
494 # should be cleared when something might have changed the filter value:
494 # should be cleared when something might have changed the filter value:
495 # - new changesets,
495 # - new changesets,
496 # - phase change,
496 # - phase change,
497 # - new obsolescence marker,
497 # - new obsolescence marker,
498 # - working directory parent change,
498 # - working directory parent change,
499 # - bookmark changes
499 # - bookmark changes
500 self.filteredrevcache = {}
500 self.filteredrevcache = {}
501
501
502 # post-dirstate-status hooks
502 # post-dirstate-status hooks
503 self._postdsstatus = []
503 self._postdsstatus = []
504
504
505 # generic mapping between names and nodes
505 # generic mapping between names and nodes
506 self.names = namespaces.namespaces()
506 self.names = namespaces.namespaces()
507
507
508 # Key to signature value.
508 # Key to signature value.
509 self._sparsesignaturecache = {}
509 self._sparsesignaturecache = {}
510 # Signature to cached matcher instance.
510 # Signature to cached matcher instance.
511 self._sparsematchercache = {}
511 self._sparsematchercache = {}
512
512
513 def _getvfsward(self, origfunc):
513 def _getvfsward(self, origfunc):
514 """build a ward for self.vfs"""
514 """build a ward for self.vfs"""
515 rref = weakref.ref(self)
515 rref = weakref.ref(self)
516 def checkvfs(path, mode=None):
516 def checkvfs(path, mode=None):
517 ret = origfunc(path, mode=mode)
517 ret = origfunc(path, mode=mode)
518 repo = rref()
518 repo = rref()
519 if (repo is None
519 if (repo is None
520 or not util.safehasattr(repo, '_wlockref')
520 or not util.safehasattr(repo, '_wlockref')
521 or not util.safehasattr(repo, '_lockref')):
521 or not util.safehasattr(repo, '_lockref')):
522 return
522 return
523 if mode in (None, 'r', 'rb'):
523 if mode in (None, 'r', 'rb'):
524 return
524 return
525 if path.startswith(repo.path):
525 if path.startswith(repo.path):
526 # truncate name relative to the repository (.hg)
526 # truncate name relative to the repository (.hg)
527 path = path[len(repo.path) + 1:]
527 path = path[len(repo.path) + 1:]
528 if path.startswith('cache/'):
528 if path.startswith('cache/'):
529 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
529 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
530 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
530 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
531 if path.startswith('journal.'):
531 if path.startswith('journal.'):
532 # journal is covered by 'lock'
532 # journal is covered by 'lock'
533 if repo._currentlock(repo._lockref) is None:
533 if repo._currentlock(repo._lockref) is None:
534 repo.ui.develwarn('write with no lock: "%s"' % path,
534 repo.ui.develwarn('write with no lock: "%s"' % path,
535 stacklevel=2, config='check-locks')
535 stacklevel=2, config='check-locks')
536 elif repo._currentlock(repo._wlockref) is None:
536 elif repo._currentlock(repo._wlockref) is None:
537 # rest of vfs files are covered by 'wlock'
537 # rest of vfs files are covered by 'wlock'
538 #
538 #
539 # exclude special files
539 # exclude special files
540 for prefix in self._wlockfreeprefix:
540 for prefix in self._wlockfreeprefix:
541 if path.startswith(prefix):
541 if path.startswith(prefix):
542 return
542 return
543 repo.ui.develwarn('write with no wlock: "%s"' % path,
543 repo.ui.develwarn('write with no wlock: "%s"' % path,
544 stacklevel=2, config='check-locks')
544 stacklevel=2, config='check-locks')
545 return ret
545 return ret
546 return checkvfs
546 return checkvfs
547
547
548 def _getsvfsward(self, origfunc):
548 def _getsvfsward(self, origfunc):
549 """build a ward for self.svfs"""
549 """build a ward for self.svfs"""
550 rref = weakref.ref(self)
550 rref = weakref.ref(self)
551 def checksvfs(path, mode=None):
551 def checksvfs(path, mode=None):
552 ret = origfunc(path, mode=mode)
552 ret = origfunc(path, mode=mode)
553 repo = rref()
553 repo = rref()
554 if repo is None or not util.safehasattr(repo, '_lockref'):
554 if repo is None or not util.safehasattr(repo, '_lockref'):
555 return
555 return
556 if mode in (None, 'r', 'rb'):
556 if mode in (None, 'r', 'rb'):
557 return
557 return
558 if path.startswith(repo.sharedpath):
558 if path.startswith(repo.sharedpath):
559 # truncate name relative to the repository (.hg)
559 # truncate name relative to the repository (.hg)
560 path = path[len(repo.sharedpath) + 1:]
560 path = path[len(repo.sharedpath) + 1:]
561 if repo._currentlock(repo._lockref) is None:
561 if repo._currentlock(repo._lockref) is None:
562 repo.ui.develwarn('write with no lock: "%s"' % path,
562 repo.ui.develwarn('write with no lock: "%s"' % path,
563 stacklevel=3)
563 stacklevel=3)
564 return ret
564 return ret
565 return checksvfs
565 return checksvfs
566
566
567 def close(self):
567 def close(self):
568 self._writecaches()
568 self._writecaches()
569
569
570 def _loadextensions(self):
570 def _loadextensions(self):
571 extensions.loadall(self.ui)
571 extensions.loadall(self.ui)
572
572
573 def _writecaches(self):
573 def _writecaches(self):
574 if self._revbranchcache:
574 if self._revbranchcache:
575 self._revbranchcache.write()
575 self._revbranchcache.write()
576
576
577 def _restrictcapabilities(self, caps):
577 def _restrictcapabilities(self, caps):
578 if self.ui.configbool('experimental', 'bundle2-advertise'):
578 if self.ui.configbool('experimental', 'bundle2-advertise'):
579 caps = set(caps)
579 caps = set(caps)
580 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
580 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
581 caps.add('bundle2=' + urlreq.quote(capsblob))
581 caps.add('bundle2=' + urlreq.quote(capsblob))
582 return caps
582 return caps
583
583
584 def _applyopenerreqs(self):
584 def _applyopenerreqs(self):
585 self.svfs.options = dict((r, 1) for r in self.requirements
585 self.svfs.options = dict((r, 1) for r in self.requirements
586 if r in self.openerreqs)
586 if r in self.openerreqs)
587 # experimental config: format.chunkcachesize
587 # experimental config: format.chunkcachesize
588 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
588 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
589 if chunkcachesize is not None:
589 if chunkcachesize is not None:
590 self.svfs.options['chunkcachesize'] = chunkcachesize
590 self.svfs.options['chunkcachesize'] = chunkcachesize
591 # experimental config: format.maxchainlen
591 # experimental config: format.maxchainlen
592 maxchainlen = self.ui.configint('format', 'maxchainlen')
592 maxchainlen = self.ui.configint('format', 'maxchainlen')
593 if maxchainlen is not None:
593 if maxchainlen is not None:
594 self.svfs.options['maxchainlen'] = maxchainlen
594 self.svfs.options['maxchainlen'] = maxchainlen
595 # experimental config: format.manifestcachesize
595 # experimental config: format.manifestcachesize
596 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
596 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
597 if manifestcachesize is not None:
597 if manifestcachesize is not None:
598 self.svfs.options['manifestcachesize'] = manifestcachesize
598 self.svfs.options['manifestcachesize'] = manifestcachesize
599 # experimental config: format.aggressivemergedeltas
599 # experimental config: format.aggressivemergedeltas
600 aggressivemergedeltas = self.ui.configbool('format',
600 aggressivemergedeltas = self.ui.configbool('format',
601 'aggressivemergedeltas')
601 'aggressivemergedeltas')
602 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
602 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
603 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
603 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
604 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
604 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
605 if 0 <= chainspan:
605 if 0 <= chainspan:
606 self.svfs.options['maxdeltachainspan'] = chainspan
606 self.svfs.options['maxdeltachainspan'] = chainspan
607 mmapindexthreshold = self.ui.configbytes('experimental',
607 mmapindexthreshold = self.ui.configbytes('experimental',
608 'mmapindexthreshold')
608 'mmapindexthreshold')
609 if mmapindexthreshold is not None:
609 if mmapindexthreshold is not None:
610 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
610 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
611 withsparseread = self.ui.configbool('experimental', 'sparse-read')
611 withsparseread = self.ui.configbool('experimental', 'sparse-read')
612 srdensitythres = float(self.ui.config('experimental',
612 srdensitythres = float(self.ui.config('experimental',
613 'sparse-read.density-threshold'))
613 'sparse-read.density-threshold'))
614 srmingapsize = self.ui.configbytes('experimental',
614 srmingapsize = self.ui.configbytes('experimental',
615 'sparse-read.min-gap-size')
615 'sparse-read.min-gap-size')
616 self.svfs.options['with-sparse-read'] = withsparseread
616 self.svfs.options['with-sparse-read'] = withsparseread
617 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
617 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
618 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
618 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
619
619
620 for r in self.requirements:
620 for r in self.requirements:
621 if r.startswith('exp-compression-'):
621 if r.startswith('exp-compression-'):
622 self.svfs.options['compengine'] = r[len('exp-compression-'):]
622 self.svfs.options['compengine'] = r[len('exp-compression-'):]
623
623
624 # TODO move "revlogv2" to openerreqs once finalized.
624 # TODO move "revlogv2" to openerreqs once finalized.
625 if REVLOGV2_REQUIREMENT in self.requirements:
625 if REVLOGV2_REQUIREMENT in self.requirements:
626 self.svfs.options['revlogv2'] = True
626 self.svfs.options['revlogv2'] = True
627
627
628 def _writerequirements(self):
628 def _writerequirements(self):
629 scmutil.writerequires(self.vfs, self.requirements)
629 scmutil.writerequires(self.vfs, self.requirements)
630
630
631 def _checknested(self, path):
631 def _checknested(self, path):
632 """Determine if path is a legal nested repository."""
632 """Determine if path is a legal nested repository."""
633 if not path.startswith(self.root):
633 if not path.startswith(self.root):
634 return False
634 return False
635 subpath = path[len(self.root) + 1:]
635 subpath = path[len(self.root) + 1:]
636 normsubpath = util.pconvert(subpath)
636 normsubpath = util.pconvert(subpath)
637
637
638 # XXX: Checking against the current working copy is wrong in
638 # XXX: Checking against the current working copy is wrong in
639 # the sense that it can reject things like
639 # the sense that it can reject things like
640 #
640 #
641 # $ hg cat -r 10 sub/x.txt
641 # $ hg cat -r 10 sub/x.txt
642 #
642 #
643 # if sub/ is no longer a subrepository in the working copy
643 # if sub/ is no longer a subrepository in the working copy
644 # parent revision.
644 # parent revision.
645 #
645 #
646 # However, it can of course also allow things that would have
646 # However, it can of course also allow things that would have
647 # been rejected before, such as the above cat command if sub/
647 # been rejected before, such as the above cat command if sub/
648 # is a subrepository now, but was a normal directory before.
648 # is a subrepository now, but was a normal directory before.
649 # The old path auditor would have rejected by mistake since it
649 # The old path auditor would have rejected by mistake since it
650 # panics when it sees sub/.hg/.
650 # panics when it sees sub/.hg/.
651 #
651 #
652 # All in all, checking against the working copy seems sensible
652 # All in all, checking against the working copy seems sensible
653 # since we want to prevent access to nested repositories on
653 # since we want to prevent access to nested repositories on
654 # the filesystem *now*.
654 # the filesystem *now*.
655 ctx = self[None]
655 ctx = self[None]
656 parts = util.splitpath(subpath)
656 parts = util.splitpath(subpath)
657 while parts:
657 while parts:
658 prefix = '/'.join(parts)
658 prefix = '/'.join(parts)
659 if prefix in ctx.substate:
659 if prefix in ctx.substate:
660 if prefix == normsubpath:
660 if prefix == normsubpath:
661 return True
661 return True
662 else:
662 else:
663 sub = ctx.sub(prefix)
663 sub = ctx.sub(prefix)
664 return sub.checknested(subpath[len(prefix) + 1:])
664 return sub.checknested(subpath[len(prefix) + 1:])
665 else:
665 else:
666 parts.pop()
666 parts.pop()
667 return False
667 return False
668
668
669 def peer(self):
669 def peer(self):
670 return localpeer(self) # not cached to avoid reference cycle
670 return localpeer(self) # not cached to avoid reference cycle
671
671
672 def unfiltered(self):
672 def unfiltered(self):
673 """Return unfiltered version of the repository
673 """Return unfiltered version of the repository
674
674
675 Intended to be overwritten by filtered repo."""
675 Intended to be overwritten by filtered repo."""
676 return self
676 return self
677
677
678 def filtered(self, name):
678 def filtered(self, name):
679 """Return a filtered version of a repository"""
679 """Return a filtered version of a repository"""
680 cls = repoview.newtype(self.unfiltered().__class__)
680 cls = repoview.newtype(self.unfiltered().__class__)
681 return cls(self, name)
681 return cls(self, name)
682
682
683 @repofilecache('bookmarks', 'bookmarks.current')
683 @repofilecache('bookmarks', 'bookmarks.current')
684 def _bookmarks(self):
684 def _bookmarks(self):
685 return bookmarks.bmstore(self)
685 return bookmarks.bmstore(self)
686
686
687 @property
687 @property
688 def _activebookmark(self):
688 def _activebookmark(self):
689 return self._bookmarks.active
689 return self._bookmarks.active
690
690
691 # _phaserevs and _phasesets depend on changelog. what we need is to
691 # _phasesets depend on changelog. what we need is to call
692 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
692 # _phasecache.invalidate() if '00changelog.i' was changed, but it
693 # can't be easily expressed in filecache mechanism.
693 # can't be easily expressed in filecache mechanism.
694 @storecache('phaseroots', '00changelog.i')
694 @storecache('phaseroots', '00changelog.i')
695 def _phasecache(self):
695 def _phasecache(self):
696 return phases.phasecache(self, self._phasedefaults)
696 return phases.phasecache(self, self._phasedefaults)
697
697
698 @storecache('obsstore')
698 @storecache('obsstore')
699 def obsstore(self):
699 def obsstore(self):
700 return obsolete.makestore(self.ui, self)
700 return obsolete.makestore(self.ui, self)
701
701
702 @storecache('00changelog.i')
702 @storecache('00changelog.i')
703 def changelog(self):
703 def changelog(self):
704 return changelog.changelog(self.svfs,
704 return changelog.changelog(self.svfs,
705 trypending=txnutil.mayhavepending(self.root))
705 trypending=txnutil.mayhavepending(self.root))
706
706
707 def _constructmanifest(self):
707 def _constructmanifest(self):
708 # This is a temporary function while we migrate from manifest to
708 # This is a temporary function while we migrate from manifest to
709 # manifestlog. It allows bundlerepo and unionrepo to intercept the
709 # manifestlog. It allows bundlerepo and unionrepo to intercept the
710 # manifest creation.
710 # manifest creation.
711 return manifest.manifestrevlog(self.svfs)
711 return manifest.manifestrevlog(self.svfs)
712
712
713 @storecache('00manifest.i')
713 @storecache('00manifest.i')
714 def manifestlog(self):
714 def manifestlog(self):
715 return manifest.manifestlog(self.svfs, self)
715 return manifest.manifestlog(self.svfs, self)
716
716
717 @repofilecache('dirstate')
717 @repofilecache('dirstate')
718 def dirstate(self):
718 def dirstate(self):
719 sparsematchfn = lambda: sparse.matcher(self)
719 sparsematchfn = lambda: sparse.matcher(self)
720
720
721 return dirstate.dirstate(self.vfs, self.ui, self.root,
721 return dirstate.dirstate(self.vfs, self.ui, self.root,
722 self._dirstatevalidate, sparsematchfn)
722 self._dirstatevalidate, sparsematchfn)
723
723
724 def _dirstatevalidate(self, node):
724 def _dirstatevalidate(self, node):
725 try:
725 try:
726 self.changelog.rev(node)
726 self.changelog.rev(node)
727 return node
727 return node
728 except error.LookupError:
728 except error.LookupError:
729 if not self._dirstatevalidatewarned:
729 if not self._dirstatevalidatewarned:
730 self._dirstatevalidatewarned = True
730 self._dirstatevalidatewarned = True
731 self.ui.warn(_("warning: ignoring unknown"
731 self.ui.warn(_("warning: ignoring unknown"
732 " working parent %s!\n") % short(node))
732 " working parent %s!\n") % short(node))
733 return nullid
733 return nullid
734
734
735 def __getitem__(self, changeid):
735 def __getitem__(self, changeid):
736 if changeid is None:
736 if changeid is None:
737 return context.workingctx(self)
737 return context.workingctx(self)
738 if isinstance(changeid, slice):
738 if isinstance(changeid, slice):
739 # wdirrev isn't contiguous so the slice shouldn't include it
739 # wdirrev isn't contiguous so the slice shouldn't include it
740 return [context.changectx(self, i)
740 return [context.changectx(self, i)
741 for i in xrange(*changeid.indices(len(self)))
741 for i in xrange(*changeid.indices(len(self)))
742 if i not in self.changelog.filteredrevs]
742 if i not in self.changelog.filteredrevs]
743 try:
743 try:
744 return context.changectx(self, changeid)
744 return context.changectx(self, changeid)
745 except error.WdirUnsupported:
745 except error.WdirUnsupported:
746 return context.workingctx(self)
746 return context.workingctx(self)
747
747
748 def __contains__(self, changeid):
748 def __contains__(self, changeid):
749 """True if the given changeid exists
749 """True if the given changeid exists
750
750
751 error.LookupError is raised if an ambiguous node specified.
751 error.LookupError is raised if an ambiguous node specified.
752 """
752 """
753 try:
753 try:
754 self[changeid]
754 self[changeid]
755 return True
755 return True
756 except error.RepoLookupError:
756 except error.RepoLookupError:
757 return False
757 return False
758
758
759 def __nonzero__(self):
759 def __nonzero__(self):
760 return True
760 return True
761
761
762 __bool__ = __nonzero__
762 __bool__ = __nonzero__
763
763
764 def __len__(self):
764 def __len__(self):
765 return len(self.changelog)
765 return len(self.changelog)
766
766
767 def __iter__(self):
767 def __iter__(self):
768 return iter(self.changelog)
768 return iter(self.changelog)
769
769
770 def revs(self, expr, *args):
770 def revs(self, expr, *args):
771 '''Find revisions matching a revset.
771 '''Find revisions matching a revset.
772
772
773 The revset is specified as a string ``expr`` that may contain
773 The revset is specified as a string ``expr`` that may contain
774 %-formatting to escape certain types. See ``revsetlang.formatspec``.
774 %-formatting to escape certain types. See ``revsetlang.formatspec``.
775
775
776 Revset aliases from the configuration are not expanded. To expand
776 Revset aliases from the configuration are not expanded. To expand
777 user aliases, consider calling ``scmutil.revrange()`` or
777 user aliases, consider calling ``scmutil.revrange()`` or
778 ``repo.anyrevs([expr], user=True)``.
778 ``repo.anyrevs([expr], user=True)``.
779
779
780 Returns a revset.abstractsmartset, which is a list-like interface
780 Returns a revset.abstractsmartset, which is a list-like interface
781 that contains integer revisions.
781 that contains integer revisions.
782 '''
782 '''
783 expr = revsetlang.formatspec(expr, *args)
783 expr = revsetlang.formatspec(expr, *args)
784 m = revset.match(None, expr)
784 m = revset.match(None, expr)
785 return m(self)
785 return m(self)
786
786
787 def set(self, expr, *args):
787 def set(self, expr, *args):
788 '''Find revisions matching a revset and emit changectx instances.
788 '''Find revisions matching a revset and emit changectx instances.
789
789
790 This is a convenience wrapper around ``revs()`` that iterates the
790 This is a convenience wrapper around ``revs()`` that iterates the
791 result and is a generator of changectx instances.
791 result and is a generator of changectx instances.
792
792
793 Revset aliases from the configuration are not expanded. To expand
793 Revset aliases from the configuration are not expanded. To expand
794 user aliases, consider calling ``scmutil.revrange()``.
794 user aliases, consider calling ``scmutil.revrange()``.
795 '''
795 '''
796 for r in self.revs(expr, *args):
796 for r in self.revs(expr, *args):
797 yield self[r]
797 yield self[r]
798
798
799 def anyrevs(self, specs, user=False, localalias=None):
799 def anyrevs(self, specs, user=False, localalias=None):
800 '''Find revisions matching one of the given revsets.
800 '''Find revisions matching one of the given revsets.
801
801
802 Revset aliases from the configuration are not expanded by default. To
802 Revset aliases from the configuration are not expanded by default. To
803 expand user aliases, specify ``user=True``. To provide some local
803 expand user aliases, specify ``user=True``. To provide some local
804 definitions overriding user aliases, set ``localalias`` to
804 definitions overriding user aliases, set ``localalias`` to
805 ``{name: definitionstring}``.
805 ``{name: definitionstring}``.
806 '''
806 '''
807 if user:
807 if user:
808 m = revset.matchany(self.ui, specs, repo=self,
808 m = revset.matchany(self.ui, specs, repo=self,
809 localalias=localalias)
809 localalias=localalias)
810 else:
810 else:
811 m = revset.matchany(None, specs, localalias=localalias)
811 m = revset.matchany(None, specs, localalias=localalias)
812 return m(self)
812 return m(self)
813
813
814 def url(self):
814 def url(self):
815 return 'file:' + self.root
815 return 'file:' + self.root
816
816
817 def hook(self, name, throw=False, **args):
817 def hook(self, name, throw=False, **args):
818 """Call a hook, passing this repo instance.
818 """Call a hook, passing this repo instance.
819
819
820 This a convenience method to aid invoking hooks. Extensions likely
820 This a convenience method to aid invoking hooks. Extensions likely
821 won't call this unless they have registered a custom hook or are
821 won't call this unless they have registered a custom hook or are
822 replacing code that is expected to call a hook.
822 replacing code that is expected to call a hook.
823 """
823 """
824 return hook.hook(self.ui, self, name, throw, **args)
824 return hook.hook(self.ui, self, name, throw, **args)
825
825
826 @filteredpropertycache
826 @filteredpropertycache
827 def _tagscache(self):
827 def _tagscache(self):
828 '''Returns a tagscache object that contains various tags related
828 '''Returns a tagscache object that contains various tags related
829 caches.'''
829 caches.'''
830
830
831 # This simplifies its cache management by having one decorated
831 # This simplifies its cache management by having one decorated
832 # function (this one) and the rest simply fetch things from it.
832 # function (this one) and the rest simply fetch things from it.
833 class tagscache(object):
833 class tagscache(object):
834 def __init__(self):
834 def __init__(self):
835 # These two define the set of tags for this repository. tags
835 # These two define the set of tags for this repository. tags
836 # maps tag name to node; tagtypes maps tag name to 'global' or
836 # maps tag name to node; tagtypes maps tag name to 'global' or
837 # 'local'. (Global tags are defined by .hgtags across all
837 # 'local'. (Global tags are defined by .hgtags across all
838 # heads, and local tags are defined in .hg/localtags.)
838 # heads, and local tags are defined in .hg/localtags.)
839 # They constitute the in-memory cache of tags.
839 # They constitute the in-memory cache of tags.
840 self.tags = self.tagtypes = None
840 self.tags = self.tagtypes = None
841
841
842 self.nodetagscache = self.tagslist = None
842 self.nodetagscache = self.tagslist = None
843
843
844 cache = tagscache()
844 cache = tagscache()
845 cache.tags, cache.tagtypes = self._findtags()
845 cache.tags, cache.tagtypes = self._findtags()
846
846
847 return cache
847 return cache
848
848
849 def tags(self):
849 def tags(self):
850 '''return a mapping of tag to node'''
850 '''return a mapping of tag to node'''
851 t = {}
851 t = {}
852 if self.changelog.filteredrevs:
852 if self.changelog.filteredrevs:
853 tags, tt = self._findtags()
853 tags, tt = self._findtags()
854 else:
854 else:
855 tags = self._tagscache.tags
855 tags = self._tagscache.tags
856 for k, v in tags.iteritems():
856 for k, v in tags.iteritems():
857 try:
857 try:
858 # ignore tags to unknown nodes
858 # ignore tags to unknown nodes
859 self.changelog.rev(v)
859 self.changelog.rev(v)
860 t[k] = v
860 t[k] = v
861 except (error.LookupError, ValueError):
861 except (error.LookupError, ValueError):
862 pass
862 pass
863 return t
863 return t
864
864
865 def _findtags(self):
865 def _findtags(self):
866 '''Do the hard work of finding tags. Return a pair of dicts
866 '''Do the hard work of finding tags. Return a pair of dicts
867 (tags, tagtypes) where tags maps tag name to node, and tagtypes
867 (tags, tagtypes) where tags maps tag name to node, and tagtypes
868 maps tag name to a string like \'global\' or \'local\'.
868 maps tag name to a string like \'global\' or \'local\'.
869 Subclasses or extensions are free to add their own tags, but
869 Subclasses or extensions are free to add their own tags, but
870 should be aware that the returned dicts will be retained for the
870 should be aware that the returned dicts will be retained for the
871 duration of the localrepo object.'''
871 duration of the localrepo object.'''
872
872
873 # XXX what tagtype should subclasses/extensions use? Currently
873 # XXX what tagtype should subclasses/extensions use? Currently
874 # mq and bookmarks add tags, but do not set the tagtype at all.
874 # mq and bookmarks add tags, but do not set the tagtype at all.
875 # Should each extension invent its own tag type? Should there
875 # Should each extension invent its own tag type? Should there
876 # be one tagtype for all such "virtual" tags? Or is the status
876 # be one tagtype for all such "virtual" tags? Or is the status
877 # quo fine?
877 # quo fine?
878
878
879
879
880 # map tag name to (node, hist)
880 # map tag name to (node, hist)
881 alltags = tagsmod.findglobaltags(self.ui, self)
881 alltags = tagsmod.findglobaltags(self.ui, self)
882 # map tag name to tag type
882 # map tag name to tag type
883 tagtypes = dict((tag, 'global') for tag in alltags)
883 tagtypes = dict((tag, 'global') for tag in alltags)
884
884
885 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
885 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
886
886
887 # Build the return dicts. Have to re-encode tag names because
887 # Build the return dicts. Have to re-encode tag names because
888 # the tags module always uses UTF-8 (in order not to lose info
888 # the tags module always uses UTF-8 (in order not to lose info
889 # writing to the cache), but the rest of Mercurial wants them in
889 # writing to the cache), but the rest of Mercurial wants them in
890 # local encoding.
890 # local encoding.
891 tags = {}
891 tags = {}
892 for (name, (node, hist)) in alltags.iteritems():
892 for (name, (node, hist)) in alltags.iteritems():
893 if node != nullid:
893 if node != nullid:
894 tags[encoding.tolocal(name)] = node
894 tags[encoding.tolocal(name)] = node
895 tags['tip'] = self.changelog.tip()
895 tags['tip'] = self.changelog.tip()
896 tagtypes = dict([(encoding.tolocal(name), value)
896 tagtypes = dict([(encoding.tolocal(name), value)
897 for (name, value) in tagtypes.iteritems()])
897 for (name, value) in tagtypes.iteritems()])
898 return (tags, tagtypes)
898 return (tags, tagtypes)
899
899
900 def tagtype(self, tagname):
900 def tagtype(self, tagname):
901 '''
901 '''
902 return the type of the given tag. result can be:
902 return the type of the given tag. result can be:
903
903
904 'local' : a local tag
904 'local' : a local tag
905 'global' : a global tag
905 'global' : a global tag
906 None : tag does not exist
906 None : tag does not exist
907 '''
907 '''
908
908
909 return self._tagscache.tagtypes.get(tagname)
909 return self._tagscache.tagtypes.get(tagname)
910
910
911 def tagslist(self):
911 def tagslist(self):
912 '''return a list of tags ordered by revision'''
912 '''return a list of tags ordered by revision'''
913 if not self._tagscache.tagslist:
913 if not self._tagscache.tagslist:
914 l = []
914 l = []
915 for t, n in self.tags().iteritems():
915 for t, n in self.tags().iteritems():
916 l.append((self.changelog.rev(n), t, n))
916 l.append((self.changelog.rev(n), t, n))
917 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
917 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
918
918
919 return self._tagscache.tagslist
919 return self._tagscache.tagslist
920
920
921 def nodetags(self, node):
921 def nodetags(self, node):
922 '''return the tags associated with a node'''
922 '''return the tags associated with a node'''
923 if not self._tagscache.nodetagscache:
923 if not self._tagscache.nodetagscache:
924 nodetagscache = {}
924 nodetagscache = {}
925 for t, n in self._tagscache.tags.iteritems():
925 for t, n in self._tagscache.tags.iteritems():
926 nodetagscache.setdefault(n, []).append(t)
926 nodetagscache.setdefault(n, []).append(t)
927 for tags in nodetagscache.itervalues():
927 for tags in nodetagscache.itervalues():
928 tags.sort()
928 tags.sort()
929 self._tagscache.nodetagscache = nodetagscache
929 self._tagscache.nodetagscache = nodetagscache
930 return self._tagscache.nodetagscache.get(node, [])
930 return self._tagscache.nodetagscache.get(node, [])
931
931
932 def nodebookmarks(self, node):
932 def nodebookmarks(self, node):
933 """return the list of bookmarks pointing to the specified node"""
933 """return the list of bookmarks pointing to the specified node"""
934 marks = []
934 marks = []
935 for bookmark, n in self._bookmarks.iteritems():
935 for bookmark, n in self._bookmarks.iteritems():
936 if n == node:
936 if n == node:
937 marks.append(bookmark)
937 marks.append(bookmark)
938 return sorted(marks)
938 return sorted(marks)
939
939
940 def branchmap(self):
940 def branchmap(self):
941 '''returns a dictionary {branch: [branchheads]} with branchheads
941 '''returns a dictionary {branch: [branchheads]} with branchheads
942 ordered by increasing revision number'''
942 ordered by increasing revision number'''
943 branchmap.updatecache(self)
943 branchmap.updatecache(self)
944 return self._branchcaches[self.filtername]
944 return self._branchcaches[self.filtername]
945
945
946 @unfilteredmethod
946 @unfilteredmethod
947 def revbranchcache(self):
947 def revbranchcache(self):
948 if not self._revbranchcache:
948 if not self._revbranchcache:
949 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
949 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
950 return self._revbranchcache
950 return self._revbranchcache
951
951
952 def branchtip(self, branch, ignoremissing=False):
952 def branchtip(self, branch, ignoremissing=False):
953 '''return the tip node for a given branch
953 '''return the tip node for a given branch
954
954
955 If ignoremissing is True, then this method will not raise an error.
955 If ignoremissing is True, then this method will not raise an error.
956 This is helpful for callers that only expect None for a missing branch
956 This is helpful for callers that only expect None for a missing branch
957 (e.g. namespace).
957 (e.g. namespace).
958
958
959 '''
959 '''
960 try:
960 try:
961 return self.branchmap().branchtip(branch)
961 return self.branchmap().branchtip(branch)
962 except KeyError:
962 except KeyError:
963 if not ignoremissing:
963 if not ignoremissing:
964 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
964 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
965 else:
965 else:
966 pass
966 pass
967
967
968 def lookup(self, key):
968 def lookup(self, key):
969 return self[key].node()
969 return self[key].node()
970
970
971 def lookupbranch(self, key, remote=None):
971 def lookupbranch(self, key, remote=None):
972 repo = remote or self
972 repo = remote or self
973 if key in repo.branchmap():
973 if key in repo.branchmap():
974 return key
974 return key
975
975
976 repo = (remote and remote.local()) and remote or self
976 repo = (remote and remote.local()) and remote or self
977 return repo[key].branch()
977 return repo[key].branch()
978
978
979 def known(self, nodes):
979 def known(self, nodes):
980 cl = self.changelog
980 cl = self.changelog
981 nm = cl.nodemap
981 nm = cl.nodemap
982 filtered = cl.filteredrevs
982 filtered = cl.filteredrevs
983 result = []
983 result = []
984 for n in nodes:
984 for n in nodes:
985 r = nm.get(n)
985 r = nm.get(n)
986 resp = not (r is None or r in filtered)
986 resp = not (r is None or r in filtered)
987 result.append(resp)
987 result.append(resp)
988 return result
988 return result
989
989
990 def local(self):
990 def local(self):
991 return self
991 return self
992
992
993 def publishing(self):
993 def publishing(self):
994 # it's safe (and desirable) to trust the publish flag unconditionally
994 # it's safe (and desirable) to trust the publish flag unconditionally
995 # so that we don't finalize changes shared between users via ssh or nfs
995 # so that we don't finalize changes shared between users via ssh or nfs
996 return self.ui.configbool('phases', 'publish', untrusted=True)
996 return self.ui.configbool('phases', 'publish', untrusted=True)
997
997
998 def cancopy(self):
998 def cancopy(self):
999 # so statichttprepo's override of local() works
999 # so statichttprepo's override of local() works
1000 if not self.local():
1000 if not self.local():
1001 return False
1001 return False
1002 if not self.publishing():
1002 if not self.publishing():
1003 return True
1003 return True
1004 # if publishing we can't copy if there is filtered content
1004 # if publishing we can't copy if there is filtered content
1005 return not self.filtered('visible').changelog.filteredrevs
1005 return not self.filtered('visible').changelog.filteredrevs
1006
1006
1007 def shared(self):
1007 def shared(self):
1008 '''the type of shared repository (None if not shared)'''
1008 '''the type of shared repository (None if not shared)'''
1009 if self.sharedpath != self.path:
1009 if self.sharedpath != self.path:
1010 return 'store'
1010 return 'store'
1011 return None
1011 return None
1012
1012
1013 def wjoin(self, f, *insidef):
1013 def wjoin(self, f, *insidef):
1014 return self.vfs.reljoin(self.root, f, *insidef)
1014 return self.vfs.reljoin(self.root, f, *insidef)
1015
1015
1016 def file(self, f):
1016 def file(self, f):
1017 if f[0] == '/':
1017 if f[0] == '/':
1018 f = f[1:]
1018 f = f[1:]
1019 return filelog.filelog(self.svfs, f)
1019 return filelog.filelog(self.svfs, f)
1020
1020
1021 def changectx(self, changeid):
1021 def changectx(self, changeid):
1022 return self[changeid]
1022 return self[changeid]
1023
1023
1024 def setparents(self, p1, p2=nullid):
1024 def setparents(self, p1, p2=nullid):
1025 with self.dirstate.parentchange():
1025 with self.dirstate.parentchange():
1026 copies = self.dirstate.setparents(p1, p2)
1026 copies = self.dirstate.setparents(p1, p2)
1027 pctx = self[p1]
1027 pctx = self[p1]
1028 if copies:
1028 if copies:
1029 # Adjust copy records, the dirstate cannot do it, it
1029 # Adjust copy records, the dirstate cannot do it, it
1030 # requires access to parents manifests. Preserve them
1030 # requires access to parents manifests. Preserve them
1031 # only for entries added to first parent.
1031 # only for entries added to first parent.
1032 for f in copies:
1032 for f in copies:
1033 if f not in pctx and copies[f] in pctx:
1033 if f not in pctx and copies[f] in pctx:
1034 self.dirstate.copy(copies[f], f)
1034 self.dirstate.copy(copies[f], f)
1035 if p2 == nullid:
1035 if p2 == nullid:
1036 for f, s in sorted(self.dirstate.copies().items()):
1036 for f, s in sorted(self.dirstate.copies().items()):
1037 if f not in pctx and s not in pctx:
1037 if f not in pctx and s not in pctx:
1038 self.dirstate.copy(None, f)
1038 self.dirstate.copy(None, f)
1039
1039
1040 def filectx(self, path, changeid=None, fileid=None):
1040 def filectx(self, path, changeid=None, fileid=None):
1041 """changeid can be a changeset revision, node, or tag.
1041 """changeid can be a changeset revision, node, or tag.
1042 fileid can be a file revision or node."""
1042 fileid can be a file revision or node."""
1043 return context.filectx(self, path, changeid, fileid)
1043 return context.filectx(self, path, changeid, fileid)
1044
1044
1045 def getcwd(self):
1045 def getcwd(self):
1046 return self.dirstate.getcwd()
1046 return self.dirstate.getcwd()
1047
1047
1048 def pathto(self, f, cwd=None):
1048 def pathto(self, f, cwd=None):
1049 return self.dirstate.pathto(f, cwd)
1049 return self.dirstate.pathto(f, cwd)
1050
1050
1051 def _loadfilter(self, filter):
1051 def _loadfilter(self, filter):
1052 if filter not in self.filterpats:
1052 if filter not in self.filterpats:
1053 l = []
1053 l = []
1054 for pat, cmd in self.ui.configitems(filter):
1054 for pat, cmd in self.ui.configitems(filter):
1055 if cmd == '!':
1055 if cmd == '!':
1056 continue
1056 continue
1057 mf = matchmod.match(self.root, '', [pat])
1057 mf = matchmod.match(self.root, '', [pat])
1058 fn = None
1058 fn = None
1059 params = cmd
1059 params = cmd
1060 for name, filterfn in self._datafilters.iteritems():
1060 for name, filterfn in self._datafilters.iteritems():
1061 if cmd.startswith(name):
1061 if cmd.startswith(name):
1062 fn = filterfn
1062 fn = filterfn
1063 params = cmd[len(name):].lstrip()
1063 params = cmd[len(name):].lstrip()
1064 break
1064 break
1065 if not fn:
1065 if not fn:
1066 fn = lambda s, c, **kwargs: util.filter(s, c)
1066 fn = lambda s, c, **kwargs: util.filter(s, c)
1067 # Wrap old filters not supporting keyword arguments
1067 # Wrap old filters not supporting keyword arguments
1068 if not inspect.getargspec(fn)[2]:
1068 if not inspect.getargspec(fn)[2]:
1069 oldfn = fn
1069 oldfn = fn
1070 fn = lambda s, c, **kwargs: oldfn(s, c)
1070 fn = lambda s, c, **kwargs: oldfn(s, c)
1071 l.append((mf, fn, params))
1071 l.append((mf, fn, params))
1072 self.filterpats[filter] = l
1072 self.filterpats[filter] = l
1073 return self.filterpats[filter]
1073 return self.filterpats[filter]
1074
1074
1075 def _filter(self, filterpats, filename, data):
1075 def _filter(self, filterpats, filename, data):
1076 for mf, fn, cmd in filterpats:
1076 for mf, fn, cmd in filterpats:
1077 if mf(filename):
1077 if mf(filename):
1078 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1078 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1079 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1079 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1080 break
1080 break
1081
1081
1082 return data
1082 return data
1083
1083
1084 @unfilteredpropertycache
1084 @unfilteredpropertycache
1085 def _encodefilterpats(self):
1085 def _encodefilterpats(self):
1086 return self._loadfilter('encode')
1086 return self._loadfilter('encode')
1087
1087
1088 @unfilteredpropertycache
1088 @unfilteredpropertycache
1089 def _decodefilterpats(self):
1089 def _decodefilterpats(self):
1090 return self._loadfilter('decode')
1090 return self._loadfilter('decode')
1091
1091
1092 def adddatafilter(self, name, filter):
1092 def adddatafilter(self, name, filter):
1093 self._datafilters[name] = filter
1093 self._datafilters[name] = filter
1094
1094
1095 def wread(self, filename):
1095 def wread(self, filename):
1096 if self.wvfs.islink(filename):
1096 if self.wvfs.islink(filename):
1097 data = self.wvfs.readlink(filename)
1097 data = self.wvfs.readlink(filename)
1098 else:
1098 else:
1099 data = self.wvfs.read(filename)
1099 data = self.wvfs.read(filename)
1100 return self._filter(self._encodefilterpats, filename, data)
1100 return self._filter(self._encodefilterpats, filename, data)
1101
1101
1102 def wwrite(self, filename, data, flags, backgroundclose=False):
1102 def wwrite(self, filename, data, flags, backgroundclose=False):
1103 """write ``data`` into ``filename`` in the working directory
1103 """write ``data`` into ``filename`` in the working directory
1104
1104
1105 This returns length of written (maybe decoded) data.
1105 This returns length of written (maybe decoded) data.
1106 """
1106 """
1107 data = self._filter(self._decodefilterpats, filename, data)
1107 data = self._filter(self._decodefilterpats, filename, data)
1108 if 'l' in flags:
1108 if 'l' in flags:
1109 self.wvfs.symlink(data, filename)
1109 self.wvfs.symlink(data, filename)
1110 else:
1110 else:
1111 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1111 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1112 if 'x' in flags:
1112 if 'x' in flags:
1113 self.wvfs.setflags(filename, False, True)
1113 self.wvfs.setflags(filename, False, True)
1114 return len(data)
1114 return len(data)
1115
1115
1116 def wwritedata(self, filename, data):
1116 def wwritedata(self, filename, data):
1117 return self._filter(self._decodefilterpats, filename, data)
1117 return self._filter(self._decodefilterpats, filename, data)
1118
1118
1119 def currenttransaction(self):
1119 def currenttransaction(self):
1120 """return the current transaction or None if non exists"""
1120 """return the current transaction or None if non exists"""
1121 if self._transref:
1121 if self._transref:
1122 tr = self._transref()
1122 tr = self._transref()
1123 else:
1123 else:
1124 tr = None
1124 tr = None
1125
1125
1126 if tr and tr.running():
1126 if tr and tr.running():
1127 return tr
1127 return tr
1128 return None
1128 return None
1129
1129
1130 def transaction(self, desc, report=None):
1130 def transaction(self, desc, report=None):
1131 if (self.ui.configbool('devel', 'all-warnings')
1131 if (self.ui.configbool('devel', 'all-warnings')
1132 or self.ui.configbool('devel', 'check-locks')):
1132 or self.ui.configbool('devel', 'check-locks')):
1133 if self._currentlock(self._lockref) is None:
1133 if self._currentlock(self._lockref) is None:
1134 raise error.ProgrammingError('transaction requires locking')
1134 raise error.ProgrammingError('transaction requires locking')
1135 tr = self.currenttransaction()
1135 tr = self.currenttransaction()
1136 if tr is not None:
1136 if tr is not None:
1137 scmutil.registersummarycallback(self, tr, desc)
1137 scmutil.registersummarycallback(self, tr, desc)
1138 return tr.nest()
1138 return tr.nest()
1139
1139
1140 # abort here if the journal already exists
1140 # abort here if the journal already exists
1141 if self.svfs.exists("journal"):
1141 if self.svfs.exists("journal"):
1142 raise error.RepoError(
1142 raise error.RepoError(
1143 _("abandoned transaction found"),
1143 _("abandoned transaction found"),
1144 hint=_("run 'hg recover' to clean up transaction"))
1144 hint=_("run 'hg recover' to clean up transaction"))
1145
1145
1146 idbase = "%.40f#%f" % (random.random(), time.time())
1146 idbase = "%.40f#%f" % (random.random(), time.time())
1147 ha = hex(hashlib.sha1(idbase).digest())
1147 ha = hex(hashlib.sha1(idbase).digest())
1148 txnid = 'TXN:' + ha
1148 txnid = 'TXN:' + ha
1149 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1149 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1150
1150
1151 self._writejournal(desc)
1151 self._writejournal(desc)
1152 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1152 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1153 if report:
1153 if report:
1154 rp = report
1154 rp = report
1155 else:
1155 else:
1156 rp = self.ui.warn
1156 rp = self.ui.warn
1157 vfsmap = {'plain': self.vfs} # root of .hg/
1157 vfsmap = {'plain': self.vfs} # root of .hg/
1158 # we must avoid cyclic reference between repo and transaction.
1158 # we must avoid cyclic reference between repo and transaction.
1159 reporef = weakref.ref(self)
1159 reporef = weakref.ref(self)
1160 # Code to track tag movement
1160 # Code to track tag movement
1161 #
1161 #
1162 # Since tags are all handled as file content, it is actually quite hard
1162 # Since tags are all handled as file content, it is actually quite hard
1163 # to track these movement from a code perspective. So we fallback to a
1163 # to track these movement from a code perspective. So we fallback to a
1164 # tracking at the repository level. One could envision to track changes
1164 # tracking at the repository level. One could envision to track changes
1165 # to the '.hgtags' file through changegroup apply but that fails to
1165 # to the '.hgtags' file through changegroup apply but that fails to
1166 # cope with case where transaction expose new heads without changegroup
1166 # cope with case where transaction expose new heads without changegroup
1167 # being involved (eg: phase movement).
1167 # being involved (eg: phase movement).
1168 #
1168 #
1169 # For now, We gate the feature behind a flag since this likely comes
1169 # For now, We gate the feature behind a flag since this likely comes
1170 # with performance impacts. The current code run more often than needed
1170 # with performance impacts. The current code run more often than needed
1171 # and do not use caches as much as it could. The current focus is on
1171 # and do not use caches as much as it could. The current focus is on
1172 # the behavior of the feature so we disable it by default. The flag
1172 # the behavior of the feature so we disable it by default. The flag
1173 # will be removed when we are happy with the performance impact.
1173 # will be removed when we are happy with the performance impact.
1174 #
1174 #
1175 # Once this feature is no longer experimental move the following
1175 # Once this feature is no longer experimental move the following
1176 # documentation to the appropriate help section:
1176 # documentation to the appropriate help section:
1177 #
1177 #
1178 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1178 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1179 # tags (new or changed or deleted tags). In addition the details of
1179 # tags (new or changed or deleted tags). In addition the details of
1180 # these changes are made available in a file at:
1180 # these changes are made available in a file at:
1181 # ``REPOROOT/.hg/changes/tags.changes``.
1181 # ``REPOROOT/.hg/changes/tags.changes``.
1182 # Make sure you check for HG_TAG_MOVED before reading that file as it
1182 # Make sure you check for HG_TAG_MOVED before reading that file as it
1183 # might exist from a previous transaction even if no tag were touched
1183 # might exist from a previous transaction even if no tag were touched
1184 # in this one. Changes are recorded in a line base format::
1184 # in this one. Changes are recorded in a line base format::
1185 #
1185 #
1186 # <action> <hex-node> <tag-name>\n
1186 # <action> <hex-node> <tag-name>\n
1187 #
1187 #
1188 # Actions are defined as follow:
1188 # Actions are defined as follow:
1189 # "-R": tag is removed,
1189 # "-R": tag is removed,
1190 # "+A": tag is added,
1190 # "+A": tag is added,
1191 # "-M": tag is moved (old value),
1191 # "-M": tag is moved (old value),
1192 # "+M": tag is moved (new value),
1192 # "+M": tag is moved (new value),
1193 tracktags = lambda x: None
1193 tracktags = lambda x: None
1194 # experimental config: experimental.hook-track-tags
1194 # experimental config: experimental.hook-track-tags
1195 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1195 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1196 if desc != 'strip' and shouldtracktags:
1196 if desc != 'strip' and shouldtracktags:
1197 oldheads = self.changelog.headrevs()
1197 oldheads = self.changelog.headrevs()
1198 def tracktags(tr2):
1198 def tracktags(tr2):
1199 repo = reporef()
1199 repo = reporef()
1200 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1200 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1201 newheads = repo.changelog.headrevs()
1201 newheads = repo.changelog.headrevs()
1202 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1202 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1203 # notes: we compare lists here.
1203 # notes: we compare lists here.
1204 # As we do it only once buiding set would not be cheaper
1204 # As we do it only once buiding set would not be cheaper
1205 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1205 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1206 if changes:
1206 if changes:
1207 tr2.hookargs['tag_moved'] = '1'
1207 tr2.hookargs['tag_moved'] = '1'
1208 with repo.vfs('changes/tags.changes', 'w',
1208 with repo.vfs('changes/tags.changes', 'w',
1209 atomictemp=True) as changesfile:
1209 atomictemp=True) as changesfile:
1210 # note: we do not register the file to the transaction
1210 # note: we do not register the file to the transaction
1211 # because we needs it to still exist on the transaction
1211 # because we needs it to still exist on the transaction
1212 # is close (for txnclose hooks)
1212 # is close (for txnclose hooks)
1213 tagsmod.writediff(changesfile, changes)
1213 tagsmod.writediff(changesfile, changes)
1214 def validate(tr2):
1214 def validate(tr2):
1215 """will run pre-closing hooks"""
1215 """will run pre-closing hooks"""
1216 # XXX the transaction API is a bit lacking here so we take a hacky
1216 # XXX the transaction API is a bit lacking here so we take a hacky
1217 # path for now
1217 # path for now
1218 #
1218 #
1219 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1219 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1220 # dict is copied before these run. In addition we needs the data
1220 # dict is copied before these run. In addition we needs the data
1221 # available to in memory hooks too.
1221 # available to in memory hooks too.
1222 #
1222 #
1223 # Moreover, we also need to make sure this runs before txnclose
1223 # Moreover, we also need to make sure this runs before txnclose
1224 # hooks and there is no "pending" mechanism that would execute
1224 # hooks and there is no "pending" mechanism that would execute
1225 # logic only if hooks are about to run.
1225 # logic only if hooks are about to run.
1226 #
1226 #
1227 # Fixing this limitation of the transaction is also needed to track
1227 # Fixing this limitation of the transaction is also needed to track
1228 # other families of changes (bookmarks, phases, obsolescence).
1228 # other families of changes (bookmarks, phases, obsolescence).
1229 #
1229 #
1230 # This will have to be fixed before we remove the experimental
1230 # This will have to be fixed before we remove the experimental
1231 # gating.
1231 # gating.
1232 tracktags(tr2)
1232 tracktags(tr2)
1233 repo = reporef()
1233 repo = reporef()
1234 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1234 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1235 scmutil.enforcesinglehead(repo, tr2, desc)
1235 scmutil.enforcesinglehead(repo, tr2, desc)
1236 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1236 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1237 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1237 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1238 args = tr.hookargs.copy()
1238 args = tr.hookargs.copy()
1239 args.update(bookmarks.preparehookargs(name, old, new))
1239 args.update(bookmarks.preparehookargs(name, old, new))
1240 repo.hook('pretxnclose-bookmark', throw=True,
1240 repo.hook('pretxnclose-bookmark', throw=True,
1241 txnname=desc,
1241 txnname=desc,
1242 **pycompat.strkwargs(args))
1242 **pycompat.strkwargs(args))
1243 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1243 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1244 cl = repo.unfiltered().changelog
1244 cl = repo.unfiltered().changelog
1245 for rev, (old, new) in tr.changes['phases'].items():
1245 for rev, (old, new) in tr.changes['phases'].items():
1246 args = tr.hookargs.copy()
1246 args = tr.hookargs.copy()
1247 node = hex(cl.node(rev))
1247 node = hex(cl.node(rev))
1248 args.update(phases.preparehookargs(node, old, new))
1248 args.update(phases.preparehookargs(node, old, new))
1249 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1249 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1250 **pycompat.strkwargs(args))
1250 **pycompat.strkwargs(args))
1251
1251
1252 repo.hook('pretxnclose', throw=True,
1252 repo.hook('pretxnclose', throw=True,
1253 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1253 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1254 def releasefn(tr, success):
1254 def releasefn(tr, success):
1255 repo = reporef()
1255 repo = reporef()
1256 if success:
1256 if success:
1257 # this should be explicitly invoked here, because
1257 # this should be explicitly invoked here, because
1258 # in-memory changes aren't written out at closing
1258 # in-memory changes aren't written out at closing
1259 # transaction, if tr.addfilegenerator (via
1259 # transaction, if tr.addfilegenerator (via
1260 # dirstate.write or so) isn't invoked while
1260 # dirstate.write or so) isn't invoked while
1261 # transaction running
1261 # transaction running
1262 repo.dirstate.write(None)
1262 repo.dirstate.write(None)
1263 else:
1263 else:
1264 # discard all changes (including ones already written
1264 # discard all changes (including ones already written
1265 # out) in this transaction
1265 # out) in this transaction
1266 repo.dirstate.restorebackup(None, 'journal.dirstate')
1266 repo.dirstate.restorebackup(None, 'journal.dirstate')
1267
1267
1268 repo.invalidate(clearfilecache=True)
1268 repo.invalidate(clearfilecache=True)
1269
1269
1270 tr = transaction.transaction(rp, self.svfs, vfsmap,
1270 tr = transaction.transaction(rp, self.svfs, vfsmap,
1271 "journal",
1271 "journal",
1272 "undo",
1272 "undo",
1273 aftertrans(renames),
1273 aftertrans(renames),
1274 self.store.createmode,
1274 self.store.createmode,
1275 validator=validate,
1275 validator=validate,
1276 releasefn=releasefn,
1276 releasefn=releasefn,
1277 checkambigfiles=_cachedfiles)
1277 checkambigfiles=_cachedfiles)
1278 tr.changes['revs'] = xrange(0, 0)
1278 tr.changes['revs'] = xrange(0, 0)
1279 tr.changes['obsmarkers'] = set()
1279 tr.changes['obsmarkers'] = set()
1280 tr.changes['phases'] = {}
1280 tr.changes['phases'] = {}
1281 tr.changes['bookmarks'] = {}
1281 tr.changes['bookmarks'] = {}
1282
1282
1283 tr.hookargs['txnid'] = txnid
1283 tr.hookargs['txnid'] = txnid
1284 # note: writing the fncache only during finalize mean that the file is
1284 # note: writing the fncache only during finalize mean that the file is
1285 # outdated when running hooks. As fncache is used for streaming clone,
1285 # outdated when running hooks. As fncache is used for streaming clone,
1286 # this is not expected to break anything that happen during the hooks.
1286 # this is not expected to break anything that happen during the hooks.
1287 tr.addfinalize('flush-fncache', self.store.write)
1287 tr.addfinalize('flush-fncache', self.store.write)
1288 def txnclosehook(tr2):
1288 def txnclosehook(tr2):
1289 """To be run if transaction is successful, will schedule a hook run
1289 """To be run if transaction is successful, will schedule a hook run
1290 """
1290 """
1291 # Don't reference tr2 in hook() so we don't hold a reference.
1291 # Don't reference tr2 in hook() so we don't hold a reference.
1292 # This reduces memory consumption when there are multiple
1292 # This reduces memory consumption when there are multiple
1293 # transactions per lock. This can likely go away if issue5045
1293 # transactions per lock. This can likely go away if issue5045
1294 # fixes the function accumulation.
1294 # fixes the function accumulation.
1295 hookargs = tr2.hookargs
1295 hookargs = tr2.hookargs
1296
1296
1297 def hookfunc():
1297 def hookfunc():
1298 repo = reporef()
1298 repo = reporef()
1299 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1299 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1300 bmchanges = sorted(tr.changes['bookmarks'].items())
1300 bmchanges = sorted(tr.changes['bookmarks'].items())
1301 for name, (old, new) in bmchanges:
1301 for name, (old, new) in bmchanges:
1302 args = tr.hookargs.copy()
1302 args = tr.hookargs.copy()
1303 args.update(bookmarks.preparehookargs(name, old, new))
1303 args.update(bookmarks.preparehookargs(name, old, new))
1304 repo.hook('txnclose-bookmark', throw=False,
1304 repo.hook('txnclose-bookmark', throw=False,
1305 txnname=desc, **pycompat.strkwargs(args))
1305 txnname=desc, **pycompat.strkwargs(args))
1306
1306
1307 if hook.hashook(repo.ui, 'txnclose-phase'):
1307 if hook.hashook(repo.ui, 'txnclose-phase'):
1308 cl = repo.unfiltered().changelog
1308 cl = repo.unfiltered().changelog
1309 phasemv = sorted(tr.changes['phases'].items())
1309 phasemv = sorted(tr.changes['phases'].items())
1310 for rev, (old, new) in phasemv:
1310 for rev, (old, new) in phasemv:
1311 args = tr.hookargs.copy()
1311 args = tr.hookargs.copy()
1312 node = hex(cl.node(rev))
1312 node = hex(cl.node(rev))
1313 args.update(phases.preparehookargs(node, old, new))
1313 args.update(phases.preparehookargs(node, old, new))
1314 repo.hook('txnclose-phase', throw=False, txnname=desc,
1314 repo.hook('txnclose-phase', throw=False, txnname=desc,
1315 **pycompat.strkwargs(args))
1315 **pycompat.strkwargs(args))
1316
1316
1317 repo.hook('txnclose', throw=False, txnname=desc,
1317 repo.hook('txnclose', throw=False, txnname=desc,
1318 **pycompat.strkwargs(hookargs))
1318 **pycompat.strkwargs(hookargs))
1319 reporef()._afterlock(hookfunc)
1319 reporef()._afterlock(hookfunc)
1320 tr.addfinalize('txnclose-hook', txnclosehook)
1320 tr.addfinalize('txnclose-hook', txnclosehook)
1321 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1321 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1322 def txnaborthook(tr2):
1322 def txnaborthook(tr2):
1323 """To be run if transaction is aborted
1323 """To be run if transaction is aborted
1324 """
1324 """
1325 reporef().hook('txnabort', throw=False, txnname=desc,
1325 reporef().hook('txnabort', throw=False, txnname=desc,
1326 **tr2.hookargs)
1326 **tr2.hookargs)
1327 tr.addabort('txnabort-hook', txnaborthook)
1327 tr.addabort('txnabort-hook', txnaborthook)
1328 # avoid eager cache invalidation. in-memory data should be identical
1328 # avoid eager cache invalidation. in-memory data should be identical
1329 # to stored data if transaction has no error.
1329 # to stored data if transaction has no error.
1330 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1330 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1331 self._transref = weakref.ref(tr)
1331 self._transref = weakref.ref(tr)
1332 scmutil.registersummarycallback(self, tr, desc)
1332 scmutil.registersummarycallback(self, tr, desc)
1333 return tr
1333 return tr
1334
1334
1335 def _journalfiles(self):
1335 def _journalfiles(self):
1336 return ((self.svfs, 'journal'),
1336 return ((self.svfs, 'journal'),
1337 (self.vfs, 'journal.dirstate'),
1337 (self.vfs, 'journal.dirstate'),
1338 (self.vfs, 'journal.branch'),
1338 (self.vfs, 'journal.branch'),
1339 (self.vfs, 'journal.desc'),
1339 (self.vfs, 'journal.desc'),
1340 (self.vfs, 'journal.bookmarks'),
1340 (self.vfs, 'journal.bookmarks'),
1341 (self.svfs, 'journal.phaseroots'))
1341 (self.svfs, 'journal.phaseroots'))
1342
1342
1343 def undofiles(self):
1343 def undofiles(self):
1344 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1344 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1345
1345
1346 @unfilteredmethod
1346 @unfilteredmethod
1347 def _writejournal(self, desc):
1347 def _writejournal(self, desc):
1348 self.dirstate.savebackup(None, 'journal.dirstate')
1348 self.dirstate.savebackup(None, 'journal.dirstate')
1349 self.vfs.write("journal.branch",
1349 self.vfs.write("journal.branch",
1350 encoding.fromlocal(self.dirstate.branch()))
1350 encoding.fromlocal(self.dirstate.branch()))
1351 self.vfs.write("journal.desc",
1351 self.vfs.write("journal.desc",
1352 "%d\n%s\n" % (len(self), desc))
1352 "%d\n%s\n" % (len(self), desc))
1353 self.vfs.write("journal.bookmarks",
1353 self.vfs.write("journal.bookmarks",
1354 self.vfs.tryread("bookmarks"))
1354 self.vfs.tryread("bookmarks"))
1355 self.svfs.write("journal.phaseroots",
1355 self.svfs.write("journal.phaseroots",
1356 self.svfs.tryread("phaseroots"))
1356 self.svfs.tryread("phaseroots"))
1357
1357
1358 def recover(self):
1358 def recover(self):
1359 with self.lock():
1359 with self.lock():
1360 if self.svfs.exists("journal"):
1360 if self.svfs.exists("journal"):
1361 self.ui.status(_("rolling back interrupted transaction\n"))
1361 self.ui.status(_("rolling back interrupted transaction\n"))
1362 vfsmap = {'': self.svfs,
1362 vfsmap = {'': self.svfs,
1363 'plain': self.vfs,}
1363 'plain': self.vfs,}
1364 transaction.rollback(self.svfs, vfsmap, "journal",
1364 transaction.rollback(self.svfs, vfsmap, "journal",
1365 self.ui.warn,
1365 self.ui.warn,
1366 checkambigfiles=_cachedfiles)
1366 checkambigfiles=_cachedfiles)
1367 self.invalidate()
1367 self.invalidate()
1368 return True
1368 return True
1369 else:
1369 else:
1370 self.ui.warn(_("no interrupted transaction available\n"))
1370 self.ui.warn(_("no interrupted transaction available\n"))
1371 return False
1371 return False
1372
1372
1373 def rollback(self, dryrun=False, force=False):
1373 def rollback(self, dryrun=False, force=False):
1374 wlock = lock = dsguard = None
1374 wlock = lock = dsguard = None
1375 try:
1375 try:
1376 wlock = self.wlock()
1376 wlock = self.wlock()
1377 lock = self.lock()
1377 lock = self.lock()
1378 if self.svfs.exists("undo"):
1378 if self.svfs.exists("undo"):
1379 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1379 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1380
1380
1381 return self._rollback(dryrun, force, dsguard)
1381 return self._rollback(dryrun, force, dsguard)
1382 else:
1382 else:
1383 self.ui.warn(_("no rollback information available\n"))
1383 self.ui.warn(_("no rollback information available\n"))
1384 return 1
1384 return 1
1385 finally:
1385 finally:
1386 release(dsguard, lock, wlock)
1386 release(dsguard, lock, wlock)
1387
1387
1388 @unfilteredmethod # Until we get smarter cache management
1388 @unfilteredmethod # Until we get smarter cache management
1389 def _rollback(self, dryrun, force, dsguard):
1389 def _rollback(self, dryrun, force, dsguard):
1390 ui = self.ui
1390 ui = self.ui
1391 try:
1391 try:
1392 args = self.vfs.read('undo.desc').splitlines()
1392 args = self.vfs.read('undo.desc').splitlines()
1393 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1393 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1394 if len(args) >= 3:
1394 if len(args) >= 3:
1395 detail = args[2]
1395 detail = args[2]
1396 oldtip = oldlen - 1
1396 oldtip = oldlen - 1
1397
1397
1398 if detail and ui.verbose:
1398 if detail and ui.verbose:
1399 msg = (_('repository tip rolled back to revision %d'
1399 msg = (_('repository tip rolled back to revision %d'
1400 ' (undo %s: %s)\n')
1400 ' (undo %s: %s)\n')
1401 % (oldtip, desc, detail))
1401 % (oldtip, desc, detail))
1402 else:
1402 else:
1403 msg = (_('repository tip rolled back to revision %d'
1403 msg = (_('repository tip rolled back to revision %d'
1404 ' (undo %s)\n')
1404 ' (undo %s)\n')
1405 % (oldtip, desc))
1405 % (oldtip, desc))
1406 except IOError:
1406 except IOError:
1407 msg = _('rolling back unknown transaction\n')
1407 msg = _('rolling back unknown transaction\n')
1408 desc = None
1408 desc = None
1409
1409
1410 if not force and self['.'] != self['tip'] and desc == 'commit':
1410 if not force and self['.'] != self['tip'] and desc == 'commit':
1411 raise error.Abort(
1411 raise error.Abort(
1412 _('rollback of last commit while not checked out '
1412 _('rollback of last commit while not checked out '
1413 'may lose data'), hint=_('use -f to force'))
1413 'may lose data'), hint=_('use -f to force'))
1414
1414
1415 ui.status(msg)
1415 ui.status(msg)
1416 if dryrun:
1416 if dryrun:
1417 return 0
1417 return 0
1418
1418
1419 parents = self.dirstate.parents()
1419 parents = self.dirstate.parents()
1420 self.destroying()
1420 self.destroying()
1421 vfsmap = {'plain': self.vfs, '': self.svfs}
1421 vfsmap = {'plain': self.vfs, '': self.svfs}
1422 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1422 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1423 checkambigfiles=_cachedfiles)
1423 checkambigfiles=_cachedfiles)
1424 if self.vfs.exists('undo.bookmarks'):
1424 if self.vfs.exists('undo.bookmarks'):
1425 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1425 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1426 if self.svfs.exists('undo.phaseroots'):
1426 if self.svfs.exists('undo.phaseroots'):
1427 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1427 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1428 self.invalidate()
1428 self.invalidate()
1429
1429
1430 parentgone = (parents[0] not in self.changelog.nodemap or
1430 parentgone = (parents[0] not in self.changelog.nodemap or
1431 parents[1] not in self.changelog.nodemap)
1431 parents[1] not in self.changelog.nodemap)
1432 if parentgone:
1432 if parentgone:
1433 # prevent dirstateguard from overwriting already restored one
1433 # prevent dirstateguard from overwriting already restored one
1434 dsguard.close()
1434 dsguard.close()
1435
1435
1436 self.dirstate.restorebackup(None, 'undo.dirstate')
1436 self.dirstate.restorebackup(None, 'undo.dirstate')
1437 try:
1437 try:
1438 branch = self.vfs.read('undo.branch')
1438 branch = self.vfs.read('undo.branch')
1439 self.dirstate.setbranch(encoding.tolocal(branch))
1439 self.dirstate.setbranch(encoding.tolocal(branch))
1440 except IOError:
1440 except IOError:
1441 ui.warn(_('named branch could not be reset: '
1441 ui.warn(_('named branch could not be reset: '
1442 'current branch is still \'%s\'\n')
1442 'current branch is still \'%s\'\n')
1443 % self.dirstate.branch())
1443 % self.dirstate.branch())
1444
1444
1445 parents = tuple([p.rev() for p in self[None].parents()])
1445 parents = tuple([p.rev() for p in self[None].parents()])
1446 if len(parents) > 1:
1446 if len(parents) > 1:
1447 ui.status(_('working directory now based on '
1447 ui.status(_('working directory now based on '
1448 'revisions %d and %d\n') % parents)
1448 'revisions %d and %d\n') % parents)
1449 else:
1449 else:
1450 ui.status(_('working directory now based on '
1450 ui.status(_('working directory now based on '
1451 'revision %d\n') % parents)
1451 'revision %d\n') % parents)
1452 mergemod.mergestate.clean(self, self['.'].node())
1452 mergemod.mergestate.clean(self, self['.'].node())
1453
1453
1454 # TODO: if we know which new heads may result from this rollback, pass
1454 # TODO: if we know which new heads may result from this rollback, pass
1455 # them to destroy(), which will prevent the branchhead cache from being
1455 # them to destroy(), which will prevent the branchhead cache from being
1456 # invalidated.
1456 # invalidated.
1457 self.destroyed()
1457 self.destroyed()
1458 return 0
1458 return 0
1459
1459
1460 def _buildcacheupdater(self, newtransaction):
1460 def _buildcacheupdater(self, newtransaction):
1461 """called during transaction to build the callback updating cache
1461 """called during transaction to build the callback updating cache
1462
1462
1463 Lives on the repository to help extension who might want to augment
1463 Lives on the repository to help extension who might want to augment
1464 this logic. For this purpose, the created transaction is passed to the
1464 this logic. For this purpose, the created transaction is passed to the
1465 method.
1465 method.
1466 """
1466 """
1467 # we must avoid cyclic reference between repo and transaction.
1467 # we must avoid cyclic reference between repo and transaction.
1468 reporef = weakref.ref(self)
1468 reporef = weakref.ref(self)
1469 def updater(tr):
1469 def updater(tr):
1470 repo = reporef()
1470 repo = reporef()
1471 repo.updatecaches(tr)
1471 repo.updatecaches(tr)
1472 return updater
1472 return updater
1473
1473
1474 @unfilteredmethod
1474 @unfilteredmethod
1475 def updatecaches(self, tr=None):
1475 def updatecaches(self, tr=None):
1476 """warm appropriate caches
1476 """warm appropriate caches
1477
1477
1478 If this function is called after a transaction closed. The transaction
1478 If this function is called after a transaction closed. The transaction
1479 will be available in the 'tr' argument. This can be used to selectively
1479 will be available in the 'tr' argument. This can be used to selectively
1480 update caches relevant to the changes in that transaction.
1480 update caches relevant to the changes in that transaction.
1481 """
1481 """
1482 if tr is not None and tr.hookargs.get('source') == 'strip':
1482 if tr is not None and tr.hookargs.get('source') == 'strip':
1483 # During strip, many caches are invalid but
1483 # During strip, many caches are invalid but
1484 # later call to `destroyed` will refresh them.
1484 # later call to `destroyed` will refresh them.
1485 return
1485 return
1486
1486
1487 if tr is None or tr.changes['revs']:
1487 if tr is None or tr.changes['revs']:
1488 # updating the unfiltered branchmap should refresh all the others,
1488 # updating the unfiltered branchmap should refresh all the others,
1489 self.ui.debug('updating the branch cache\n')
1489 self.ui.debug('updating the branch cache\n')
1490 branchmap.updatecache(self.filtered('served'))
1490 branchmap.updatecache(self.filtered('served'))
1491
1491
1492 def invalidatecaches(self):
1492 def invalidatecaches(self):
1493
1493
1494 if '_tagscache' in vars(self):
1494 if '_tagscache' in vars(self):
1495 # can't use delattr on proxy
1495 # can't use delattr on proxy
1496 del self.__dict__['_tagscache']
1496 del self.__dict__['_tagscache']
1497
1497
1498 self.unfiltered()._branchcaches.clear()
1498 self.unfiltered()._branchcaches.clear()
1499 self.invalidatevolatilesets()
1499 self.invalidatevolatilesets()
1500 self._sparsesignaturecache.clear()
1500 self._sparsesignaturecache.clear()
1501
1501
1502 def invalidatevolatilesets(self):
1502 def invalidatevolatilesets(self):
1503 self.filteredrevcache.clear()
1503 self.filteredrevcache.clear()
1504 obsolete.clearobscaches(self)
1504 obsolete.clearobscaches(self)
1505
1505
1506 def invalidatedirstate(self):
1506 def invalidatedirstate(self):
1507 '''Invalidates the dirstate, causing the next call to dirstate
1507 '''Invalidates the dirstate, causing the next call to dirstate
1508 to check if it was modified since the last time it was read,
1508 to check if it was modified since the last time it was read,
1509 rereading it if it has.
1509 rereading it if it has.
1510
1510
1511 This is different to dirstate.invalidate() that it doesn't always
1511 This is different to dirstate.invalidate() that it doesn't always
1512 rereads the dirstate. Use dirstate.invalidate() if you want to
1512 rereads the dirstate. Use dirstate.invalidate() if you want to
1513 explicitly read the dirstate again (i.e. restoring it to a previous
1513 explicitly read the dirstate again (i.e. restoring it to a previous
1514 known good state).'''
1514 known good state).'''
1515 if hasunfilteredcache(self, 'dirstate'):
1515 if hasunfilteredcache(self, 'dirstate'):
1516 for k in self.dirstate._filecache:
1516 for k in self.dirstate._filecache:
1517 try:
1517 try:
1518 delattr(self.dirstate, k)
1518 delattr(self.dirstate, k)
1519 except AttributeError:
1519 except AttributeError:
1520 pass
1520 pass
1521 delattr(self.unfiltered(), 'dirstate')
1521 delattr(self.unfiltered(), 'dirstate')
1522
1522
1523 def invalidate(self, clearfilecache=False):
1523 def invalidate(self, clearfilecache=False):
1524 '''Invalidates both store and non-store parts other than dirstate
1524 '''Invalidates both store and non-store parts other than dirstate
1525
1525
1526 If a transaction is running, invalidation of store is omitted,
1526 If a transaction is running, invalidation of store is omitted,
1527 because discarding in-memory changes might cause inconsistency
1527 because discarding in-memory changes might cause inconsistency
1528 (e.g. incomplete fncache causes unintentional failure, but
1528 (e.g. incomplete fncache causes unintentional failure, but
1529 redundant one doesn't).
1529 redundant one doesn't).
1530 '''
1530 '''
1531 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1531 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1532 for k in list(self._filecache.keys()):
1532 for k in list(self._filecache.keys()):
1533 # dirstate is invalidated separately in invalidatedirstate()
1533 # dirstate is invalidated separately in invalidatedirstate()
1534 if k == 'dirstate':
1534 if k == 'dirstate':
1535 continue
1535 continue
1536 if (k == 'changelog' and
1536 if (k == 'changelog' and
1537 self.currenttransaction() and
1537 self.currenttransaction() and
1538 self.changelog._delayed):
1538 self.changelog._delayed):
1539 # The changelog object may store unwritten revisions. We don't
1539 # The changelog object may store unwritten revisions. We don't
1540 # want to lose them.
1540 # want to lose them.
1541 # TODO: Solve the problem instead of working around it.
1541 # TODO: Solve the problem instead of working around it.
1542 continue
1542 continue
1543
1543
1544 if clearfilecache:
1544 if clearfilecache:
1545 del self._filecache[k]
1545 del self._filecache[k]
1546 try:
1546 try:
1547 delattr(unfiltered, k)
1547 delattr(unfiltered, k)
1548 except AttributeError:
1548 except AttributeError:
1549 pass
1549 pass
1550 self.invalidatecaches()
1550 self.invalidatecaches()
1551 if not self.currenttransaction():
1551 if not self.currenttransaction():
1552 # TODO: Changing contents of store outside transaction
1552 # TODO: Changing contents of store outside transaction
1553 # causes inconsistency. We should make in-memory store
1553 # causes inconsistency. We should make in-memory store
1554 # changes detectable, and abort if changed.
1554 # changes detectable, and abort if changed.
1555 self.store.invalidatecaches()
1555 self.store.invalidatecaches()
1556
1556
1557 def invalidateall(self):
1557 def invalidateall(self):
1558 '''Fully invalidates both store and non-store parts, causing the
1558 '''Fully invalidates both store and non-store parts, causing the
1559 subsequent operation to reread any outside changes.'''
1559 subsequent operation to reread any outside changes.'''
1560 # extension should hook this to invalidate its caches
1560 # extension should hook this to invalidate its caches
1561 self.invalidate()
1561 self.invalidate()
1562 self.invalidatedirstate()
1562 self.invalidatedirstate()
1563
1563
1564 @unfilteredmethod
1564 @unfilteredmethod
1565 def _refreshfilecachestats(self, tr):
1565 def _refreshfilecachestats(self, tr):
1566 """Reload stats of cached files so that they are flagged as valid"""
1566 """Reload stats of cached files so that they are flagged as valid"""
1567 for k, ce in self._filecache.items():
1567 for k, ce in self._filecache.items():
1568 if k == 'dirstate' or k not in self.__dict__:
1568 if k == 'dirstate' or k not in self.__dict__:
1569 continue
1569 continue
1570 ce.refresh()
1570 ce.refresh()
1571
1571
1572 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1572 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1573 inheritchecker=None, parentenvvar=None):
1573 inheritchecker=None, parentenvvar=None):
1574 parentlock = None
1574 parentlock = None
1575 # the contents of parentenvvar are used by the underlying lock to
1575 # the contents of parentenvvar are used by the underlying lock to
1576 # determine whether it can be inherited
1576 # determine whether it can be inherited
1577 if parentenvvar is not None:
1577 if parentenvvar is not None:
1578 parentlock = encoding.environ.get(parentenvvar)
1578 parentlock = encoding.environ.get(parentenvvar)
1579
1579
1580 timeout = 0
1580 timeout = 0
1581 warntimeout = 0
1581 warntimeout = 0
1582 if wait:
1582 if wait:
1583 timeout = self.ui.configint("ui", "timeout")
1583 timeout = self.ui.configint("ui", "timeout")
1584 warntimeout = self.ui.configint("ui", "timeout.warn")
1584 warntimeout = self.ui.configint("ui", "timeout.warn")
1585
1585
1586 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1586 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1587 releasefn=releasefn,
1587 releasefn=releasefn,
1588 acquirefn=acquirefn, desc=desc,
1588 acquirefn=acquirefn, desc=desc,
1589 inheritchecker=inheritchecker,
1589 inheritchecker=inheritchecker,
1590 parentlock=parentlock)
1590 parentlock=parentlock)
1591 return l
1591 return l
1592
1592
1593 def _afterlock(self, callback):
1593 def _afterlock(self, callback):
1594 """add a callback to be run when the repository is fully unlocked
1594 """add a callback to be run when the repository is fully unlocked
1595
1595
1596 The callback will be executed when the outermost lock is released
1596 The callback will be executed when the outermost lock is released
1597 (with wlock being higher level than 'lock')."""
1597 (with wlock being higher level than 'lock')."""
1598 for ref in (self._wlockref, self._lockref):
1598 for ref in (self._wlockref, self._lockref):
1599 l = ref and ref()
1599 l = ref and ref()
1600 if l and l.held:
1600 if l and l.held:
1601 l.postrelease.append(callback)
1601 l.postrelease.append(callback)
1602 break
1602 break
1603 else: # no lock have been found.
1603 else: # no lock have been found.
1604 callback()
1604 callback()
1605
1605
1606 def lock(self, wait=True):
1606 def lock(self, wait=True):
1607 '''Lock the repository store (.hg/store) and return a weak reference
1607 '''Lock the repository store (.hg/store) and return a weak reference
1608 to the lock. Use this before modifying the store (e.g. committing or
1608 to the lock. Use this before modifying the store (e.g. committing or
1609 stripping). If you are opening a transaction, get a lock as well.)
1609 stripping). If you are opening a transaction, get a lock as well.)
1610
1610
1611 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1611 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1612 'wlock' first to avoid a dead-lock hazard.'''
1612 'wlock' first to avoid a dead-lock hazard.'''
1613 l = self._currentlock(self._lockref)
1613 l = self._currentlock(self._lockref)
1614 if l is not None:
1614 if l is not None:
1615 l.lock()
1615 l.lock()
1616 return l
1616 return l
1617
1617
1618 l = self._lock(self.svfs, "lock", wait, None,
1618 l = self._lock(self.svfs, "lock", wait, None,
1619 self.invalidate, _('repository %s') % self.origroot)
1619 self.invalidate, _('repository %s') % self.origroot)
1620 self._lockref = weakref.ref(l)
1620 self._lockref = weakref.ref(l)
1621 return l
1621 return l
1622
1622
1623 def _wlockchecktransaction(self):
1623 def _wlockchecktransaction(self):
1624 if self.currenttransaction() is not None:
1624 if self.currenttransaction() is not None:
1625 raise error.LockInheritanceContractViolation(
1625 raise error.LockInheritanceContractViolation(
1626 'wlock cannot be inherited in the middle of a transaction')
1626 'wlock cannot be inherited in the middle of a transaction')
1627
1627
1628 def wlock(self, wait=True):
1628 def wlock(self, wait=True):
1629 '''Lock the non-store parts of the repository (everything under
1629 '''Lock the non-store parts of the repository (everything under
1630 .hg except .hg/store) and return a weak reference to the lock.
1630 .hg except .hg/store) and return a weak reference to the lock.
1631
1631
1632 Use this before modifying files in .hg.
1632 Use this before modifying files in .hg.
1633
1633
1634 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1634 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1635 'wlock' first to avoid a dead-lock hazard.'''
1635 'wlock' first to avoid a dead-lock hazard.'''
1636 l = self._wlockref and self._wlockref()
1636 l = self._wlockref and self._wlockref()
1637 if l is not None and l.held:
1637 if l is not None and l.held:
1638 l.lock()
1638 l.lock()
1639 return l
1639 return l
1640
1640
1641 # We do not need to check for non-waiting lock acquisition. Such
1641 # We do not need to check for non-waiting lock acquisition. Such
1642 # acquisition would not cause dead-lock as they would just fail.
1642 # acquisition would not cause dead-lock as they would just fail.
1643 if wait and (self.ui.configbool('devel', 'all-warnings')
1643 if wait and (self.ui.configbool('devel', 'all-warnings')
1644 or self.ui.configbool('devel', 'check-locks')):
1644 or self.ui.configbool('devel', 'check-locks')):
1645 if self._currentlock(self._lockref) is not None:
1645 if self._currentlock(self._lockref) is not None:
1646 self.ui.develwarn('"wlock" acquired after "lock"')
1646 self.ui.develwarn('"wlock" acquired after "lock"')
1647
1647
1648 def unlock():
1648 def unlock():
1649 if self.dirstate.pendingparentchange():
1649 if self.dirstate.pendingparentchange():
1650 self.dirstate.invalidate()
1650 self.dirstate.invalidate()
1651 else:
1651 else:
1652 self.dirstate.write(None)
1652 self.dirstate.write(None)
1653
1653
1654 self._filecache['dirstate'].refresh()
1654 self._filecache['dirstate'].refresh()
1655
1655
1656 l = self._lock(self.vfs, "wlock", wait, unlock,
1656 l = self._lock(self.vfs, "wlock", wait, unlock,
1657 self.invalidatedirstate, _('working directory of %s') %
1657 self.invalidatedirstate, _('working directory of %s') %
1658 self.origroot,
1658 self.origroot,
1659 inheritchecker=self._wlockchecktransaction,
1659 inheritchecker=self._wlockchecktransaction,
1660 parentenvvar='HG_WLOCK_LOCKER')
1660 parentenvvar='HG_WLOCK_LOCKER')
1661 self._wlockref = weakref.ref(l)
1661 self._wlockref = weakref.ref(l)
1662 return l
1662 return l
1663
1663
1664 def _currentlock(self, lockref):
1664 def _currentlock(self, lockref):
1665 """Returns the lock if it's held, or None if it's not."""
1665 """Returns the lock if it's held, or None if it's not."""
1666 if lockref is None:
1666 if lockref is None:
1667 return None
1667 return None
1668 l = lockref()
1668 l = lockref()
1669 if l is None or not l.held:
1669 if l is None or not l.held:
1670 return None
1670 return None
1671 return l
1671 return l
1672
1672
1673 def currentwlock(self):
1673 def currentwlock(self):
1674 """Returns the wlock if it's held, or None if it's not."""
1674 """Returns the wlock if it's held, or None if it's not."""
1675 return self._currentlock(self._wlockref)
1675 return self._currentlock(self._wlockref)
1676
1676
1677 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1677 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1678 """
1678 """
1679 commit an individual file as part of a larger transaction
1679 commit an individual file as part of a larger transaction
1680 """
1680 """
1681
1681
1682 fname = fctx.path()
1682 fname = fctx.path()
1683 fparent1 = manifest1.get(fname, nullid)
1683 fparent1 = manifest1.get(fname, nullid)
1684 fparent2 = manifest2.get(fname, nullid)
1684 fparent2 = manifest2.get(fname, nullid)
1685 if isinstance(fctx, context.filectx):
1685 if isinstance(fctx, context.filectx):
1686 node = fctx.filenode()
1686 node = fctx.filenode()
1687 if node in [fparent1, fparent2]:
1687 if node in [fparent1, fparent2]:
1688 self.ui.debug('reusing %s filelog entry\n' % fname)
1688 self.ui.debug('reusing %s filelog entry\n' % fname)
1689 if manifest1.flags(fname) != fctx.flags():
1689 if manifest1.flags(fname) != fctx.flags():
1690 changelist.append(fname)
1690 changelist.append(fname)
1691 return node
1691 return node
1692
1692
1693 flog = self.file(fname)
1693 flog = self.file(fname)
1694 meta = {}
1694 meta = {}
1695 copy = fctx.renamed()
1695 copy = fctx.renamed()
1696 if copy and copy[0] != fname:
1696 if copy and copy[0] != fname:
1697 # Mark the new revision of this file as a copy of another
1697 # Mark the new revision of this file as a copy of another
1698 # file. This copy data will effectively act as a parent
1698 # file. This copy data will effectively act as a parent
1699 # of this new revision. If this is a merge, the first
1699 # of this new revision. If this is a merge, the first
1700 # parent will be the nullid (meaning "look up the copy data")
1700 # parent will be the nullid (meaning "look up the copy data")
1701 # and the second one will be the other parent. For example:
1701 # and the second one will be the other parent. For example:
1702 #
1702 #
1703 # 0 --- 1 --- 3 rev1 changes file foo
1703 # 0 --- 1 --- 3 rev1 changes file foo
1704 # \ / rev2 renames foo to bar and changes it
1704 # \ / rev2 renames foo to bar and changes it
1705 # \- 2 -/ rev3 should have bar with all changes and
1705 # \- 2 -/ rev3 should have bar with all changes and
1706 # should record that bar descends from
1706 # should record that bar descends from
1707 # bar in rev2 and foo in rev1
1707 # bar in rev2 and foo in rev1
1708 #
1708 #
1709 # this allows this merge to succeed:
1709 # this allows this merge to succeed:
1710 #
1710 #
1711 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1711 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1712 # \ / merging rev3 and rev4 should use bar@rev2
1712 # \ / merging rev3 and rev4 should use bar@rev2
1713 # \- 2 --- 4 as the merge base
1713 # \- 2 --- 4 as the merge base
1714 #
1714 #
1715
1715
1716 cfname = copy[0]
1716 cfname = copy[0]
1717 crev = manifest1.get(cfname)
1717 crev = manifest1.get(cfname)
1718 newfparent = fparent2
1718 newfparent = fparent2
1719
1719
1720 if manifest2: # branch merge
1720 if manifest2: # branch merge
1721 if fparent2 == nullid or crev is None: # copied on remote side
1721 if fparent2 == nullid or crev is None: # copied on remote side
1722 if cfname in manifest2:
1722 if cfname in manifest2:
1723 crev = manifest2[cfname]
1723 crev = manifest2[cfname]
1724 newfparent = fparent1
1724 newfparent = fparent1
1725
1725
1726 # Here, we used to search backwards through history to try to find
1726 # Here, we used to search backwards through history to try to find
1727 # where the file copy came from if the source of a copy was not in
1727 # where the file copy came from if the source of a copy was not in
1728 # the parent directory. However, this doesn't actually make sense to
1728 # the parent directory. However, this doesn't actually make sense to
1729 # do (what does a copy from something not in your working copy even
1729 # do (what does a copy from something not in your working copy even
1730 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1730 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1731 # the user that copy information was dropped, so if they didn't
1731 # the user that copy information was dropped, so if they didn't
1732 # expect this outcome it can be fixed, but this is the correct
1732 # expect this outcome it can be fixed, but this is the correct
1733 # behavior in this circumstance.
1733 # behavior in this circumstance.
1734
1734
1735 if crev:
1735 if crev:
1736 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1736 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1737 meta["copy"] = cfname
1737 meta["copy"] = cfname
1738 meta["copyrev"] = hex(crev)
1738 meta["copyrev"] = hex(crev)
1739 fparent1, fparent2 = nullid, newfparent
1739 fparent1, fparent2 = nullid, newfparent
1740 else:
1740 else:
1741 self.ui.warn(_("warning: can't find ancestor for '%s' "
1741 self.ui.warn(_("warning: can't find ancestor for '%s' "
1742 "copied from '%s'!\n") % (fname, cfname))
1742 "copied from '%s'!\n") % (fname, cfname))
1743
1743
1744 elif fparent1 == nullid:
1744 elif fparent1 == nullid:
1745 fparent1, fparent2 = fparent2, nullid
1745 fparent1, fparent2 = fparent2, nullid
1746 elif fparent2 != nullid:
1746 elif fparent2 != nullid:
1747 # is one parent an ancestor of the other?
1747 # is one parent an ancestor of the other?
1748 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1748 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1749 if fparent1 in fparentancestors:
1749 if fparent1 in fparentancestors:
1750 fparent1, fparent2 = fparent2, nullid
1750 fparent1, fparent2 = fparent2, nullid
1751 elif fparent2 in fparentancestors:
1751 elif fparent2 in fparentancestors:
1752 fparent2 = nullid
1752 fparent2 = nullid
1753
1753
1754 # is the file changed?
1754 # is the file changed?
1755 text = fctx.data()
1755 text = fctx.data()
1756 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1756 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1757 changelist.append(fname)
1757 changelist.append(fname)
1758 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1758 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1759 # are just the flags changed during merge?
1759 # are just the flags changed during merge?
1760 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1760 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1761 changelist.append(fname)
1761 changelist.append(fname)
1762
1762
1763 return fparent1
1763 return fparent1
1764
1764
1765 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1765 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1766 """check for commit arguments that aren't committable"""
1766 """check for commit arguments that aren't committable"""
1767 if match.isexact() or match.prefix():
1767 if match.isexact() or match.prefix():
1768 matched = set(status.modified + status.added + status.removed)
1768 matched = set(status.modified + status.added + status.removed)
1769
1769
1770 for f in match.files():
1770 for f in match.files():
1771 f = self.dirstate.normalize(f)
1771 f = self.dirstate.normalize(f)
1772 if f == '.' or f in matched or f in wctx.substate:
1772 if f == '.' or f in matched or f in wctx.substate:
1773 continue
1773 continue
1774 if f in status.deleted:
1774 if f in status.deleted:
1775 fail(f, _('file not found!'))
1775 fail(f, _('file not found!'))
1776 if f in vdirs: # visited directory
1776 if f in vdirs: # visited directory
1777 d = f + '/'
1777 d = f + '/'
1778 for mf in matched:
1778 for mf in matched:
1779 if mf.startswith(d):
1779 if mf.startswith(d):
1780 break
1780 break
1781 else:
1781 else:
1782 fail(f, _("no match under directory!"))
1782 fail(f, _("no match under directory!"))
1783 elif f not in self.dirstate:
1783 elif f not in self.dirstate:
1784 fail(f, _("file not tracked!"))
1784 fail(f, _("file not tracked!"))
1785
1785
1786 @unfilteredmethod
1786 @unfilteredmethod
1787 def commit(self, text="", user=None, date=None, match=None, force=False,
1787 def commit(self, text="", user=None, date=None, match=None, force=False,
1788 editor=False, extra=None):
1788 editor=False, extra=None):
1789 """Add a new revision to current repository.
1789 """Add a new revision to current repository.
1790
1790
1791 Revision information is gathered from the working directory,
1791 Revision information is gathered from the working directory,
1792 match can be used to filter the committed files. If editor is
1792 match can be used to filter the committed files. If editor is
1793 supplied, it is called to get a commit message.
1793 supplied, it is called to get a commit message.
1794 """
1794 """
1795 if extra is None:
1795 if extra is None:
1796 extra = {}
1796 extra = {}
1797
1797
1798 def fail(f, msg):
1798 def fail(f, msg):
1799 raise error.Abort('%s: %s' % (f, msg))
1799 raise error.Abort('%s: %s' % (f, msg))
1800
1800
1801 if not match:
1801 if not match:
1802 match = matchmod.always(self.root, '')
1802 match = matchmod.always(self.root, '')
1803
1803
1804 if not force:
1804 if not force:
1805 vdirs = []
1805 vdirs = []
1806 match.explicitdir = vdirs.append
1806 match.explicitdir = vdirs.append
1807 match.bad = fail
1807 match.bad = fail
1808
1808
1809 wlock = lock = tr = None
1809 wlock = lock = tr = None
1810 try:
1810 try:
1811 wlock = self.wlock()
1811 wlock = self.wlock()
1812 lock = self.lock() # for recent changelog (see issue4368)
1812 lock = self.lock() # for recent changelog (see issue4368)
1813
1813
1814 wctx = self[None]
1814 wctx = self[None]
1815 merge = len(wctx.parents()) > 1
1815 merge = len(wctx.parents()) > 1
1816
1816
1817 if not force and merge and not match.always():
1817 if not force and merge and not match.always():
1818 raise error.Abort(_('cannot partially commit a merge '
1818 raise error.Abort(_('cannot partially commit a merge '
1819 '(do not specify files or patterns)'))
1819 '(do not specify files or patterns)'))
1820
1820
1821 status = self.status(match=match, clean=force)
1821 status = self.status(match=match, clean=force)
1822 if force:
1822 if force:
1823 status.modified.extend(status.clean) # mq may commit clean files
1823 status.modified.extend(status.clean) # mq may commit clean files
1824
1824
1825 # check subrepos
1825 # check subrepos
1826 subs, commitsubs, newstate = subrepo.precommit(
1826 subs, commitsubs, newstate = subrepo.precommit(
1827 self.ui, wctx, status, match, force=force)
1827 self.ui, wctx, status, match, force=force)
1828
1828
1829 # make sure all explicit patterns are matched
1829 # make sure all explicit patterns are matched
1830 if not force:
1830 if not force:
1831 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1831 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1832
1832
1833 cctx = context.workingcommitctx(self, status,
1833 cctx = context.workingcommitctx(self, status,
1834 text, user, date, extra)
1834 text, user, date, extra)
1835
1835
1836 # internal config: ui.allowemptycommit
1836 # internal config: ui.allowemptycommit
1837 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1837 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1838 or extra.get('close') or merge or cctx.files()
1838 or extra.get('close') or merge or cctx.files()
1839 or self.ui.configbool('ui', 'allowemptycommit'))
1839 or self.ui.configbool('ui', 'allowemptycommit'))
1840 if not allowemptycommit:
1840 if not allowemptycommit:
1841 return None
1841 return None
1842
1842
1843 if merge and cctx.deleted():
1843 if merge and cctx.deleted():
1844 raise error.Abort(_("cannot commit merge with missing files"))
1844 raise error.Abort(_("cannot commit merge with missing files"))
1845
1845
1846 ms = mergemod.mergestate.read(self)
1846 ms = mergemod.mergestate.read(self)
1847 mergeutil.checkunresolved(ms)
1847 mergeutil.checkunresolved(ms)
1848
1848
1849 if editor:
1849 if editor:
1850 cctx._text = editor(self, cctx, subs)
1850 cctx._text = editor(self, cctx, subs)
1851 edited = (text != cctx._text)
1851 edited = (text != cctx._text)
1852
1852
1853 # Save commit message in case this transaction gets rolled back
1853 # Save commit message in case this transaction gets rolled back
1854 # (e.g. by a pretxncommit hook). Leave the content alone on
1854 # (e.g. by a pretxncommit hook). Leave the content alone on
1855 # the assumption that the user will use the same editor again.
1855 # the assumption that the user will use the same editor again.
1856 msgfn = self.savecommitmessage(cctx._text)
1856 msgfn = self.savecommitmessage(cctx._text)
1857
1857
1858 # commit subs and write new state
1858 # commit subs and write new state
1859 if subs:
1859 if subs:
1860 for s in sorted(commitsubs):
1860 for s in sorted(commitsubs):
1861 sub = wctx.sub(s)
1861 sub = wctx.sub(s)
1862 self.ui.status(_('committing subrepository %s\n') %
1862 self.ui.status(_('committing subrepository %s\n') %
1863 subrepo.subrelpath(sub))
1863 subrepo.subrelpath(sub))
1864 sr = sub.commit(cctx._text, user, date)
1864 sr = sub.commit(cctx._text, user, date)
1865 newstate[s] = (newstate[s][0], sr)
1865 newstate[s] = (newstate[s][0], sr)
1866 subrepo.writestate(self, newstate)
1866 subrepo.writestate(self, newstate)
1867
1867
1868 p1, p2 = self.dirstate.parents()
1868 p1, p2 = self.dirstate.parents()
1869 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1869 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1870 try:
1870 try:
1871 self.hook("precommit", throw=True, parent1=hookp1,
1871 self.hook("precommit", throw=True, parent1=hookp1,
1872 parent2=hookp2)
1872 parent2=hookp2)
1873 tr = self.transaction('commit')
1873 tr = self.transaction('commit')
1874 ret = self.commitctx(cctx, True)
1874 ret = self.commitctx(cctx, True)
1875 except: # re-raises
1875 except: # re-raises
1876 if edited:
1876 if edited:
1877 self.ui.write(
1877 self.ui.write(
1878 _('note: commit message saved in %s\n') % msgfn)
1878 _('note: commit message saved in %s\n') % msgfn)
1879 raise
1879 raise
1880 # update bookmarks, dirstate and mergestate
1880 # update bookmarks, dirstate and mergestate
1881 bookmarks.update(self, [p1, p2], ret)
1881 bookmarks.update(self, [p1, p2], ret)
1882 cctx.markcommitted(ret)
1882 cctx.markcommitted(ret)
1883 ms.reset()
1883 ms.reset()
1884 tr.close()
1884 tr.close()
1885
1885
1886 finally:
1886 finally:
1887 lockmod.release(tr, lock, wlock)
1887 lockmod.release(tr, lock, wlock)
1888
1888
1889 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1889 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1890 # hack for command that use a temporary commit (eg: histedit)
1890 # hack for command that use a temporary commit (eg: histedit)
1891 # temporary commit got stripped before hook release
1891 # temporary commit got stripped before hook release
1892 if self.changelog.hasnode(ret):
1892 if self.changelog.hasnode(ret):
1893 self.hook("commit", node=node, parent1=parent1,
1893 self.hook("commit", node=node, parent1=parent1,
1894 parent2=parent2)
1894 parent2=parent2)
1895 self._afterlock(commithook)
1895 self._afterlock(commithook)
1896 return ret
1896 return ret
1897
1897
1898 @unfilteredmethod
1898 @unfilteredmethod
1899 def commitctx(self, ctx, error=False):
1899 def commitctx(self, ctx, error=False):
1900 """Add a new revision to current repository.
1900 """Add a new revision to current repository.
1901 Revision information is passed via the context argument.
1901 Revision information is passed via the context argument.
1902 """
1902 """
1903
1903
1904 tr = None
1904 tr = None
1905 p1, p2 = ctx.p1(), ctx.p2()
1905 p1, p2 = ctx.p1(), ctx.p2()
1906 user = ctx.user()
1906 user = ctx.user()
1907
1907
1908 lock = self.lock()
1908 lock = self.lock()
1909 try:
1909 try:
1910 tr = self.transaction("commit")
1910 tr = self.transaction("commit")
1911 trp = weakref.proxy(tr)
1911 trp = weakref.proxy(tr)
1912
1912
1913 if ctx.manifestnode():
1913 if ctx.manifestnode():
1914 # reuse an existing manifest revision
1914 # reuse an existing manifest revision
1915 mn = ctx.manifestnode()
1915 mn = ctx.manifestnode()
1916 files = ctx.files()
1916 files = ctx.files()
1917 elif ctx.files():
1917 elif ctx.files():
1918 m1ctx = p1.manifestctx()
1918 m1ctx = p1.manifestctx()
1919 m2ctx = p2.manifestctx()
1919 m2ctx = p2.manifestctx()
1920 mctx = m1ctx.copy()
1920 mctx = m1ctx.copy()
1921
1921
1922 m = mctx.read()
1922 m = mctx.read()
1923 m1 = m1ctx.read()
1923 m1 = m1ctx.read()
1924 m2 = m2ctx.read()
1924 m2 = m2ctx.read()
1925
1925
1926 # check in files
1926 # check in files
1927 added = []
1927 added = []
1928 changed = []
1928 changed = []
1929 removed = list(ctx.removed())
1929 removed = list(ctx.removed())
1930 linkrev = len(self)
1930 linkrev = len(self)
1931 self.ui.note(_("committing files:\n"))
1931 self.ui.note(_("committing files:\n"))
1932 for f in sorted(ctx.modified() + ctx.added()):
1932 for f in sorted(ctx.modified() + ctx.added()):
1933 self.ui.note(f + "\n")
1933 self.ui.note(f + "\n")
1934 try:
1934 try:
1935 fctx = ctx[f]
1935 fctx = ctx[f]
1936 if fctx is None:
1936 if fctx is None:
1937 removed.append(f)
1937 removed.append(f)
1938 else:
1938 else:
1939 added.append(f)
1939 added.append(f)
1940 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1940 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1941 trp, changed)
1941 trp, changed)
1942 m.setflag(f, fctx.flags())
1942 m.setflag(f, fctx.flags())
1943 except OSError as inst:
1943 except OSError as inst:
1944 self.ui.warn(_("trouble committing %s!\n") % f)
1944 self.ui.warn(_("trouble committing %s!\n") % f)
1945 raise
1945 raise
1946 except IOError as inst:
1946 except IOError as inst:
1947 errcode = getattr(inst, 'errno', errno.ENOENT)
1947 errcode = getattr(inst, 'errno', errno.ENOENT)
1948 if error or errcode and errcode != errno.ENOENT:
1948 if error or errcode and errcode != errno.ENOENT:
1949 self.ui.warn(_("trouble committing %s!\n") % f)
1949 self.ui.warn(_("trouble committing %s!\n") % f)
1950 raise
1950 raise
1951
1951
1952 # update manifest
1952 # update manifest
1953 self.ui.note(_("committing manifest\n"))
1953 self.ui.note(_("committing manifest\n"))
1954 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1954 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1955 drop = [f for f in removed if f in m]
1955 drop = [f for f in removed if f in m]
1956 for f in drop:
1956 for f in drop:
1957 del m[f]
1957 del m[f]
1958 mn = mctx.write(trp, linkrev,
1958 mn = mctx.write(trp, linkrev,
1959 p1.manifestnode(), p2.manifestnode(),
1959 p1.manifestnode(), p2.manifestnode(),
1960 added, drop)
1960 added, drop)
1961 files = changed + removed
1961 files = changed + removed
1962 else:
1962 else:
1963 mn = p1.manifestnode()
1963 mn = p1.manifestnode()
1964 files = []
1964 files = []
1965
1965
1966 # update changelog
1966 # update changelog
1967 self.ui.note(_("committing changelog\n"))
1967 self.ui.note(_("committing changelog\n"))
1968 self.changelog.delayupdate(tr)
1968 self.changelog.delayupdate(tr)
1969 n = self.changelog.add(mn, files, ctx.description(),
1969 n = self.changelog.add(mn, files, ctx.description(),
1970 trp, p1.node(), p2.node(),
1970 trp, p1.node(), p2.node(),
1971 user, ctx.date(), ctx.extra().copy())
1971 user, ctx.date(), ctx.extra().copy())
1972 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1972 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1973 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1973 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1974 parent2=xp2)
1974 parent2=xp2)
1975 # set the new commit is proper phase
1975 # set the new commit is proper phase
1976 targetphase = subrepo.newcommitphase(self.ui, ctx)
1976 targetphase = subrepo.newcommitphase(self.ui, ctx)
1977 if targetphase:
1977 if targetphase:
1978 # retract boundary do not alter parent changeset.
1978 # retract boundary do not alter parent changeset.
1979 # if a parent have higher the resulting phase will
1979 # if a parent have higher the resulting phase will
1980 # be compliant anyway
1980 # be compliant anyway
1981 #
1981 #
1982 # if minimal phase was 0 we don't need to retract anything
1982 # if minimal phase was 0 we don't need to retract anything
1983 phases.registernew(self, tr, targetphase, [n])
1983 phases.registernew(self, tr, targetphase, [n])
1984 tr.close()
1984 tr.close()
1985 return n
1985 return n
1986 finally:
1986 finally:
1987 if tr:
1987 if tr:
1988 tr.release()
1988 tr.release()
1989 lock.release()
1989 lock.release()
1990
1990
1991 @unfilteredmethod
1991 @unfilteredmethod
1992 def destroying(self):
1992 def destroying(self):
1993 '''Inform the repository that nodes are about to be destroyed.
1993 '''Inform the repository that nodes are about to be destroyed.
1994 Intended for use by strip and rollback, so there's a common
1994 Intended for use by strip and rollback, so there's a common
1995 place for anything that has to be done before destroying history.
1995 place for anything that has to be done before destroying history.
1996
1996
1997 This is mostly useful for saving state that is in memory and waiting
1997 This is mostly useful for saving state that is in memory and waiting
1998 to be flushed when the current lock is released. Because a call to
1998 to be flushed when the current lock is released. Because a call to
1999 destroyed is imminent, the repo will be invalidated causing those
1999 destroyed is imminent, the repo will be invalidated causing those
2000 changes to stay in memory (waiting for the next unlock), or vanish
2000 changes to stay in memory (waiting for the next unlock), or vanish
2001 completely.
2001 completely.
2002 '''
2002 '''
2003 # When using the same lock to commit and strip, the phasecache is left
2003 # When using the same lock to commit and strip, the phasecache is left
2004 # dirty after committing. Then when we strip, the repo is invalidated,
2004 # dirty after committing. Then when we strip, the repo is invalidated,
2005 # causing those changes to disappear.
2005 # causing those changes to disappear.
2006 if '_phasecache' in vars(self):
2006 if '_phasecache' in vars(self):
2007 self._phasecache.write()
2007 self._phasecache.write()
2008
2008
2009 @unfilteredmethod
2009 @unfilteredmethod
2010 def destroyed(self):
2010 def destroyed(self):
2011 '''Inform the repository that nodes have been destroyed.
2011 '''Inform the repository that nodes have been destroyed.
2012 Intended for use by strip and rollback, so there's a common
2012 Intended for use by strip and rollback, so there's a common
2013 place for anything that has to be done after destroying history.
2013 place for anything that has to be done after destroying history.
2014 '''
2014 '''
2015 # When one tries to:
2015 # When one tries to:
2016 # 1) destroy nodes thus calling this method (e.g. strip)
2016 # 1) destroy nodes thus calling this method (e.g. strip)
2017 # 2) use phasecache somewhere (e.g. commit)
2017 # 2) use phasecache somewhere (e.g. commit)
2018 #
2018 #
2019 # then 2) will fail because the phasecache contains nodes that were
2019 # then 2) will fail because the phasecache contains nodes that were
2020 # removed. We can either remove phasecache from the filecache,
2020 # removed. We can either remove phasecache from the filecache,
2021 # causing it to reload next time it is accessed, or simply filter
2021 # causing it to reload next time it is accessed, or simply filter
2022 # the removed nodes now and write the updated cache.
2022 # the removed nodes now and write the updated cache.
2023 self._phasecache.filterunknown(self)
2023 self._phasecache.filterunknown(self)
2024 self._phasecache.write()
2024 self._phasecache.write()
2025
2025
2026 # refresh all repository caches
2026 # refresh all repository caches
2027 self.updatecaches()
2027 self.updatecaches()
2028
2028
2029 # Ensure the persistent tag cache is updated. Doing it now
2029 # Ensure the persistent tag cache is updated. Doing it now
2030 # means that the tag cache only has to worry about destroyed
2030 # means that the tag cache only has to worry about destroyed
2031 # heads immediately after a strip/rollback. That in turn
2031 # heads immediately after a strip/rollback. That in turn
2032 # guarantees that "cachetip == currenttip" (comparing both rev
2032 # guarantees that "cachetip == currenttip" (comparing both rev
2033 # and node) always means no nodes have been added or destroyed.
2033 # and node) always means no nodes have been added or destroyed.
2034
2034
2035 # XXX this is suboptimal when qrefresh'ing: we strip the current
2035 # XXX this is suboptimal when qrefresh'ing: we strip the current
2036 # head, refresh the tag cache, then immediately add a new head.
2036 # head, refresh the tag cache, then immediately add a new head.
2037 # But I think doing it this way is necessary for the "instant
2037 # But I think doing it this way is necessary for the "instant
2038 # tag cache retrieval" case to work.
2038 # tag cache retrieval" case to work.
2039 self.invalidate()
2039 self.invalidate()
2040
2040
2041 def walk(self, match, node=None):
2041 def walk(self, match, node=None):
2042 '''
2042 '''
2043 walk recursively through the directory tree or a given
2043 walk recursively through the directory tree or a given
2044 changeset, finding all files matched by the match
2044 changeset, finding all files matched by the match
2045 function
2045 function
2046 '''
2046 '''
2047 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2047 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2048 return self[node].walk(match)
2048 return self[node].walk(match)
2049
2049
2050 def status(self, node1='.', node2=None, match=None,
2050 def status(self, node1='.', node2=None, match=None,
2051 ignored=False, clean=False, unknown=False,
2051 ignored=False, clean=False, unknown=False,
2052 listsubrepos=False):
2052 listsubrepos=False):
2053 '''a convenience method that calls node1.status(node2)'''
2053 '''a convenience method that calls node1.status(node2)'''
2054 return self[node1].status(node2, match, ignored, clean, unknown,
2054 return self[node1].status(node2, match, ignored, clean, unknown,
2055 listsubrepos)
2055 listsubrepos)
2056
2056
2057 def addpostdsstatus(self, ps):
2057 def addpostdsstatus(self, ps):
2058 """Add a callback to run within the wlock, at the point at which status
2058 """Add a callback to run within the wlock, at the point at which status
2059 fixups happen.
2059 fixups happen.
2060
2060
2061 On status completion, callback(wctx, status) will be called with the
2061 On status completion, callback(wctx, status) will be called with the
2062 wlock held, unless the dirstate has changed from underneath or the wlock
2062 wlock held, unless the dirstate has changed from underneath or the wlock
2063 couldn't be grabbed.
2063 couldn't be grabbed.
2064
2064
2065 Callbacks should not capture and use a cached copy of the dirstate --
2065 Callbacks should not capture and use a cached copy of the dirstate --
2066 it might change in the meanwhile. Instead, they should access the
2066 it might change in the meanwhile. Instead, they should access the
2067 dirstate via wctx.repo().dirstate.
2067 dirstate via wctx.repo().dirstate.
2068
2068
2069 This list is emptied out after each status run -- extensions should
2069 This list is emptied out after each status run -- extensions should
2070 make sure it adds to this list each time dirstate.status is called.
2070 make sure it adds to this list each time dirstate.status is called.
2071 Extensions should also make sure they don't call this for statuses
2071 Extensions should also make sure they don't call this for statuses
2072 that don't involve the dirstate.
2072 that don't involve the dirstate.
2073 """
2073 """
2074
2074
2075 # The list is located here for uniqueness reasons -- it is actually
2075 # The list is located here for uniqueness reasons -- it is actually
2076 # managed by the workingctx, but that isn't unique per-repo.
2076 # managed by the workingctx, but that isn't unique per-repo.
2077 self._postdsstatus.append(ps)
2077 self._postdsstatus.append(ps)
2078
2078
2079 def postdsstatus(self):
2079 def postdsstatus(self):
2080 """Used by workingctx to get the list of post-dirstate-status hooks."""
2080 """Used by workingctx to get the list of post-dirstate-status hooks."""
2081 return self._postdsstatus
2081 return self._postdsstatus
2082
2082
2083 def clearpostdsstatus(self):
2083 def clearpostdsstatus(self):
2084 """Used by workingctx to clear post-dirstate-status hooks."""
2084 """Used by workingctx to clear post-dirstate-status hooks."""
2085 del self._postdsstatus[:]
2085 del self._postdsstatus[:]
2086
2086
2087 def heads(self, start=None):
2087 def heads(self, start=None):
2088 if start is None:
2088 if start is None:
2089 cl = self.changelog
2089 cl = self.changelog
2090 headrevs = reversed(cl.headrevs())
2090 headrevs = reversed(cl.headrevs())
2091 return [cl.node(rev) for rev in headrevs]
2091 return [cl.node(rev) for rev in headrevs]
2092
2092
2093 heads = self.changelog.heads(start)
2093 heads = self.changelog.heads(start)
2094 # sort the output in rev descending order
2094 # sort the output in rev descending order
2095 return sorted(heads, key=self.changelog.rev, reverse=True)
2095 return sorted(heads, key=self.changelog.rev, reverse=True)
2096
2096
2097 def branchheads(self, branch=None, start=None, closed=False):
2097 def branchheads(self, branch=None, start=None, closed=False):
2098 '''return a (possibly filtered) list of heads for the given branch
2098 '''return a (possibly filtered) list of heads for the given branch
2099
2099
2100 Heads are returned in topological order, from newest to oldest.
2100 Heads are returned in topological order, from newest to oldest.
2101 If branch is None, use the dirstate branch.
2101 If branch is None, use the dirstate branch.
2102 If start is not None, return only heads reachable from start.
2102 If start is not None, return only heads reachable from start.
2103 If closed is True, return heads that are marked as closed as well.
2103 If closed is True, return heads that are marked as closed as well.
2104 '''
2104 '''
2105 if branch is None:
2105 if branch is None:
2106 branch = self[None].branch()
2106 branch = self[None].branch()
2107 branches = self.branchmap()
2107 branches = self.branchmap()
2108 if branch not in branches:
2108 if branch not in branches:
2109 return []
2109 return []
2110 # the cache returns heads ordered lowest to highest
2110 # the cache returns heads ordered lowest to highest
2111 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2111 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2112 if start is not None:
2112 if start is not None:
2113 # filter out the heads that cannot be reached from startrev
2113 # filter out the heads that cannot be reached from startrev
2114 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2114 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2115 bheads = [h for h in bheads if h in fbheads]
2115 bheads = [h for h in bheads if h in fbheads]
2116 return bheads
2116 return bheads
2117
2117
2118 def branches(self, nodes):
2118 def branches(self, nodes):
2119 if not nodes:
2119 if not nodes:
2120 nodes = [self.changelog.tip()]
2120 nodes = [self.changelog.tip()]
2121 b = []
2121 b = []
2122 for n in nodes:
2122 for n in nodes:
2123 t = n
2123 t = n
2124 while True:
2124 while True:
2125 p = self.changelog.parents(n)
2125 p = self.changelog.parents(n)
2126 if p[1] != nullid or p[0] == nullid:
2126 if p[1] != nullid or p[0] == nullid:
2127 b.append((t, n, p[0], p[1]))
2127 b.append((t, n, p[0], p[1]))
2128 break
2128 break
2129 n = p[0]
2129 n = p[0]
2130 return b
2130 return b
2131
2131
2132 def between(self, pairs):
2132 def between(self, pairs):
2133 r = []
2133 r = []
2134
2134
2135 for top, bottom in pairs:
2135 for top, bottom in pairs:
2136 n, l, i = top, [], 0
2136 n, l, i = top, [], 0
2137 f = 1
2137 f = 1
2138
2138
2139 while n != bottom and n != nullid:
2139 while n != bottom and n != nullid:
2140 p = self.changelog.parents(n)[0]
2140 p = self.changelog.parents(n)[0]
2141 if i == f:
2141 if i == f:
2142 l.append(n)
2142 l.append(n)
2143 f = f * 2
2143 f = f * 2
2144 n = p
2144 n = p
2145 i += 1
2145 i += 1
2146
2146
2147 r.append(l)
2147 r.append(l)
2148
2148
2149 return r
2149 return r
2150
2150
2151 def checkpush(self, pushop):
2151 def checkpush(self, pushop):
2152 """Extensions can override this function if additional checks have
2152 """Extensions can override this function if additional checks have
2153 to be performed before pushing, or call it if they override push
2153 to be performed before pushing, or call it if they override push
2154 command.
2154 command.
2155 """
2155 """
2156
2156
2157 @unfilteredpropertycache
2157 @unfilteredpropertycache
2158 def prepushoutgoinghooks(self):
2158 def prepushoutgoinghooks(self):
2159 """Return util.hooks consists of a pushop with repo, remote, outgoing
2159 """Return util.hooks consists of a pushop with repo, remote, outgoing
2160 methods, which are called before pushing changesets.
2160 methods, which are called before pushing changesets.
2161 """
2161 """
2162 return util.hooks()
2162 return util.hooks()
2163
2163
2164 def pushkey(self, namespace, key, old, new):
2164 def pushkey(self, namespace, key, old, new):
2165 try:
2165 try:
2166 tr = self.currenttransaction()
2166 tr = self.currenttransaction()
2167 hookargs = {}
2167 hookargs = {}
2168 if tr is not None:
2168 if tr is not None:
2169 hookargs.update(tr.hookargs)
2169 hookargs.update(tr.hookargs)
2170 hookargs['namespace'] = namespace
2170 hookargs['namespace'] = namespace
2171 hookargs['key'] = key
2171 hookargs['key'] = key
2172 hookargs['old'] = old
2172 hookargs['old'] = old
2173 hookargs['new'] = new
2173 hookargs['new'] = new
2174 self.hook('prepushkey', throw=True, **hookargs)
2174 self.hook('prepushkey', throw=True, **hookargs)
2175 except error.HookAbort as exc:
2175 except error.HookAbort as exc:
2176 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2176 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2177 if exc.hint:
2177 if exc.hint:
2178 self.ui.write_err(_("(%s)\n") % exc.hint)
2178 self.ui.write_err(_("(%s)\n") % exc.hint)
2179 return False
2179 return False
2180 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2180 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2181 ret = pushkey.push(self, namespace, key, old, new)
2181 ret = pushkey.push(self, namespace, key, old, new)
2182 def runhook():
2182 def runhook():
2183 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2183 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2184 ret=ret)
2184 ret=ret)
2185 self._afterlock(runhook)
2185 self._afterlock(runhook)
2186 return ret
2186 return ret
2187
2187
2188 def listkeys(self, namespace):
2188 def listkeys(self, namespace):
2189 self.hook('prelistkeys', throw=True, namespace=namespace)
2189 self.hook('prelistkeys', throw=True, namespace=namespace)
2190 self.ui.debug('listing keys for "%s"\n' % namespace)
2190 self.ui.debug('listing keys for "%s"\n' % namespace)
2191 values = pushkey.list(self, namespace)
2191 values = pushkey.list(self, namespace)
2192 self.hook('listkeys', namespace=namespace, values=values)
2192 self.hook('listkeys', namespace=namespace, values=values)
2193 return values
2193 return values
2194
2194
2195 def debugwireargs(self, one, two, three=None, four=None, five=None):
2195 def debugwireargs(self, one, two, three=None, four=None, five=None):
2196 '''used to test argument passing over the wire'''
2196 '''used to test argument passing over the wire'''
2197 return "%s %s %s %s %s" % (one, two, three, four, five)
2197 return "%s %s %s %s %s" % (one, two, three, four, five)
2198
2198
2199 def savecommitmessage(self, text):
2199 def savecommitmessage(self, text):
2200 fp = self.vfs('last-message.txt', 'wb')
2200 fp = self.vfs('last-message.txt', 'wb')
2201 try:
2201 try:
2202 fp.write(text)
2202 fp.write(text)
2203 finally:
2203 finally:
2204 fp.close()
2204 fp.close()
2205 return self.pathto(fp.name[len(self.root) + 1:])
2205 return self.pathto(fp.name[len(self.root) + 1:])
2206
2206
2207 # used to avoid circular references so destructors work
2207 # used to avoid circular references so destructors work
2208 def aftertrans(files):
2208 def aftertrans(files):
2209 renamefiles = [tuple(t) for t in files]
2209 renamefiles = [tuple(t) for t in files]
2210 def a():
2210 def a():
2211 for vfs, src, dest in renamefiles:
2211 for vfs, src, dest in renamefiles:
2212 # if src and dest refer to a same file, vfs.rename is a no-op,
2212 # if src and dest refer to a same file, vfs.rename is a no-op,
2213 # leaving both src and dest on disk. delete dest to make sure
2213 # leaving both src and dest on disk. delete dest to make sure
2214 # the rename couldn't be such a no-op.
2214 # the rename couldn't be such a no-op.
2215 vfs.tryunlink(dest)
2215 vfs.tryunlink(dest)
2216 try:
2216 try:
2217 vfs.rename(src, dest)
2217 vfs.rename(src, dest)
2218 except OSError: # journal file does not yet exist
2218 except OSError: # journal file does not yet exist
2219 pass
2219 pass
2220 return a
2220 return a
2221
2221
2222 def undoname(fn):
2222 def undoname(fn):
2223 base, name = os.path.split(fn)
2223 base, name = os.path.split(fn)
2224 assert name.startswith('journal')
2224 assert name.startswith('journal')
2225 return os.path.join(base, name.replace('journal', 'undo', 1))
2225 return os.path.join(base, name.replace('journal', 'undo', 1))
2226
2226
2227 def instance(ui, path, create):
2227 def instance(ui, path, create):
2228 return localrepository(ui, util.urllocalpath(path), create)
2228 return localrepository(ui, util.urllocalpath(path), create)
2229
2229
2230 def islocal(path):
2230 def islocal(path):
2231 return True
2231 return True
2232
2232
2233 def newreporequirements(repo):
2233 def newreporequirements(repo):
2234 """Determine the set of requirements for a new local repository.
2234 """Determine the set of requirements for a new local repository.
2235
2235
2236 Extensions can wrap this function to specify custom requirements for
2236 Extensions can wrap this function to specify custom requirements for
2237 new repositories.
2237 new repositories.
2238 """
2238 """
2239 ui = repo.ui
2239 ui = repo.ui
2240 requirements = {'revlogv1'}
2240 requirements = {'revlogv1'}
2241 if ui.configbool('format', 'usestore'):
2241 if ui.configbool('format', 'usestore'):
2242 requirements.add('store')
2242 requirements.add('store')
2243 if ui.configbool('format', 'usefncache'):
2243 if ui.configbool('format', 'usefncache'):
2244 requirements.add('fncache')
2244 requirements.add('fncache')
2245 if ui.configbool('format', 'dotencode'):
2245 if ui.configbool('format', 'dotencode'):
2246 requirements.add('dotencode')
2246 requirements.add('dotencode')
2247
2247
2248 compengine = ui.config('experimental', 'format.compression')
2248 compengine = ui.config('experimental', 'format.compression')
2249 if compengine not in util.compengines:
2249 if compengine not in util.compengines:
2250 raise error.Abort(_('compression engine %s defined by '
2250 raise error.Abort(_('compression engine %s defined by '
2251 'experimental.format.compression not available') %
2251 'experimental.format.compression not available') %
2252 compengine,
2252 compengine,
2253 hint=_('run "hg debuginstall" to list available '
2253 hint=_('run "hg debuginstall" to list available '
2254 'compression engines'))
2254 'compression engines'))
2255
2255
2256 # zlib is the historical default and doesn't need an explicit requirement.
2256 # zlib is the historical default and doesn't need an explicit requirement.
2257 if compengine != 'zlib':
2257 if compengine != 'zlib':
2258 requirements.add('exp-compression-%s' % compengine)
2258 requirements.add('exp-compression-%s' % compengine)
2259
2259
2260 if scmutil.gdinitconfig(ui):
2260 if scmutil.gdinitconfig(ui):
2261 requirements.add('generaldelta')
2261 requirements.add('generaldelta')
2262 if ui.configbool('experimental', 'treemanifest'):
2262 if ui.configbool('experimental', 'treemanifest'):
2263 requirements.add('treemanifest')
2263 requirements.add('treemanifest')
2264 if ui.configbool('experimental', 'manifestv2'):
2264 if ui.configbool('experimental', 'manifestv2'):
2265 requirements.add('manifestv2')
2265 requirements.add('manifestv2')
2266
2266
2267 revlogv2 = ui.config('experimental', 'revlogv2')
2267 revlogv2 = ui.config('experimental', 'revlogv2')
2268 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2268 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2269 requirements.remove('revlogv1')
2269 requirements.remove('revlogv1')
2270 # generaldelta is implied by revlogv2.
2270 # generaldelta is implied by revlogv2.
2271 requirements.discard('generaldelta')
2271 requirements.discard('generaldelta')
2272 requirements.add(REVLOGV2_REQUIREMENT)
2272 requirements.add(REVLOGV2_REQUIREMENT)
2273
2273
2274 return requirements
2274 return requirements
@@ -1,666 +1,674
1 """ Mercurial phases support code
1 """ Mercurial phases support code
2
2
3 ---
3 ---
4
4
5 Copyright 2011 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
5 Copyright 2011 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
6 Logilab SA <contact@logilab.fr>
6 Logilab SA <contact@logilab.fr>
7 Augie Fackler <durin42@gmail.com>
7 Augie Fackler <durin42@gmail.com>
8
8
9 This software may be used and distributed according to the terms
9 This software may be used and distributed according to the terms
10 of the GNU General Public License version 2 or any later version.
10 of the GNU General Public License version 2 or any later version.
11
11
12 ---
12 ---
13
13
14 This module implements most phase logic in mercurial.
14 This module implements most phase logic in mercurial.
15
15
16
16
17 Basic Concept
17 Basic Concept
18 =============
18 =============
19
19
20 A 'changeset phase' is an indicator that tells us how a changeset is
20 A 'changeset phase' is an indicator that tells us how a changeset is
21 manipulated and communicated. The details of each phase is described
21 manipulated and communicated. The details of each phase is described
22 below, here we describe the properties they have in common.
22 below, here we describe the properties they have in common.
23
23
24 Like bookmarks, phases are not stored in history and thus are not
24 Like bookmarks, phases are not stored in history and thus are not
25 permanent and leave no audit trail.
25 permanent and leave no audit trail.
26
26
27 First, no changeset can be in two phases at once. Phases are ordered,
27 First, no changeset can be in two phases at once. Phases are ordered,
28 so they can be considered from lowest to highest. The default, lowest
28 so they can be considered from lowest to highest. The default, lowest
29 phase is 'public' - this is the normal phase of existing changesets. A
29 phase is 'public' - this is the normal phase of existing changesets. A
30 child changeset can not be in a lower phase than its parents.
30 child changeset can not be in a lower phase than its parents.
31
31
32 These phases share a hierarchy of traits:
32 These phases share a hierarchy of traits:
33
33
34 immutable shared
34 immutable shared
35 public: X X
35 public: X X
36 draft: X
36 draft: X
37 secret:
37 secret:
38
38
39 Local commits are draft by default.
39 Local commits are draft by default.
40
40
41 Phase Movement and Exchange
41 Phase Movement and Exchange
42 ===========================
42 ===========================
43
43
44 Phase data is exchanged by pushkey on pull and push. Some servers have
44 Phase data is exchanged by pushkey on pull and push. Some servers have
45 a publish option set, we call such a server a "publishing server".
45 a publish option set, we call such a server a "publishing server".
46 Pushing a draft changeset to a publishing server changes the phase to
46 Pushing a draft changeset to a publishing server changes the phase to
47 public.
47 public.
48
48
49 A small list of fact/rules define the exchange of phase:
49 A small list of fact/rules define the exchange of phase:
50
50
51 * old client never changes server states
51 * old client never changes server states
52 * pull never changes server states
52 * pull never changes server states
53 * publish and old server changesets are seen as public by client
53 * publish and old server changesets are seen as public by client
54 * any secret changeset seen in another repository is lowered to at
54 * any secret changeset seen in another repository is lowered to at
55 least draft
55 least draft
56
56
57 Here is the final table summing up the 49 possible use cases of phase
57 Here is the final table summing up the 49 possible use cases of phase
58 exchange:
58 exchange:
59
59
60 server
60 server
61 old publish non-publish
61 old publish non-publish
62 N X N D P N D P
62 N X N D P N D P
63 old client
63 old client
64 pull
64 pull
65 N - X/X - X/D X/P - X/D X/P
65 N - X/X - X/D X/P - X/D X/P
66 X - X/X - X/D X/P - X/D X/P
66 X - X/X - X/D X/P - X/D X/P
67 push
67 push
68 X X/X X/X X/P X/P X/P X/D X/D X/P
68 X X/X X/X X/P X/P X/P X/D X/D X/P
69 new client
69 new client
70 pull
70 pull
71 N - P/X - P/D P/P - D/D P/P
71 N - P/X - P/D P/P - D/D P/P
72 D - P/X - P/D P/P - D/D P/P
72 D - P/X - P/D P/P - D/D P/P
73 P - P/X - P/D P/P - P/D P/P
73 P - P/X - P/D P/P - P/D P/P
74 push
74 push
75 D P/X P/X P/P P/P P/P D/D D/D P/P
75 D P/X P/X P/P P/P P/P D/D D/D P/P
76 P P/X P/X P/P P/P P/P P/P P/P P/P
76 P P/X P/X P/P P/P P/P P/P P/P P/P
77
77
78 Legend:
78 Legend:
79
79
80 A/B = final state on client / state on server
80 A/B = final state on client / state on server
81
81
82 * N = new/not present,
82 * N = new/not present,
83 * P = public,
83 * P = public,
84 * D = draft,
84 * D = draft,
85 * X = not tracked (i.e., the old client or server has no internal
85 * X = not tracked (i.e., the old client or server has no internal
86 way of recording the phase.)
86 way of recording the phase.)
87
87
88 passive = only pushes
88 passive = only pushes
89
89
90
90
91 A cell here can be read like this:
91 A cell here can be read like this:
92
92
93 "When a new client pushes a draft changeset (D) to a publishing
93 "When a new client pushes a draft changeset (D) to a publishing
94 server where it's not present (N), it's marked public on both
94 server where it's not present (N), it's marked public on both
95 sides (P/P)."
95 sides (P/P)."
96
96
97 Note: old client behave as a publishing server with draft only content
97 Note: old client behave as a publishing server with draft only content
98 - other people see it as public
98 - other people see it as public
99 - content is pushed as draft
99 - content is pushed as draft
100
100
101 """
101 """
102
102
103 from __future__ import absolute_import
103 from __future__ import absolute_import
104
104
105 import errno
105 import errno
106 import struct
106 import struct
107
107
108 from .i18n import _
108 from .i18n import _
109 from .node import (
109 from .node import (
110 bin,
110 bin,
111 hex,
111 hex,
112 nullid,
112 nullid,
113 nullrev,
113 nullrev,
114 short,
114 short,
115 )
115 )
116 from . import (
116 from . import (
117 error,
117 error,
118 pycompat,
118 smartset,
119 smartset,
119 txnutil,
120 txnutil,
120 util,
121 util,
121 )
122 )
122
123
123 _fphasesentry = struct.Struct('>i20s')
124 _fphasesentry = struct.Struct('>i20s')
124
125
125 allphases = public, draft, secret = range(3)
126 allphases = public, draft, secret = range(3)
126 trackedphases = allphases[1:]
127 trackedphases = allphases[1:]
127 phasenames = ['public', 'draft', 'secret']
128 phasenames = ['public', 'draft', 'secret']
128
129
129 def _readroots(repo, phasedefaults=None):
130 def _readroots(repo, phasedefaults=None):
130 """Read phase roots from disk
131 """Read phase roots from disk
131
132
132 phasedefaults is a list of fn(repo, roots) callable, which are
133 phasedefaults is a list of fn(repo, roots) callable, which are
133 executed if the phase roots file does not exist. When phases are
134 executed if the phase roots file does not exist. When phases are
134 being initialized on an existing repository, this could be used to
135 being initialized on an existing repository, this could be used to
135 set selected changesets phase to something else than public.
136 set selected changesets phase to something else than public.
136
137
137 Return (roots, dirty) where dirty is true if roots differ from
138 Return (roots, dirty) where dirty is true if roots differ from
138 what is being stored.
139 what is being stored.
139 """
140 """
140 repo = repo.unfiltered()
141 repo = repo.unfiltered()
141 dirty = False
142 dirty = False
142 roots = [set() for i in allphases]
143 roots = [set() for i in allphases]
143 try:
144 try:
144 f, pending = txnutil.trypending(repo.root, repo.svfs, 'phaseroots')
145 f, pending = txnutil.trypending(repo.root, repo.svfs, 'phaseroots')
145 try:
146 try:
146 for line in f:
147 for line in f:
147 phase, nh = line.split()
148 phase, nh = line.split()
148 roots[int(phase)].add(bin(nh))
149 roots[int(phase)].add(bin(nh))
149 finally:
150 finally:
150 f.close()
151 f.close()
151 except IOError as inst:
152 except IOError as inst:
152 if inst.errno != errno.ENOENT:
153 if inst.errno != errno.ENOENT:
153 raise
154 raise
154 if phasedefaults:
155 if phasedefaults:
155 for f in phasedefaults:
156 for f in phasedefaults:
156 roots = f(repo, roots)
157 roots = f(repo, roots)
157 dirty = True
158 dirty = True
158 return roots, dirty
159 return roots, dirty
159
160
160 def binaryencode(phasemapping):
161 def binaryencode(phasemapping):
161 """encode a 'phase -> nodes' mapping into a binary stream
162 """encode a 'phase -> nodes' mapping into a binary stream
162
163
163 Since phases are integer the mapping is actually a python list:
164 Since phases are integer the mapping is actually a python list:
164 [[PUBLIC_HEADS], [DRAFTS_HEADS], [SECRET_HEADS]]
165 [[PUBLIC_HEADS], [DRAFTS_HEADS], [SECRET_HEADS]]
165 """
166 """
166 binarydata = []
167 binarydata = []
167 for phase, nodes in enumerate(phasemapping):
168 for phase, nodes in enumerate(phasemapping):
168 for head in nodes:
169 for head in nodes:
169 binarydata.append(_fphasesentry.pack(phase, head))
170 binarydata.append(_fphasesentry.pack(phase, head))
170 return ''.join(binarydata)
171 return ''.join(binarydata)
171
172
172 def binarydecode(stream):
173 def binarydecode(stream):
173 """decode a binary stream into a 'phase -> nodes' mapping
174 """decode a binary stream into a 'phase -> nodes' mapping
174
175
175 Since phases are integer the mapping is actually a python list."""
176 Since phases are integer the mapping is actually a python list."""
176 headsbyphase = [[] for i in allphases]
177 headsbyphase = [[] for i in allphases]
177 entrysize = _fphasesentry.size
178 entrysize = _fphasesentry.size
178 while True:
179 while True:
179 entry = stream.read(entrysize)
180 entry = stream.read(entrysize)
180 if len(entry) < entrysize:
181 if len(entry) < entrysize:
181 if entry:
182 if entry:
182 raise error.Abort(_('bad phase-heads stream'))
183 raise error.Abort(_('bad phase-heads stream'))
183 break
184 break
184 phase, node = _fphasesentry.unpack(entry)
185 phase, node = _fphasesentry.unpack(entry)
185 headsbyphase[phase].append(node)
186 headsbyphase[phase].append(node)
186 return headsbyphase
187 return headsbyphase
187
188
188 def _trackphasechange(data, rev, old, new):
189 def _trackphasechange(data, rev, old, new):
189 """add a phase move the <data> dictionnary
190 """add a phase move the <data> dictionnary
190
191
191 If data is None, nothing happens.
192 If data is None, nothing happens.
192 """
193 """
193 if data is None:
194 if data is None:
194 return
195 return
195 existing = data.get(rev)
196 existing = data.get(rev)
196 if existing is not None:
197 if existing is not None:
197 old = existing[0]
198 old = existing[0]
198 data[rev] = (old, new)
199 data[rev] = (old, new)
199
200
200 class phasecache(object):
201 class phasecache(object):
201 def __init__(self, repo, phasedefaults, _load=True):
202 def __init__(self, repo, phasedefaults, _load=True):
202 if _load:
203 if _load:
203 # Cheap trick to allow shallow-copy without copy module
204 # Cheap trick to allow shallow-copy without copy module
204 self.phaseroots, self.dirty = _readroots(repo, phasedefaults)
205 self.phaseroots, self.dirty = _readroots(repo, phasedefaults)
205 self._phaserevs = None
206 self._phasemaxrev = nullrev
206 self._phasesets = None
207 self._phasesets = None
207 self.filterunknown(repo)
208 self.filterunknown(repo)
208 self.opener = repo.svfs
209 self.opener = repo.svfs
209
210
210 def getrevset(self, repo, phases):
211 def getrevset(self, repo, phases):
211 """return a smartset for the given phases"""
212 """return a smartset for the given phases"""
212 self.loadphaserevs(repo) # ensure phase's sets are loaded
213 self.loadphaserevs(repo) # ensure phase's sets are loaded
213
214 phases = set(phases)
214 if self._phasesets and all(self._phasesets[p] is not None
215 if public not in phases:
215 for p in phases):
216 # fast path: _phasesets contains the interesting sets,
216 # fast path - use _phasesets
217 # might only need a union and post-filtering.
217 revs = self._phasesets[phases[0]]
218 if len(phases) == 1:
218 if len(phases) > 1:
219 [p] = phases
219 revs = revs.copy() # only copy when needed
220 revs = self._phasesets[p]
220 for p in phases[1:]:
221 else:
221 revs.update(self._phasesets[p])
222 revs = set.union(*[self._phasesets[p] for p in phases])
222 if repo.changelog.filteredrevs:
223 if repo.changelog.filteredrevs:
223 revs = revs - repo.changelog.filteredrevs
224 revs = revs - repo.changelog.filteredrevs
224 return smartset.baseset(revs)
225 return smartset.baseset(revs)
225 else:
226 else:
226 # slow path - enumerate all revisions
227 phases = set(allphases).difference(phases)
227 phase = self.phase
228 if not phases:
228 revs = (r for r in repo if phase(repo, r) in phases)
229 return smartset.fullreposet(repo)
229 return smartset.generatorset(revs, iterasc=True)
230 if len(phases) == 1:
231 [p] = phases
232 revs = self._phasesets[p]
233 else:
234 revs = set.union(*[self._phasesets[p] for p in phases])
235 if not revs:
236 return smartset.fullreposet(repo)
237 return smartset.fullreposet(repo).filter(lambda r: r not in revs)
230
238
231 def copy(self):
239 def copy(self):
232 # Shallow copy meant to ensure isolation in
240 # Shallow copy meant to ensure isolation in
233 # advance/retractboundary(), nothing more.
241 # advance/retractboundary(), nothing more.
234 ph = self.__class__(None, None, _load=False)
242 ph = self.__class__(None, None, _load=False)
235 ph.phaseroots = self.phaseroots[:]
243 ph.phaseroots = self.phaseroots[:]
236 ph.dirty = self.dirty
244 ph.dirty = self.dirty
237 ph.opener = self.opener
245 ph.opener = self.opener
238 ph._phaserevs = self._phaserevs
246 ph._phasemaxrev = self._phasemaxrev
239 ph._phasesets = self._phasesets
247 ph._phasesets = self._phasesets
240 return ph
248 return ph
241
249
242 def replace(self, phcache):
250 def replace(self, phcache):
243 """replace all values in 'self' with content of phcache"""
251 """replace all values in 'self' with content of phcache"""
244 for a in ('phaseroots', 'dirty', 'opener', '_phaserevs', '_phasesets'):
252 for a in ('phaseroots', 'dirty', 'opener', '_phasemaxrev',
253 '_phasesets'):
245 setattr(self, a, getattr(phcache, a))
254 setattr(self, a, getattr(phcache, a))
246
255
247 def _getphaserevsnative(self, repo):
256 def _getphaserevsnative(self, repo):
248 repo = repo.unfiltered()
257 repo = repo.unfiltered()
249 nativeroots = []
258 nativeroots = []
250 for phase in trackedphases:
259 for phase in trackedphases:
251 nativeroots.append(map(repo.changelog.rev, self.phaseroots[phase]))
260 nativeroots.append(map(repo.changelog.rev, self.phaseroots[phase]))
252 return repo.changelog.computephases(nativeroots)
261 return repo.changelog.computephases(nativeroots)
253
262
254 def _computephaserevspure(self, repo):
263 def _computephaserevspure(self, repo):
255 repo = repo.unfiltered()
264 repo = repo.unfiltered()
256 revs = [public] * len(repo.changelog)
265 cl = repo.changelog
257 self._phaserevs = revs
266 self._phasesets = [set() for phase in allphases]
258 self._populatephaseroots(repo)
267 roots = pycompat.maplist(cl.rev, self.phaseroots[secret])
259 for phase in trackedphases:
268 if roots:
260 roots = list(map(repo.changelog.rev, self.phaseroots[phase]))
269 ps = set(cl.descendants(roots))
261 if roots:
270 for root in roots:
262 for rev in roots:
271 ps.add(root)
263 revs[rev] = phase
272 self._phasesets[secret] = ps
264 for rev in repo.changelog.descendants(roots):
273 roots = pycompat.maplist(cl.rev, self.phaseroots[draft])
265 revs[rev] = phase
274 if roots:
275 ps = set(cl.descendants(roots))
276 for root in roots:
277 ps.add(root)
278 ps.difference_update(self._phasesets[secret])
279 self._phasesets[draft] = ps
280 self._phasemaxrev = len(cl)
266
281
267 def loadphaserevs(self, repo):
282 def loadphaserevs(self, repo):
268 """ensure phase information is loaded in the object"""
283 """ensure phase information is loaded in the object"""
269 if self._phaserevs is None:
284 if self._phasesets is None:
270 try:
285 try:
271 res = self._getphaserevsnative(repo)
286 res = self._getphaserevsnative(repo)
272 self._phaserevs, self._phasesets = res
287 self._phasemaxrev, self._phasesets = res
273 except AttributeError:
288 except AttributeError:
274 self._computephaserevspure(repo)
289 self._computephaserevspure(repo)
275
290
276 def invalidate(self):
291 def invalidate(self):
277 self._phaserevs = None
292 self._phasemaxrev = nullrev
278 self._phasesets = None
293 self._phasesets = None
279
294
280 def _populatephaseroots(self, repo):
281 """Fills the _phaserevs cache with phases for the roots.
282 """
283 cl = repo.changelog
284 phaserevs = self._phaserevs
285 for phase in trackedphases:
286 roots = map(cl.rev, self.phaseroots[phase])
287 for root in roots:
288 phaserevs[root] = phase
289
290 def phase(self, repo, rev):
295 def phase(self, repo, rev):
291 # We need a repo argument here to be able to build _phaserevs
296 # We need a repo argument here to be able to build _phasesets
292 # if necessary. The repository instance is not stored in
297 # if necessary. The repository instance is not stored in
293 # phasecache to avoid reference cycles. The changelog instance
298 # phasecache to avoid reference cycles. The changelog instance
294 # is not stored because it is a filecache() property and can
299 # is not stored because it is a filecache() property and can
295 # be replaced without us being notified.
300 # be replaced without us being notified.
296 if rev == nullrev:
301 if rev == nullrev:
297 return public
302 return public
298 if rev < nullrev:
303 if rev < nullrev:
299 raise ValueError(_('cannot lookup negative revision'))
304 raise ValueError(_('cannot lookup negative revision'))
300 if self._phaserevs is None or rev >= len(self._phaserevs):
305 if rev >= self._phasemaxrev:
301 self.invalidate()
306 self.invalidate()
302 self.loadphaserevs(repo)
307 self.loadphaserevs(repo)
303 return self._phaserevs[rev]
308 for phase in trackedphases:
309 if rev in self._phasesets[phase]:
310 return phase
311 return public
304
312
305 def write(self):
313 def write(self):
306 if not self.dirty:
314 if not self.dirty:
307 return
315 return
308 f = self.opener('phaseroots', 'w', atomictemp=True, checkambig=True)
316 f = self.opener('phaseroots', 'w', atomictemp=True, checkambig=True)
309 try:
317 try:
310 self._write(f)
318 self._write(f)
311 finally:
319 finally:
312 f.close()
320 f.close()
313
321
314 def _write(self, fp):
322 def _write(self, fp):
315 for phase, roots in enumerate(self.phaseroots):
323 for phase, roots in enumerate(self.phaseroots):
316 for h in roots:
324 for h in roots:
317 fp.write('%i %s\n' % (phase, hex(h)))
325 fp.write('%i %s\n' % (phase, hex(h)))
318 self.dirty = False
326 self.dirty = False
319
327
320 def _updateroots(self, phase, newroots, tr):
328 def _updateroots(self, phase, newroots, tr):
321 self.phaseroots[phase] = newroots
329 self.phaseroots[phase] = newroots
322 self.invalidate()
330 self.invalidate()
323 self.dirty = True
331 self.dirty = True
324
332
325 tr.addfilegenerator('phase', ('phaseroots',), self._write)
333 tr.addfilegenerator('phase', ('phaseroots',), self._write)
326 tr.hookargs['phases_moved'] = '1'
334 tr.hookargs['phases_moved'] = '1'
327
335
328 def registernew(self, repo, tr, targetphase, nodes):
336 def registernew(self, repo, tr, targetphase, nodes):
329 repo = repo.unfiltered()
337 repo = repo.unfiltered()
330 self._retractboundary(repo, tr, targetphase, nodes)
338 self._retractboundary(repo, tr, targetphase, nodes)
331 if tr is not None and 'phases' in tr.changes:
339 if tr is not None and 'phases' in tr.changes:
332 phasetracking = tr.changes['phases']
340 phasetracking = tr.changes['phases']
333 torev = repo.changelog.rev
341 torev = repo.changelog.rev
334 phase = self.phase
342 phase = self.phase
335 for n in nodes:
343 for n in nodes:
336 rev = torev(n)
344 rev = torev(n)
337 revphase = phase(repo, rev)
345 revphase = phase(repo, rev)
338 _trackphasechange(phasetracking, rev, None, revphase)
346 _trackphasechange(phasetracking, rev, None, revphase)
339 repo.invalidatevolatilesets()
347 repo.invalidatevolatilesets()
340
348
341 def advanceboundary(self, repo, tr, targetphase, nodes):
349 def advanceboundary(self, repo, tr, targetphase, nodes):
342 """Set all 'nodes' to phase 'targetphase'
350 """Set all 'nodes' to phase 'targetphase'
343
351
344 Nodes with a phase lower than 'targetphase' are not affected.
352 Nodes with a phase lower than 'targetphase' are not affected.
345 """
353 """
346 # Be careful to preserve shallow-copied values: do not update
354 # Be careful to preserve shallow-copied values: do not update
347 # phaseroots values, replace them.
355 # phaseroots values, replace them.
348 if tr is None:
356 if tr is None:
349 phasetracking = None
357 phasetracking = None
350 else:
358 else:
351 phasetracking = tr.changes.get('phases')
359 phasetracking = tr.changes.get('phases')
352
360
353 repo = repo.unfiltered()
361 repo = repo.unfiltered()
354
362
355 delroots = [] # set of root deleted by this path
363 delroots = [] # set of root deleted by this path
356 for phase in xrange(targetphase + 1, len(allphases)):
364 for phase in xrange(targetphase + 1, len(allphases)):
357 # filter nodes that are not in a compatible phase already
365 # filter nodes that are not in a compatible phase already
358 nodes = [n for n in nodes
366 nodes = [n for n in nodes
359 if self.phase(repo, repo[n].rev()) >= phase]
367 if self.phase(repo, repo[n].rev()) >= phase]
360 if not nodes:
368 if not nodes:
361 break # no roots to move anymore
369 break # no roots to move anymore
362
370
363 olds = self.phaseroots[phase]
371 olds = self.phaseroots[phase]
364
372
365 affected = repo.revs('%ln::%ln', olds, nodes)
373 affected = repo.revs('%ln::%ln', olds, nodes)
366 for r in affected:
374 for r in affected:
367 _trackphasechange(phasetracking, r, self.phase(repo, r),
375 _trackphasechange(phasetracking, r, self.phase(repo, r),
368 targetphase)
376 targetphase)
369
377
370 roots = set(ctx.node() for ctx in repo.set(
378 roots = set(ctx.node() for ctx in repo.set(
371 'roots((%ln::) - %ld)', olds, affected))
379 'roots((%ln::) - %ld)', olds, affected))
372 if olds != roots:
380 if olds != roots:
373 self._updateroots(phase, roots, tr)
381 self._updateroots(phase, roots, tr)
374 # some roots may need to be declared for lower phases
382 # some roots may need to be declared for lower phases
375 delroots.extend(olds - roots)
383 delroots.extend(olds - roots)
376 # declare deleted root in the target phase
384 # declare deleted root in the target phase
377 if targetphase != 0:
385 if targetphase != 0:
378 self._retractboundary(repo, tr, targetphase, delroots)
386 self._retractboundary(repo, tr, targetphase, delroots)
379 repo.invalidatevolatilesets()
387 repo.invalidatevolatilesets()
380
388
381 def retractboundary(self, repo, tr, targetphase, nodes):
389 def retractboundary(self, repo, tr, targetphase, nodes):
382 oldroots = self.phaseroots[:targetphase + 1]
390 oldroots = self.phaseroots[:targetphase + 1]
383 if tr is None:
391 if tr is None:
384 phasetracking = None
392 phasetracking = None
385 else:
393 else:
386 phasetracking = tr.changes.get('phases')
394 phasetracking = tr.changes.get('phases')
387 repo = repo.unfiltered()
395 repo = repo.unfiltered()
388 if (self._retractboundary(repo, tr, targetphase, nodes)
396 if (self._retractboundary(repo, tr, targetphase, nodes)
389 and phasetracking is not None):
397 and phasetracking is not None):
390
398
391 # find the affected revisions
399 # find the affected revisions
392 new = self.phaseroots[targetphase]
400 new = self.phaseroots[targetphase]
393 old = oldroots[targetphase]
401 old = oldroots[targetphase]
394 affected = set(repo.revs('(%ln::) - (%ln::)', new, old))
402 affected = set(repo.revs('(%ln::) - (%ln::)', new, old))
395
403
396 # find the phase of the affected revision
404 # find the phase of the affected revision
397 for phase in xrange(targetphase, -1, -1):
405 for phase in xrange(targetphase, -1, -1):
398 if phase:
406 if phase:
399 roots = oldroots[phase]
407 roots = oldroots[phase]
400 revs = set(repo.revs('%ln::%ld', roots, affected))
408 revs = set(repo.revs('%ln::%ld', roots, affected))
401 affected -= revs
409 affected -= revs
402 else: # public phase
410 else: # public phase
403 revs = affected
411 revs = affected
404 for r in revs:
412 for r in revs:
405 _trackphasechange(phasetracking, r, phase, targetphase)
413 _trackphasechange(phasetracking, r, phase, targetphase)
406 repo.invalidatevolatilesets()
414 repo.invalidatevolatilesets()
407
415
408 def _retractboundary(self, repo, tr, targetphase, nodes):
416 def _retractboundary(self, repo, tr, targetphase, nodes):
409 # Be careful to preserve shallow-copied values: do not update
417 # Be careful to preserve shallow-copied values: do not update
410 # phaseroots values, replace them.
418 # phaseroots values, replace them.
411
419
412 repo = repo.unfiltered()
420 repo = repo.unfiltered()
413 currentroots = self.phaseroots[targetphase]
421 currentroots = self.phaseroots[targetphase]
414 finalroots = oldroots = set(currentroots)
422 finalroots = oldroots = set(currentroots)
415 newroots = [n for n in nodes
423 newroots = [n for n in nodes
416 if self.phase(repo, repo[n].rev()) < targetphase]
424 if self.phase(repo, repo[n].rev()) < targetphase]
417 if newroots:
425 if newroots:
418
426
419 if nullid in newroots:
427 if nullid in newroots:
420 raise error.Abort(_('cannot change null revision phase'))
428 raise error.Abort(_('cannot change null revision phase'))
421 currentroots = currentroots.copy()
429 currentroots = currentroots.copy()
422 currentroots.update(newroots)
430 currentroots.update(newroots)
423
431
424 # Only compute new roots for revs above the roots that are being
432 # Only compute new roots for revs above the roots that are being
425 # retracted.
433 # retracted.
426 minnewroot = min(repo[n].rev() for n in newroots)
434 minnewroot = min(repo[n].rev() for n in newroots)
427 aboveroots = [n for n in currentroots
435 aboveroots = [n for n in currentroots
428 if repo[n].rev() >= minnewroot]
436 if repo[n].rev() >= minnewroot]
429 updatedroots = repo.set('roots(%ln::)', aboveroots)
437 updatedroots = repo.set('roots(%ln::)', aboveroots)
430
438
431 finalroots = set(n for n in currentroots if repo[n].rev() <
439 finalroots = set(n for n in currentroots if repo[n].rev() <
432 minnewroot)
440 minnewroot)
433 finalroots.update(ctx.node() for ctx in updatedroots)
441 finalroots.update(ctx.node() for ctx in updatedroots)
434 if finalroots != oldroots:
442 if finalroots != oldroots:
435 self._updateroots(targetphase, finalroots, tr)
443 self._updateroots(targetphase, finalroots, tr)
436 return True
444 return True
437 return False
445 return False
438
446
439 def filterunknown(self, repo):
447 def filterunknown(self, repo):
440 """remove unknown nodes from the phase boundary
448 """remove unknown nodes from the phase boundary
441
449
442 Nothing is lost as unknown nodes only hold data for their descendants.
450 Nothing is lost as unknown nodes only hold data for their descendants.
443 """
451 """
444 filtered = False
452 filtered = False
445 nodemap = repo.changelog.nodemap # to filter unknown nodes
453 nodemap = repo.changelog.nodemap # to filter unknown nodes
446 for phase, nodes in enumerate(self.phaseroots):
454 for phase, nodes in enumerate(self.phaseroots):
447 missing = sorted(node for node in nodes if node not in nodemap)
455 missing = sorted(node for node in nodes if node not in nodemap)
448 if missing:
456 if missing:
449 for mnode in missing:
457 for mnode in missing:
450 repo.ui.debug(
458 repo.ui.debug(
451 'removing unknown node %s from %i-phase boundary\n'
459 'removing unknown node %s from %i-phase boundary\n'
452 % (short(mnode), phase))
460 % (short(mnode), phase))
453 nodes.symmetric_difference_update(missing)
461 nodes.symmetric_difference_update(missing)
454 filtered = True
462 filtered = True
455 if filtered:
463 if filtered:
456 self.dirty = True
464 self.dirty = True
457 # filterunknown is called by repo.destroyed, we may have no changes in
465 # filterunknown is called by repo.destroyed, we may have no changes in
458 # root but phaserevs contents is certainly invalid (or at least we
466 # root but _phasesets contents is certainly invalid (or at least we
459 # have not proper way to check that). related to issue 3858.
467 # have not proper way to check that). related to issue 3858.
460 #
468 #
461 # The other caller is __init__ that have no _phaserevs initialized
469 # The other caller is __init__ that have no _phasesets initialized
462 # anyway. If this change we should consider adding a dedicated
470 # anyway. If this change we should consider adding a dedicated
463 # "destroyed" function to phasecache or a proper cache key mechanism
471 # "destroyed" function to phasecache or a proper cache key mechanism
464 # (see branchmap one)
472 # (see branchmap one)
465 self.invalidate()
473 self.invalidate()
466
474
467 def advanceboundary(repo, tr, targetphase, nodes):
475 def advanceboundary(repo, tr, targetphase, nodes):
468 """Add nodes to a phase changing other nodes phases if necessary.
476 """Add nodes to a phase changing other nodes phases if necessary.
469
477
470 This function move boundary *forward* this means that all nodes
478 This function move boundary *forward* this means that all nodes
471 are set in the target phase or kept in a *lower* phase.
479 are set in the target phase or kept in a *lower* phase.
472
480
473 Simplify boundary to contains phase roots only."""
481 Simplify boundary to contains phase roots only."""
474 phcache = repo._phasecache.copy()
482 phcache = repo._phasecache.copy()
475 phcache.advanceboundary(repo, tr, targetphase, nodes)
483 phcache.advanceboundary(repo, tr, targetphase, nodes)
476 repo._phasecache.replace(phcache)
484 repo._phasecache.replace(phcache)
477
485
478 def retractboundary(repo, tr, targetphase, nodes):
486 def retractboundary(repo, tr, targetphase, nodes):
479 """Set nodes back to a phase changing other nodes phases if
487 """Set nodes back to a phase changing other nodes phases if
480 necessary.
488 necessary.
481
489
482 This function move boundary *backward* this means that all nodes
490 This function move boundary *backward* this means that all nodes
483 are set in the target phase or kept in a *higher* phase.
491 are set in the target phase or kept in a *higher* phase.
484
492
485 Simplify boundary to contains phase roots only."""
493 Simplify boundary to contains phase roots only."""
486 phcache = repo._phasecache.copy()
494 phcache = repo._phasecache.copy()
487 phcache.retractboundary(repo, tr, targetphase, nodes)
495 phcache.retractboundary(repo, tr, targetphase, nodes)
488 repo._phasecache.replace(phcache)
496 repo._phasecache.replace(phcache)
489
497
490 def registernew(repo, tr, targetphase, nodes):
498 def registernew(repo, tr, targetphase, nodes):
491 """register a new revision and its phase
499 """register a new revision and its phase
492
500
493 Code adding revisions to the repository should use this function to
501 Code adding revisions to the repository should use this function to
494 set new changeset in their target phase (or higher).
502 set new changeset in their target phase (or higher).
495 """
503 """
496 phcache = repo._phasecache.copy()
504 phcache = repo._phasecache.copy()
497 phcache.registernew(repo, tr, targetphase, nodes)
505 phcache.registernew(repo, tr, targetphase, nodes)
498 repo._phasecache.replace(phcache)
506 repo._phasecache.replace(phcache)
499
507
500 def listphases(repo):
508 def listphases(repo):
501 """List phases root for serialization over pushkey"""
509 """List phases root for serialization over pushkey"""
502 # Use ordered dictionary so behavior is deterministic.
510 # Use ordered dictionary so behavior is deterministic.
503 keys = util.sortdict()
511 keys = util.sortdict()
504 value = '%i' % draft
512 value = '%i' % draft
505 cl = repo.unfiltered().changelog
513 cl = repo.unfiltered().changelog
506 for root in repo._phasecache.phaseroots[draft]:
514 for root in repo._phasecache.phaseroots[draft]:
507 if repo._phasecache.phase(repo, cl.rev(root)) <= draft:
515 if repo._phasecache.phase(repo, cl.rev(root)) <= draft:
508 keys[hex(root)] = value
516 keys[hex(root)] = value
509
517
510 if repo.publishing():
518 if repo.publishing():
511 # Add an extra data to let remote know we are a publishing
519 # Add an extra data to let remote know we are a publishing
512 # repo. Publishing repo can't just pretend they are old repo.
520 # repo. Publishing repo can't just pretend they are old repo.
513 # When pushing to a publishing repo, the client still need to
521 # When pushing to a publishing repo, the client still need to
514 # push phase boundary
522 # push phase boundary
515 #
523 #
516 # Push do not only push changeset. It also push phase data.
524 # Push do not only push changeset. It also push phase data.
517 # New phase data may apply to common changeset which won't be
525 # New phase data may apply to common changeset which won't be
518 # push (as they are common). Here is a very simple example:
526 # push (as they are common). Here is a very simple example:
519 #
527 #
520 # 1) repo A push changeset X as draft to repo B
528 # 1) repo A push changeset X as draft to repo B
521 # 2) repo B make changeset X public
529 # 2) repo B make changeset X public
522 # 3) repo B push to repo A. X is not pushed but the data that
530 # 3) repo B push to repo A. X is not pushed but the data that
523 # X as now public should
531 # X as now public should
524 #
532 #
525 # The server can't handle it on it's own as it has no idea of
533 # The server can't handle it on it's own as it has no idea of
526 # client phase data.
534 # client phase data.
527 keys['publishing'] = 'True'
535 keys['publishing'] = 'True'
528 return keys
536 return keys
529
537
530 def pushphase(repo, nhex, oldphasestr, newphasestr):
538 def pushphase(repo, nhex, oldphasestr, newphasestr):
531 """List phases root for serialization over pushkey"""
539 """List phases root for serialization over pushkey"""
532 repo = repo.unfiltered()
540 repo = repo.unfiltered()
533 with repo.lock():
541 with repo.lock():
534 currentphase = repo[nhex].phase()
542 currentphase = repo[nhex].phase()
535 newphase = abs(int(newphasestr)) # let's avoid negative index surprise
543 newphase = abs(int(newphasestr)) # let's avoid negative index surprise
536 oldphase = abs(int(oldphasestr)) # let's avoid negative index surprise
544 oldphase = abs(int(oldphasestr)) # let's avoid negative index surprise
537 if currentphase == oldphase and newphase < oldphase:
545 if currentphase == oldphase and newphase < oldphase:
538 with repo.transaction('pushkey-phase') as tr:
546 with repo.transaction('pushkey-phase') as tr:
539 advanceboundary(repo, tr, newphase, [bin(nhex)])
547 advanceboundary(repo, tr, newphase, [bin(nhex)])
540 return True
548 return True
541 elif currentphase == newphase:
549 elif currentphase == newphase:
542 # raced, but got correct result
550 # raced, but got correct result
543 return True
551 return True
544 else:
552 else:
545 return False
553 return False
546
554
547 def subsetphaseheads(repo, subset):
555 def subsetphaseheads(repo, subset):
548 """Finds the phase heads for a subset of a history
556 """Finds the phase heads for a subset of a history
549
557
550 Returns a list indexed by phase number where each item is a list of phase
558 Returns a list indexed by phase number where each item is a list of phase
551 head nodes.
559 head nodes.
552 """
560 """
553 cl = repo.changelog
561 cl = repo.changelog
554
562
555 headsbyphase = [[] for i in allphases]
563 headsbyphase = [[] for i in allphases]
556 # No need to keep track of secret phase; any heads in the subset that
564 # No need to keep track of secret phase; any heads in the subset that
557 # are not mentioned are implicitly secret.
565 # are not mentioned are implicitly secret.
558 for phase in allphases[:-1]:
566 for phase in allphases[:-1]:
559 revset = "heads(%%ln & %s())" % phasenames[phase]
567 revset = "heads(%%ln & %s())" % phasenames[phase]
560 headsbyphase[phase] = [cl.node(r) for r in repo.revs(revset, subset)]
568 headsbyphase[phase] = [cl.node(r) for r in repo.revs(revset, subset)]
561 return headsbyphase
569 return headsbyphase
562
570
563 def updatephases(repo, trgetter, headsbyphase):
571 def updatephases(repo, trgetter, headsbyphase):
564 """Updates the repo with the given phase heads"""
572 """Updates the repo with the given phase heads"""
565 # Now advance phase boundaries of all but secret phase
573 # Now advance phase boundaries of all but secret phase
566 #
574 #
567 # run the update (and fetch transaction) only if there are actually things
575 # run the update (and fetch transaction) only if there are actually things
568 # to update. This avoid creating empty transaction during no-op operation.
576 # to update. This avoid creating empty transaction during no-op operation.
569
577
570 for phase in allphases[:-1]:
578 for phase in allphases[:-1]:
571 revset = '%%ln - %s()' % phasenames[phase]
579 revset = '%%ln - %s()' % phasenames[phase]
572 heads = [c.node() for c in repo.set(revset, headsbyphase[phase])]
580 heads = [c.node() for c in repo.set(revset, headsbyphase[phase])]
573 if heads:
581 if heads:
574 advanceboundary(repo, trgetter(), phase, heads)
582 advanceboundary(repo, trgetter(), phase, heads)
575
583
576 def analyzeremotephases(repo, subset, roots):
584 def analyzeremotephases(repo, subset, roots):
577 """Compute phases heads and root in a subset of node from root dict
585 """Compute phases heads and root in a subset of node from root dict
578
586
579 * subset is heads of the subset
587 * subset is heads of the subset
580 * roots is {<nodeid> => phase} mapping. key and value are string.
588 * roots is {<nodeid> => phase} mapping. key and value are string.
581
589
582 Accept unknown element input
590 Accept unknown element input
583 """
591 """
584 repo = repo.unfiltered()
592 repo = repo.unfiltered()
585 # build list from dictionary
593 # build list from dictionary
586 draftroots = []
594 draftroots = []
587 nodemap = repo.changelog.nodemap # to filter unknown nodes
595 nodemap = repo.changelog.nodemap # to filter unknown nodes
588 for nhex, phase in roots.iteritems():
596 for nhex, phase in roots.iteritems():
589 if nhex == 'publishing': # ignore data related to publish option
597 if nhex == 'publishing': # ignore data related to publish option
590 continue
598 continue
591 node = bin(nhex)
599 node = bin(nhex)
592 phase = int(phase)
600 phase = int(phase)
593 if phase == public:
601 if phase == public:
594 if node != nullid:
602 if node != nullid:
595 repo.ui.warn(_('ignoring inconsistent public root'
603 repo.ui.warn(_('ignoring inconsistent public root'
596 ' from remote: %s\n') % nhex)
604 ' from remote: %s\n') % nhex)
597 elif phase == draft:
605 elif phase == draft:
598 if node in nodemap:
606 if node in nodemap:
599 draftroots.append(node)
607 draftroots.append(node)
600 else:
608 else:
601 repo.ui.warn(_('ignoring unexpected root from remote: %i %s\n')
609 repo.ui.warn(_('ignoring unexpected root from remote: %i %s\n')
602 % (phase, nhex))
610 % (phase, nhex))
603 # compute heads
611 # compute heads
604 publicheads = newheads(repo, subset, draftroots)
612 publicheads = newheads(repo, subset, draftroots)
605 return publicheads, draftroots
613 return publicheads, draftroots
606
614
607 class remotephasessummary(object):
615 class remotephasessummary(object):
608 """summarize phase information on the remote side
616 """summarize phase information on the remote side
609
617
610 :publishing: True is the remote is publishing
618 :publishing: True is the remote is publishing
611 :publicheads: list of remote public phase heads (nodes)
619 :publicheads: list of remote public phase heads (nodes)
612 :draftheads: list of remote draft phase heads (nodes)
620 :draftheads: list of remote draft phase heads (nodes)
613 :draftroots: list of remote draft phase root (nodes)
621 :draftroots: list of remote draft phase root (nodes)
614 """
622 """
615
623
616 def __init__(self, repo, remotesubset, remoteroots):
624 def __init__(self, repo, remotesubset, remoteroots):
617 unfi = repo.unfiltered()
625 unfi = repo.unfiltered()
618 self._allremoteroots = remoteroots
626 self._allremoteroots = remoteroots
619
627
620 self.publishing = remoteroots.get('publishing', False)
628 self.publishing = remoteroots.get('publishing', False)
621
629
622 ana = analyzeremotephases(repo, remotesubset, remoteroots)
630 ana = analyzeremotephases(repo, remotesubset, remoteroots)
623 self.publicheads, self.draftroots = ana
631 self.publicheads, self.draftroots = ana
624 # Get the list of all "heads" revs draft on remote
632 # Get the list of all "heads" revs draft on remote
625 dheads = unfi.set('heads(%ln::%ln)', self.draftroots, remotesubset)
633 dheads = unfi.set('heads(%ln::%ln)', self.draftroots, remotesubset)
626 self.draftheads = [c.node() for c in dheads]
634 self.draftheads = [c.node() for c in dheads]
627
635
628 def newheads(repo, heads, roots):
636 def newheads(repo, heads, roots):
629 """compute new head of a subset minus another
637 """compute new head of a subset minus another
630
638
631 * `heads`: define the first subset
639 * `heads`: define the first subset
632 * `roots`: define the second we subtract from the first"""
640 * `roots`: define the second we subtract from the first"""
633 repo = repo.unfiltered()
641 repo = repo.unfiltered()
634 revset = repo.set('heads((%ln + parents(%ln)) - (%ln::%ln))',
642 revset = repo.set('heads((%ln + parents(%ln)) - (%ln::%ln))',
635 heads, roots, roots, heads)
643 heads, roots, roots, heads)
636 return [c.node() for c in revset]
644 return [c.node() for c in revset]
637
645
638
646
639 def newcommitphase(ui):
647 def newcommitphase(ui):
640 """helper to get the target phase of new commit
648 """helper to get the target phase of new commit
641
649
642 Handle all possible values for the phases.new-commit options.
650 Handle all possible values for the phases.new-commit options.
643
651
644 """
652 """
645 v = ui.config('phases', 'new-commit')
653 v = ui.config('phases', 'new-commit')
646 try:
654 try:
647 return phasenames.index(v)
655 return phasenames.index(v)
648 except ValueError:
656 except ValueError:
649 try:
657 try:
650 return int(v)
658 return int(v)
651 except ValueError:
659 except ValueError:
652 msg = _("phases.new-commit: not a valid phase name ('%s')")
660 msg = _("phases.new-commit: not a valid phase name ('%s')")
653 raise error.ConfigError(msg % v)
661 raise error.ConfigError(msg % v)
654
662
655 def hassecret(repo):
663 def hassecret(repo):
656 """utility function that check if a repo have any secret changeset."""
664 """utility function that check if a repo have any secret changeset."""
657 return bool(repo._phasecache.phaseroots[2])
665 return bool(repo._phasecache.phaseroots[2])
658
666
659 def preparehookargs(node, old, new):
667 def preparehookargs(node, old, new):
660 if old is None:
668 if old is None:
661 old = ''
669 old = ''
662 else:
670 else:
663 old = phasenames[old]
671 old = phasenames[old]
664 return {'node': node,
672 return {'node': node,
665 'oldphase': old,
673 'oldphase': old,
666 'phase': phasenames[new]}
674 'phase': phasenames[new]}
@@ -1,116 +1,116
1 # policy.py - module policy logic for Mercurial.
1 # policy.py - module policy logic for Mercurial.
2 #
2 #
3 # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com>
3 # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import os
10 import os
11 import sys
11 import sys
12
12
13 # Rules for how modules can be loaded. Values are:
13 # Rules for how modules can be loaded. Values are:
14 #
14 #
15 # c - require C extensions
15 # c - require C extensions
16 # allow - allow pure Python implementation when C loading fails
16 # allow - allow pure Python implementation when C loading fails
17 # cffi - required cffi versions (implemented within pure module)
17 # cffi - required cffi versions (implemented within pure module)
18 # cffi-allow - allow pure Python implementation if cffi version is missing
18 # cffi-allow - allow pure Python implementation if cffi version is missing
19 # py - only load pure Python modules
19 # py - only load pure Python modules
20 #
20 #
21 # By default, fall back to the pure modules so the in-place build can
21 # By default, fall back to the pure modules so the in-place build can
22 # run without recompiling the C extensions. This will be overridden by
22 # run without recompiling the C extensions. This will be overridden by
23 # __modulepolicy__ generated by setup.py.
23 # __modulepolicy__ generated by setup.py.
24 policy = b'allow'
24 policy = b'allow'
25 _packageprefs = {
25 _packageprefs = {
26 # policy: (versioned package, pure package)
26 # policy: (versioned package, pure package)
27 b'c': (r'cext', None),
27 b'c': (r'cext', None),
28 b'allow': (r'cext', r'pure'),
28 b'allow': (r'cext', r'pure'),
29 b'cffi': (r'cffi', None),
29 b'cffi': (r'cffi', None),
30 b'cffi-allow': (r'cffi', r'pure'),
30 b'cffi-allow': (r'cffi', r'pure'),
31 b'py': (None, r'pure'),
31 b'py': (None, r'pure'),
32 }
32 }
33
33
34 try:
34 try:
35 from . import __modulepolicy__
35 from . import __modulepolicy__
36 policy = __modulepolicy__.modulepolicy
36 policy = __modulepolicy__.modulepolicy
37 except ImportError:
37 except ImportError:
38 pass
38 pass
39
39
40 # PyPy doesn't load C extensions.
40 # PyPy doesn't load C extensions.
41 #
41 #
42 # The canonical way to do this is to test platform.python_implementation().
42 # The canonical way to do this is to test platform.python_implementation().
43 # But we don't import platform and don't bloat for it here.
43 # But we don't import platform and don't bloat for it here.
44 if r'__pypy__' in sys.builtin_module_names:
44 if r'__pypy__' in sys.builtin_module_names:
45 policy = b'cffi'
45 policy = b'cffi'
46
46
47 # Our C extensions aren't yet compatible with Python 3. So use pure Python
47 # Our C extensions aren't yet compatible with Python 3. So use pure Python
48 # on Python 3 for now.
48 # on Python 3 for now.
49 if sys.version_info[0] >= 3:
49 if sys.version_info[0] >= 3:
50 policy = b'py'
50 policy = b'py'
51
51
52 # Environment variable can always force settings.
52 # Environment variable can always force settings.
53 if sys.version_info[0] >= 3:
53 if sys.version_info[0] >= 3:
54 if r'HGMODULEPOLICY' in os.environ:
54 if r'HGMODULEPOLICY' in os.environ:
55 policy = os.environ[r'HGMODULEPOLICY'].encode(r'utf-8')
55 policy = os.environ[r'HGMODULEPOLICY'].encode(r'utf-8')
56 else:
56 else:
57 policy = os.environ.get(r'HGMODULEPOLICY', policy)
57 policy = os.environ.get(r'HGMODULEPOLICY', policy)
58
58
59 def _importfrom(pkgname, modname):
59 def _importfrom(pkgname, modname):
60 # from .<pkgname> import <modname> (where . is looked through this module)
60 # from .<pkgname> import <modname> (where . is looked through this module)
61 fakelocals = {}
61 fakelocals = {}
62 pkg = __import__(pkgname, globals(), fakelocals, [modname], level=1)
62 pkg = __import__(pkgname, globals(), fakelocals, [modname], level=1)
63 try:
63 try:
64 fakelocals[modname] = mod = getattr(pkg, modname)
64 fakelocals[modname] = mod = getattr(pkg, modname)
65 except AttributeError:
65 except AttributeError:
66 raise ImportError(r'cannot import name %s' % modname)
66 raise ImportError(r'cannot import name %s' % modname)
67 # force import; fakelocals[modname] may be replaced with the real module
67 # force import; fakelocals[modname] may be replaced with the real module
68 getattr(mod, r'__doc__', None)
68 getattr(mod, r'__doc__', None)
69 return fakelocals[modname]
69 return fakelocals[modname]
70
70
71 # keep in sync with "version" in C modules
71 # keep in sync with "version" in C modules
72 _cextversions = {
72 _cextversions = {
73 (r'cext', r'base85'): 1,
73 (r'cext', r'base85'): 1,
74 (r'cext', r'bdiff'): 1,
74 (r'cext', r'bdiff'): 1,
75 (r'cext', r'diffhelpers'): 1,
75 (r'cext', r'diffhelpers'): 1,
76 (r'cext', r'mpatch'): 1,
76 (r'cext', r'mpatch'): 1,
77 (r'cext', r'osutil'): 1,
77 (r'cext', r'osutil'): 1,
78 (r'cext', r'parsers'): 3,
78 (r'cext', r'parsers'): 4,
79 }
79 }
80
80
81 # map import request to other package or module
81 # map import request to other package or module
82 _modredirects = {
82 _modredirects = {
83 (r'cext', r'charencode'): (r'cext', r'parsers'),
83 (r'cext', r'charencode'): (r'cext', r'parsers'),
84 (r'cffi', r'base85'): (r'pure', r'base85'),
84 (r'cffi', r'base85'): (r'pure', r'base85'),
85 (r'cffi', r'charencode'): (r'pure', r'charencode'),
85 (r'cffi', r'charencode'): (r'pure', r'charencode'),
86 (r'cffi', r'diffhelpers'): (r'pure', r'diffhelpers'),
86 (r'cffi', r'diffhelpers'): (r'pure', r'diffhelpers'),
87 (r'cffi', r'parsers'): (r'pure', r'parsers'),
87 (r'cffi', r'parsers'): (r'pure', r'parsers'),
88 }
88 }
89
89
90 def _checkmod(pkgname, modname, mod):
90 def _checkmod(pkgname, modname, mod):
91 expected = _cextversions.get((pkgname, modname))
91 expected = _cextversions.get((pkgname, modname))
92 actual = getattr(mod, r'version', None)
92 actual = getattr(mod, r'version', None)
93 if actual != expected:
93 if actual != expected:
94 raise ImportError(r'cannot import module %s.%s '
94 raise ImportError(r'cannot import module %s.%s '
95 r'(expected version: %d, actual: %r)'
95 r'(expected version: %d, actual: %r)'
96 % (pkgname, modname, expected, actual))
96 % (pkgname, modname, expected, actual))
97
97
98 def importmod(modname):
98 def importmod(modname):
99 """Import module according to policy and check API version"""
99 """Import module according to policy and check API version"""
100 try:
100 try:
101 verpkg, purepkg = _packageprefs[policy]
101 verpkg, purepkg = _packageprefs[policy]
102 except KeyError:
102 except KeyError:
103 raise ImportError(r'invalid HGMODULEPOLICY %r' % policy)
103 raise ImportError(r'invalid HGMODULEPOLICY %r' % policy)
104 assert verpkg or purepkg
104 assert verpkg or purepkg
105 if verpkg:
105 if verpkg:
106 pn, mn = _modredirects.get((verpkg, modname), (verpkg, modname))
106 pn, mn = _modredirects.get((verpkg, modname), (verpkg, modname))
107 try:
107 try:
108 mod = _importfrom(pn, mn)
108 mod = _importfrom(pn, mn)
109 if pn == verpkg:
109 if pn == verpkg:
110 _checkmod(pn, mn, mod)
110 _checkmod(pn, mn, mod)
111 return mod
111 return mod
112 except ImportError:
112 except ImportError:
113 if not purepkg:
113 if not purepkg:
114 raise
114 raise
115 pn, mn = _modredirects.get((purepkg, modname), (purepkg, modname))
115 pn, mn = _modredirects.get((purepkg, modname), (purepkg, modname))
116 return _importfrom(pn, mn)
116 return _importfrom(pn, mn)
General Comments 0
You need to be logged in to leave comments. Login now