Skip to content

Commit

Permalink
No object should ever be False
Browse files Browse the repository at this point in the history
The representation of Tree as a sequence causes boolean coercion to
consider the empty tree to be False, which is nonsensical.

Override __nonzero__ for all object types to return True.

This fixes libgit2#432.
  • Loading branch information
carlosmn committed Oct 6, 2014
1 parent a53d8b2 commit 2031136
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
38 changes: 37 additions & 1 deletion src/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ Object_peel(Object *self, PyObject *py_type)
return wrap_object(peeled, self->repo);
}

PyObject *
Object___nonzero__(PyObject *self)
{
Py_RETURN_TRUE;
}

PyGetSetDef Object_getseters[] = {
GETTER(Object, oid),
GETTER(Object, id),
Expand All @@ -199,6 +205,36 @@ PyMethodDef Object_methods[] = {
{NULL}
};

#if PY_MAJOR_VERSION == 2
static PyNumberMethods Object_as_number = {
0, /* nb_add */
0, /* nb_subtract */
0, /* nb_multiply */
0, /* nb_divide */
0, /* nb_remainder */
0, /* nb_divmod */
0, /* nb_power */
0, /* nb_negative */
0, /* nb_positive */
0, /* nb_absolute */
Object___nonzero__, /* nb_nonzero */
/* There are a lot more, we we don't need any of them */
};
#else
static PyNumberMethods Object_as_number = {
0, /* nb_add */
0, /* nb_subtract */
0, /* nb_divide */
0, /* nb_remainder */
0, /* nb_divmod */
0, /* nb_power */
0, /* nb_negative */
0, /* nb_positive */
0, /* nb_absolute */
Object___nonzero__, /* nb_nonzero */
/* There are a lot more, we we don't need any of them */
};
#endif

PyDoc_STRVAR(Object__doc__, "Base class for Git objects.");

Expand All @@ -213,7 +249,7 @@ PyTypeObject ObjectType = {
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
&Object_as_number, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
Expand Down
9 changes: 8 additions & 1 deletion test/test_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
import unittest

import pygit2
from pygit2 import GIT_OBJ_TREE, GIT_OBJ_TAG, Tree, Tag
from pygit2 import GIT_OBJ_TREE, GIT_OBJ_TAG, GIT_OBJ_BLOB, Tree, Tag
from . import utils


Expand Down Expand Up @@ -78,5 +78,12 @@ def test_invalid_type(self):

self.assertRaises(ValueError, commit.peel, Tag)

def test_nonzero(self):
empty_tree_id = self.repo.TreeBuilder().write()
self.assertTrue(self.repo[empty_tree_id])

empty_blob_id = self.repo.write(GIT_OBJ_BLOB, '')
self.assertTrue(self.repo[empty_tree_id])

if __name__ == '__main__':
unittest.main()

0 comments on commit 2031136

Please sign in to comment.